Переопределение различные базовые типы c как исправить

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 Functionn3) Separate Words Functionn4) 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");
  }
}

Nisse Engström's user avatar

asked Nov 30, 2014 at 17:56

Alinur Çağlayan's user avatar

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 Sard's user avatar

Patricio SardPatricio Sard

2,0723 gold badges21 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öm's user avatar

Nisse EngströmNisse Engström

4,71823 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 Functionn");
        printf( "2) Shortest Word Functionn");
        printf( "3) Separate Words Functionn");
        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 enteredn");
                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's user avatar

scopchanov

7,84610 gold badges40 silver badges68 bronze badges

answered Dec 1, 2014 at 2:11

user3629249's user avatar

user3629249user3629249

16.3k1 gold badge16 silver badges17 bronze badges

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("nnnnn");
    // 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();
}

Время на прочтение
1 мин

Количество просмотров 3.5K

Нередко программисты для удобства и краткости переопределяют простейшие типы данных, дают им другие имена. Чаще всего это делаетс примерно так:

typedef unsingned int uint32;
typedef signed int int32;
typedef unsigned char byte;

Ну и так далее. Выступлю с предложением: а почему бы не переопределить простейшие типы, написав для каждого типа свой класс? Расход памяти при хранении таких объектов увеличиться по идее не должен(ессно, виртуальные функции не используем). Например, пишем класс Double, примерно так:

class Double
{
public:
     Double(const Double& value);
     Double          operator+(const Double &right) const;
     Double          operator-(const Double &right) const;
     Bool              IsPositiveInfinity();
     Bool              IsNegativeInfinity();
     
private:
     double _value;
     
}

Или например для типа char:

class Char
{
public:
    Char(char value);

    Bool IsDecimalDigit() const;
    Bool IsLetter() const;
    Bool IsWhiteSpace() const;
    
    Bool operator==(const Char &other);
    Bool operator!=(const Char &other);

private:
    char _value;
};

Таким образом, можно работать с простейшими типами как с объектами, повысить удобочитаемость кода, иметь больше контроля над тем что происходит в программе(например, для подсчета количества умножений, выполняемых над типом double достаточно поместить счетчик в перегруженный оператор).

Оверхеда по производительности/расходу памяти по идее быть не должно.

Пока не могу поделиться плюсами/минусами такого подхода, но постепенно внедряю его в свои C++ библиотеки.

Я использую VS 2010 Ultimate. Набор инструментов v90.

У меня есть DLL и тестовый проект, который статически ссылается на DLL. Внутри DLL находится экспортируемый класс IFilter. Этот интерфейсный класс заключен в пространство имен, использование указанного класса явно прописано с использованием пространства имен, например. void DoSomethingWithDLLTypes (const Observer :: IFilter &);

В течение нескольких месяцев все работало нормально, однако с недавними изменениями вне проекта DLL я начал загружать новые файлы. Когда я добавлял эти файлы в решение, перестраивая с каждым добавлением к тесту, все работало хорошо, а затем внезапно я получил эту ошибку.

C: Program Files Microsoft SDKs Windows v6.0A include Filter.h (53): предупреждение C4099: ‘Observer :: IFilter’: имя типа, впервые увиденное с помощью ‘class’, теперь отображается с ‘struct’ d: proj pub h IFilter.h (12): см. объявление ‘Observer :: IFilter’ C: Program Files Microsoft SDKs Windows v6.0A include Filter.h (183): ошибка C2371: IFilter: переопределение; различные базовые типы C: Program Files Microsoft SDK Windows v6.0A include Filter.h (53): см. объявление ‘IFilter’

Первоначально IFilter не был заключен в пространство имен, поэтому мне пришлось просмотреть все мои файлы (думая, что это решит эту проблему) и обернуть все в пространство имен. Теперь DLL компилируется нормально, однако я по-прежнему получаю ту же ошибку в тестовом проекте. Я даже не знаю, как / почему включается IFilter / Filter.h из MS SDK.

В тестовом проекте используются предварительно скомпилированные заголовки, однако он не использует Windows.h, в любом случае я пошел дальше и сделал там макрос #define lean_and_mean «на всякий случай», ничего не помогло.


Ответы (1)

Одно из мест, где компилятор Visual Studio не соответствует стандарту. В соответствии со стандартом ключевые слова struct и class могут использоваться взаимозаменяемо для объявления одного и того же типа, но VS имеет различную обработку для типов, определенных как struct и class, поэтому требуется, чтобы вы последовательно использовали одно или другое ключевое слово для вашего типа.

Теперь ошибка указывает на два, казалось бы, не связанных между собой файла заголовков, так что это может быть просто совпадение имен:

C:Program FilesMicrosoft SDKsWindowsv6.0AincludeFilter.h
d:projpubhIFilter.h

В первом заголовке есть class Observer::IFilter, а во втором — struct Observer::IFilter. Если они одинаковы, то вы должны исправить проект, чтобы он не включал несколько заголовков с определением, если это разные вещи, вы должны сделать имена уникальными (добавить пространство имен)

person
David Rodríguez — dribeas
  
schedule
01.08.2012

Понравилась статья? Поделить с друзьями:
  • План продаж как составить продажа квартир
  • Как на биглионе найти купленный купон
  • Как найти своего депутата в воронеже
  • Как найти свою очередь на квартиру
  • Как найти продукцию в реестре минпромторга