I get the error code c2371, for the functions; seperate, longest and shortest. I think its about the input arguments.
error C2371: 'seperate' : redefinition; different basic types
error C2371: 'shortest' : redefinition; different basic types
error C2371: 'longest' : redefinition; different basic types
Code:
#include <stdio.h>
int main(void)
{
char msg[41];
int selector = 0;
printf("Alinur Caglayan - 18050127622 - Lab Work 5 ");
printf("Please enter a string message with maximum of 40 characters: ");
gets(msg);
printf("Please select one of the following functions:\n1) Longest Word Function");
printf("\n2) Shortest Word Function\n3) Separate Words Function\n4) Exit: ");
scanf("%d", &selector);
if(selector == 1)
{
longest(msg);
}
else if(selector == 2)
{
shortest();
}
else if(selector == 3)
{
seperate();
}
else if(selector == 4)
{
return 0;
}
else
{
printf("\nPlease enter a valid integer!\n");
scanf("%d", selector);
}
}
char longest(msg)
{
char *temp = msg, *word = msg, *max = msg;
int increment = 0, incrementmax = 0;
do {
if(!(*temp & ~32))
{
if(increment > incrementmax)
{
incrementmax = increment;
max = word;
}
increment = 0;
}
else if(!increment++)
{
word = temp;
}
}
while(*temp++ != 0);
for(temp = max; (*temp & ~32); )
{
printf("%c", *temp++);
}
}
char shortest(msg)
{
char *temp = msg, *word = msg, *max = msg;
int increment = 0, incrementmax = 0;
do {
if(!(*temp & ~32))
{
if(increment > incrementmax)
{
incrementmax = increment;
max = word;
}
increment = 0;
}
else if(!increment++)
{
word = temp;
}
}
while(*temp++ != 0);
for(temp = max; (*temp & ~32); )
{
printf("%c", *temp++);
}
}
char seperate(msg)
{
char *temp = msg;
int i;
printf("Alinur Caglayan - 18050127622 - Lab Work 5 ");
printf("Please enter a string message with maximum of 40 characters: ");
gets(msg);
for(i=0; i < 41; i++)
{
if(*temp & ~32)
{
printf("\n");
}
else
{
printf("%c", temp);
}
system("pause");
}
}
asked Nov 30, 2014 at 17:56
5
There are a lot of errors.
You should declare your functions before main like this:
char shortest(char msg[41]);
char longest(char msg[41]);
or if you don’t want to declare them you could define them before main…
Also you have a:
scanf("%d", selector);
While it should be:
scanf("%d", &selector);
And all your functioncs should return a char too.
Edited: Another thing is that you define your functions like:
char longest(msg) {
...
}
But you have to specify the type of the argument, like this.
char longest(char msg[41]) {
...
}
answered Nov 30, 2014 at 18:22
Patricio SardPatricio Sard
2,1023 gold badges22 silver badges52 bronze badges
You are calling your functions without first declaring their types. This is not allowed in the two latest versions of the C standard, and should result in a diagnostic message.
However, if your compiler complies with an older standard (or none at all), calling an undeclared function will cause the compiler to provide its own declaration with a return type that defaults to int
. When you later define the functions to have a different return type, the compiler warns you about the mismatch.
You should always declare your functions (i.e. the return type and the types of its parameters), or in trivial cases, define your functions (i.e. with function body) before you call them.
answered Nov 30, 2014 at 18:11
Nisse EngströmNisse Engström
4,73823 gold badges27 silver badges42 bronze badges
The following only corrects the basic syntax, without looking into what that sub functions are actually doing:
#include <stdio.h>
#include <stdlib.h>
// prototypes
void longest ( char * );
void shortest( char * );
void seperate( char * );
int main(void)
{
char msg[41];
int selector = 0;
printf("Alinur Caglayan - 18050127622 - Lab Work 5 ");
printf("Please enter a string message with maximum of 40 characters: ");
if( NULL == fgets(msg, sizeof(msg), stdin) )
{
perror( "fgets failed" );
exit( EXIT_FAILURE );
}
int done = 0; // indicate not done
while(!done)
{
printf("Please select one of the following functions:\n");
printf( "1) Longest Word Function\n");
printf( "2) Shortest Word Function\n");
printf( "3) Separate Words Function\n");
printf( "4) Exit:\n");
if( 1 != scanf(" %d", &selector) )
{
perror( "scanf failed" );
exit( EXIT_FAILURE );
}
switch( selector )
{
case 1:
longest(msg);
break;
case 2:
shortest(msg);
break;
case 3:
seperate(msg);
break;
case 4:
done = 1; // cause loop to exit
break;
default:
printf("\nERROR: invalid selection entered\n");
break;
} // end switch
} // end while
return(0);
} // end funtion: main
void longest( char* msg)
{
char *temp = msg, *word = msg, *max = msg;
int increment = 0, incrementmax = 0;
do {
if(!(*temp & ~32))
{
if(increment > incrementmax)
{
incrementmax = increment;
max = word;
} // end if
increment = 0;
}
else if(!increment++)
{
word = temp;
} // end if
} while(*temp++ != 0);
for(temp = max; (*temp & ~32); )
{
printf("%c", *temp++);
}
} // end function: longest
void shortest(char* msg)
{
char *temp = msg, *word = msg, *max = msg;
int increment = 0, incrementmax = 0;
do {
if(!(*temp & ~32))
{
if(increment > incrementmax)
{
incrementmax = increment;
max = word;
} // end if
increment = 0;
}
else if(!increment++)
{
word = temp;
}
} while(*temp++ != 0);
for(temp = max; (*temp & ~32); temp++)
{
printf("%c", *temp);
}
} // end function: shortest
void seperate(char* msg)
{
char *temp = msg;
int i;
printf("Alinur Caglayan - 18050127622 - Lab Work 5 ");
printf("Please enter a string message with maximum of 40 characters: ");
if( NULL == fgets(msg, sizeof(msg), stdin) )
{
perror( "fgets failed" );
exit( EXIT_FAILURE );
}
for(i=0; i < 41; i++)
{
if(*temp & ~32)
{
printf("\n");
}
else
{
printf("%c", temp);
} // end if
system("pause");
} // end for
} // end function: seperate
scopchanov
7,98610 gold badges40 silver badges69 bronze badges
answered Dec 1, 2014 at 2:11
user3629249user3629249
16.4k1 gold badge16 silver badges17 bronze badges
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
void aboutH() { printf("Information on hard disks"); int j; _int64 FreeBytesAvailable; _int64 TotalNumberOfBytes; _int64 TotalNumberOfFreeBytes; LPCWSTR disk = L"I:\"; LPCWSTR diski[26] = { L"A:\",L"B:\",L"C:\",L"D:\",L"E:\",L"F:\",L"G:\",L"H:\",L"I:\",L"J:\",L"K:\",L"L:\",L"M:\",L"N:\" ,L"O:\",L"P:\",L"Q:\",L"R:\",L"S:\",L"T:\",L"U:\",L"V:\",L"W:\",L"X:\",L"Y:\",L"Z:\" }; for (j = 0; j<26; j++) { TotalNumberOfBytes = NULL; TotalNumberOfFreeBytes = NULL; FreeBytesAvailable = NULL; GetDiskFreeSpaceEx(diski[j], (PULARGE_INTEGER)&FreeBytesAvailable, (PULARGE_INTEGER)&TotalNumberOfBytes, (PULARGE_INTEGER)&TotalNumberOfFreeBytes); if (GetDriveType(diski[j]) == DRIVE_FIXED) { if (TotalNumberOfBytes != 0) { printf("%s: ", diski[j]); printf("Total Memory %lf Gb, ", (long double)TotalNumberOfBytes / 1024 / 1024 / 1024); printf("Free %lf Gb\n", (long double)TotalNumberOfFreeBytes / 1024 / 1024 / 1024); } else { printf("%s: ", diski[j]); printf("inactive disk\n"); } } else { continue; } } _getch(); fMenu(); } |
I have the following code:
#include <stdio.h>
#include <stdlib.h>
// helping
void sortint(int numbers[], int array_size)
{
int i, j, temp;
for (i = (array_size - 1); i > 0; i--)
{
for (j = 1; j <= i; j++)
{
if (numbers[j-1] > numbers[j])
{
temp = numbers[j-1];
numbers[j-1] = numbers[j];
numbers[j] = temp;
}
}
}
}
// exer1 - A
void sort(int** arr, int arrsize) {
int i = 0;
// sort....
for(; i < arrsize; ++i) {
sortint((*(arr+i))+1, **(arr+i));
}
}
// Exer1 - B
void print(int** arr, int arrsize) {
int i = 0, j, size, *xArr;
for(; i < arrsize; ++i) {
size = **(arr+i);
xArr = *(arr+i);
printf("size: %d: ", size);
// print elements
for(j = 1; j <= size; ++j) printf("[%d], ", *(xArr+j));
printf("\n");
}
}
// Exer2:
void exera() {
int* ptr = (int*)malloc(sizeof(int));
if(!ptr) exit(-1);
eb(ptr);
free(ptr);
}
void eb(int* ptr) {
int* arr = (int*) malloc(sizeof(int) * (*ptr));
int i = 0;
for(; i < *ptr; ++i) scanf("%d", arr+i);
ec(arr, *ptr);
}
void ec(int* arr, int size) {
int i;
sortint(arr, size);
for(i = 0; i < size; ++i) printf("[%d], ", *(arr+i));
}
int main() {
// Exer1:
int a[] = {4,3,9,6,7};
int b[] = {3,2,5,5};
int c[] = {1,0};
int d[] = {2,1,6};
int e[] = {5,4,5,6,2,1};
int* list[5] = {a,b,c,d,e};
sort(list, 5); // A
print(list, 5); // B
printf("\n\n\n\n\n");
// Exer2:
exera();
fflush(stdin);
getchar();
return 0;
}
I get these errors:
Error 2 error C2371: 'eb' : redefinition; different basic types
source.c 56
Error 4 error C2371: 'ec' : redefinition; different basic types
source.c 63
Warning 1 warning C4013: 'eb' undefined; assuming extern returning int
source.c 52
Warning 3 warning C4013: 'ec' undefined; assuming extern returning int
source.c 60
I tried to change function names — for nothing.
Why is that error is being shown? I’m using Visual C++ Express 2010.
Перейти к контенту
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
void aboutH() { printf("Information on hard disks"); int j; _int64 FreeBytesAvailable; _int64 TotalNumberOfBytes; _int64 TotalNumberOfFreeBytes; LPCWSTR disk = L"I:"; LPCWSTR diski[26] = { L"A:",L"B:",L"C:",L"D:",L"E:",L"F:",L"G:",L"H:",L"I:",L"J:",L"K:",L"L:",L"M:",L"N:" ,L"O:",L"P:",L"Q:",L"R:",L"S:",L"T:",L"U:",L"V:",L"W:",L"X:",L"Y:",L"Z:" }; for (j = 0; j<26; j++) { TotalNumberOfBytes = NULL; TotalNumberOfFreeBytes = NULL; FreeBytesAvailable = NULL; GetDiskFreeSpaceEx(diski[j], (PULARGE_INTEGER)&FreeBytesAvailable, (PULARGE_INTEGER)&TotalNumberOfBytes, (PULARGE_INTEGER)&TotalNumberOfFreeBytes); if (GetDriveType(diski[j]) == DRIVE_FIXED) { if (TotalNumberOfBytes != 0) { printf("%s: ", diski[j]); printf("Total Memory %lf Gb, ", (long double)TotalNumberOfBytes / 1024 / 1024 / 1024); printf("Free %lf Gbn", (long double)TotalNumberOfFreeBytes / 1024 / 1024 / 1024); } else { printf("%s: ", diski[j]); printf("inactive diskn"); } } else { continue; } } _getch(); fMenu(); } |
KarnstenK sort of gives you the correct answer but it needs expanding
There are two units both trying to define «int8_t» and one of those is part of the standard C library it will be in «StdInt.H» in the system include directory of any C99 compliant compiler.
Fixed width integer types (since C99)
http://en.cppreference.com/w/c/types/integer[^]
As you are using the standard libraries that you can not get around that unit.
You need to find the none system unit that is also trying to define int8_t and see if you can fix it. There are a number of ways to do that from using #ifndef thru to renaming the non standard unit using of int8_t to a new name.
However to start you need to find what the second unit is that contains the name int8_t because it really shouldn’t be defining that particular name and personally I would fix that unit.
- Remove From My Forums
Ошибки переопределения переменных
-
Вопрос
-
В проекте подключаю два заголовочных файла из поставки MS Visual Studio 8:
#include <NTSecAPI.h> #include <winternl.h>
При сборке проекта возникают ошибки, связанные с переопределением переменных в этих файлах:
2>c:program files (x86)microsoft visual studio 8vcplatformsdkincludewinternl.h(99) : error C2371: 'STRING' : redefinition; different basic types 2> c:program files (x86)microsoft visual studio 8vcplatformsdkincludentsecapi.h(2063) : see declaration of 'STRING' 2>c:program files (x86)microsoft visual studio 8vcplatformsdkincludewinternl.h(114) : error C2371: 'UNICODE_STRING' : redefinition; different basic types 2> c:program files (x86)microsoft visual studio 8vcplatformsdkincludentsecapi.h(2062) : see declaration of 'UNICODE_STRING'
Как решить эту проблему?
В интернете нашла только ситуации переопределения переменных в пользовательском коде (т.е. в том коде, который программист написал сам).
Ответы
-
Здравствуйте.
Для решения подобных проблем используйте пространства имен:
#include "stdafx.h" #include <windows.h> namespace myunistr { #include <Ntsecapi.h> } namespace mystr { #include <winternl.h> } int _tmain(int argc, _TCHAR* argv[]) { mystr::STRING str; myunistr::UNICODE_STRING unistr; return 0; }
Для связи [mail]
-
Предложено в качестве ответа
30 марта 2012 г. 6:38
-
Помечено в качестве ответа
Abolmasov Dmitry
2 апреля 2012 г. 13:25
-
Предложено в качестве ответа
#visual-c
#visual-c
Вопрос:
class DATE
{
public:
void extend_date(int,int,int,int );
int diff(int, int, int, int, int, int);
int day,mon,year;
};
void DATE ::extend_date(int d1, int m1, int y1, int days)
{
...
}
int DATE :: diff(int d1, int m1, int y1, int d2, int m2, int y2)
{
...
}
У меня ошибка — ДАТА класса
Переопределение; другой базовый тип
Кто-нибудь, пожалуйста, помогите мне?
Комментарии:
1. Скорее всего, проблема в том, что заголовки Windows уже определяют тип с именем
DATE
. Рассмотрите возможность использования другого имени для вашего класса.2. Да, это решено, спасибо.
3. зак и @IgorTandetnik: Пожалуйста, ответьте и примите ответ.
Я пытаюсь использовать идиому PIMPL — скрывая детали реализации класса от пользователя. Я также хочу сделать еще один шаг, скрыв фактическое имя класса реализации. Это также должно позволить мне быстро заменить класс реализации, изменив одну строку кода.
Мой подход таков:
В файле заголовка я определяю Public
класс и объявляю прокси-имя. Implementation
того, что будет классом реализации.
Xh:
#pragma once
namespace detail {
class Implementation;
}
class Public {
public:
Public();
void foo();
private:
detail::Implementation* data;
};
В рамках реализации я определяю фактический класс реализации (под другим именем), а затем использую typedef, чтобы установить Implementation
таким классом по своему выбору.
x.cpp
#include <iostream>
#include "X.h"
namespace {
class Private { //the actual implementation class. Everything about it, including its name, should be hidden
public:
void foo() { std::cout << "Hello world!" << std::endl; }
};
}
namespace detail {
typedef Private Implementation; //set Private as the actual Implementation
}
Public::Public() : data(new detail::Implementation()) {}
void Public::foo() {
data->foo();
}
К сожалению, я получаю сообщение об ошибке:
error C2371: 'detail::Implementation': redefinition; different basic types
в строке typedef
. Но в обоих местах (файлы cpp и h) я объявляю класс; один с определением, другой без. Так что я пропущу?
Если typedef
(или С++ 11 using
) не может использоваться по причинам, как еще я могу достичь своей цели?
Я видел похожие вопросы об одной и той же ошибке, но все, что я нашел, это некоторые тривиальные ошибки, такие как:
- Ошибка C2371: переопределение; разные базовые типы — почему? : использует имя до его определения
- переопределение; различные базовые типы (typedef struct) или переопределение различных базовых типов => typedef: включен охранник