Error new undeclared first use in this function

This code is for Hamiltonian Cycle I can't solve this error: In function ‘hamCycle’: error: ‘new’ undeclared (first use in this function) int *path = new int [V]; ...

This code is for Hamiltonian Cycle
I can’t solve this error:

    In function ‘hamCycle’:
   error: ‘new’ undeclared (first use in this function)
         int *path = new int [V];
                     ^
 note: each undeclared identifier is reported only once for each function it appears in
 error: expected ‘,’ or ‘;’ before ‘int’
         int *path = new int [V];
                         ^

the Hamiltonian Cycle code is:

/*
 * C Program to Find Hamiltonian Cycle
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define V 5

void printSolution(int path[]);

/* 
 * check if the vertex v can be added at index 'pos' in the Hamiltonian Cycle 
 */
bool isSafe(int v, bool graph[V][V], int path[], int pos)
{
    if (graph [path[pos-1]][v] == 0)
        return false;
   for (int i = 0; i < pos; i++)
        if (path[i] == v)
            return false;
    return true;
}

/* solve hamiltonian cycle problem */
bool hamCycleUtil(bool graph[V][V], int path[], int pos)
{
    if (pos == V)
    {
        if (graph[ path[pos-1] ][ path[0] ] == 1)
            return true;
        else
            return false;
    }

    for (int v = 1; v < V; v++)
    {
        if (isSafe(v, graph, path, pos))
        {
            path[pos] = v;
            if (hamCycleUtil (graph, path, pos+1) == true)
                return true;
            path[pos] = -1;
        }
    }
    return false;
}

/* solves the Hamiltonian Cycle problem using Backtracking.*/
bool hamCycle(bool graph[V][V])
{
    int *path = new int [V];
    for (int i = 0; i < V; i++)
        path[i] = -1;
    path[0] = 0;
    if (hamCycleUtil(graph, path, 1) == false)
    {
      printf("nSolution does not exist");
        return false;
    }
    printSolution(path);
    return true;
}

/* Main */
void printSolution(int path[])
{
    printf("Solution Exists:");
    printf(" Following is one Hamiltonian Cycle n");
    for (int i = 0; i < V; i++)
        printf(" %d",path[i]);
    printf(" %d",path[0]);
}

int main()
{
   /* Let us create the following graph
      (0)--(1)--(2)
       |   /    |
       |  /     |
       | /      |
      (3)-------(4)    */
   bool graph1[V][V] = {{0, 1, 0, 1, 0},
                      {1, 0, 1, 1, 1},
                      {0, 1, 0, 0, 1},
                      {1, 1, 0, 0, 1},
                      {0, 1, 1, 1, 0},
                     };
   hamCycle(graph1);

   /* Let us create the following graph
      (0)--(1)--(2)
       |   /    |
       |  /     |
       | /      |
      (3)       (4)    */
    bool graph2[V][V] = {{0, 1, 0, 1, 0},
                      {1, 0, 1, 1, 1},
                      {0, 1, 0, 0, 1},
                      {1, 1, 0, 0, 0},
                      {0, 1, 1, 0, 0},
                     };
    hamCycle(graph2);
    return 0;
}

How can I solve this?

  • Forum
  • Beginners
  • [SOLVED]»new» operator compile error

[SOLVED]»new» operator compile error

Hi all, I hope you can help me with this:

when using the ‘new’ operator in this line:

char *numbuffer = new char[len+1]

(with len being defined, no worries there), I get the ‘undeclared identifier’ compile error:

‘new’ undeclared (first use in this function)

Somehow, this scares me, since I think I used the operator correctly.

Edit: I hate how Google gives me no results before writing posts here and how it brings me exactly what I needed after I’ve posted the post.

I just used malloc and free instead:

1
2
char *numbuffer;
numbuffer = (char*) malloc(len+1);    //len is defined beforehand 

and in the function that calls the one which contains the snippet above:

1
2
3
char *strTrainno = getTrainno(buffer);     //getTrainno is the name of the function mentioned above, buffer a parameter passed to the current fn
//do stuff with strTrainno
free(&strTrainno);

Last edited on

Just out of interest have you thought about why new didn’t work or gave that error??

I guess I forgot to #include <new> .

Last edited on

Just out of curiosity, which compiler are you using? I have only ever seen a problem like that when someone tried to compile C++ with a C compiler.

Dev C++ 4.9.9.2’s standard compiler (first time working with this IDE, previous C++ coding has been done in Apple’s XCode 2.x, on PPC macs), which, according to Dev C++’s offline help, is MingW32.

I have another question, though. What does one do when s/he is the only one coding and there is literally noone nearby (physically) to ask to look at the code? Because I don’t want to litter any forum with requests which basically boil down to ‘read my code and tell me where my typos are’ (I’ve done so here already, and I’m sorry for it).

Last edited on

@bnbertha that’s what I was trying to angle around to eventaully — that he might be using a c compiler instead of c++ one

Topic archived. No new replies allowed.

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include <windows.h>
#include <tchar.h>
#define  DIB_RGB(r, g, b) 
((DWORD)((r & 0xFF) << 16) | ((g & 0xFF) << 8) | (b & 0xFF)) 
 
void fill_rect(__int32*, int, int, int, int, int, DWORD);
 
 
 
 
 
// 24/32 бит
BOOL  SaveArrFile(const TCHAR* filename, const __int32* arr, 
                         int width, int height, int bpp = 24){
 
    if((bpp < 24) || (bpp > 32)) // только 24/32 бит
         return FALSE;
 
    DWORD p_row = (DWORD)((width * bpp + 31) & ~31) / 8uL;
    DWORD size  = (DWORD)(height * p_row);
 
    // формируем файловый заголовок
    BITMAPFILEHEADER  hdr;
    ZeroMemory(&hdr, sizeof(BITMAPFILEHEADER));
    hdr.bfType    = 0x4D42;
    hdr.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
    hdr.bfSize    = hdr.bfOffBits + size;
 
    // заголовок описателя растра
    BITMAPINFO dib;
    ZeroMemory(&dib, sizeof(BITMAPINFO));
    dib.bmiHeader.biSize        = sizeof(BITMAPINFOHEADER);
    dib.bmiHeader.biBitCount  = bpp;
    dib.bmiHeader.biCompression  = BI_RGB;
    dib.bmiHeader.biPlanes  = 1u;
    dib.bmiHeader.biWidth   = (long)width;
    dib.bmiHeader.biHeight  = (long)-height;
    dib.bmiHeader.biSizeImage   = size;
    dib.bmiHeader.biXPelsPerMeter = 11811L;
    dib.bmiHeader.biYPelsPerMeter = 11811L;
    dib.bmiHeader.biClrImportant  = 0uL;
    dib.bmiHeader.biClrUsed  = 0uL;
 
    // далее запись в файл
    HANDLE fp = CreateFile(filename, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, 
                                   CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if(fp == INVALID_HANDLE_VALUE)
           return FALSE;
 
    // записываем заголовки...
    DWORD  dwr = 0uL;
    WriteFile(fp, (LPCVOID)&hdr, sizeof(BITMAPFILEHEADER), &dwr, NULL);
    WriteFile(fp, (LPCVOID)&dib.bmiHeader, sizeof(BITMAPINFOHEADER), &dwr, NULL);
 
    // запись массива пикселей
    if(bpp == 32) // 32-бит
           WriteFile(fp, (LPCVOID)arr, size, &dwr, NULL);
    else if(bpp == 24) { // 24-бит с дополнением до 32-разрядной границы
 
          BYTE   nil = 0u;
          int   cb  = sizeof(RGBQUAD);
          int  align = ((cb - ((width*bpp + 7) / 8) % cb) % cb);
        
          for(int y = 0; y < height; y++) {
               for(int x = 0; x < width; x++) 
                    WriteFile(fp, (LPCVOID)&arr[y*width+x], sizeof(RGBTRIPLE), &dwr, NULL);
            
                    for(int i = 0; i < align; i++) // до границы DWORD
                          WriteFile(fp, (LPCVOID)&nil, sizeof(BYTE), &dwr, NULL);
               }
   }
 
   FlushFileBuffers(fp);
   CloseHandle(fp);
   return TRUE;
}
 
 
 
 
 
int  main(void) {
    //массив пикселей
    __int32 arr[111*222] = {0};
    int cw = 222; 
    int ch = 111;
 
    // нарисуем что-нибудь
    DWORD rgb;
    int   sx  = ch / 5;
    int   sy  = cw / 10;
    for(int y = 0; y < 5; y++) {
         for(int x = 0; x < 10; x++) {
              rgb = DIB_RGB(rand()%2*0xFF, rand()%2*0xFF, rand()%2*0xFF);
              fill_rect(arr, cw, x*sx, y*sy, sx, sy, rgb);
        }
    }
 
 
    // сохраняем в файл
    if(SaveArrFile(_T("grid.bmp"), arr, cw, ch, 24))
           _putts(_T("Good save file."));
    else
           _putts(_T("Error save file !"));
 
    _gettchar();
    return 0;
}
 
 
 
// вывод прямоугольника
void fill_rect(__int32* arr, int width, int x, int y, int cx, int cy, DWORD color){
     for(int r = y; r <= (y + cy); r++) {
          for(int c = x; c <= (x + cx); c++)
               arr[r*width + c] = color;
     }
}

gcc -ansi -pedantic -Wall -g -lm -o p3 p3.c
p3.c: In function 'list_insert':
p3.c:42: error: 'new' undeclared (first use in this function)
p3.c:42: error: (Each undeclared identifier is reported only once
p3.c:42: error: for each function it appears in.)
p3.c:43: error: expected expression before ')' token
make: *** [p3] Error 1

struct list_element { float element; struct list_element* next;};
typedef struct list_element node;

node* list_insert(node* node, float value){
    node* new;
    new=(node*)malloc(sizeof(node*));
    new->element=value;
    if (node) { /* needs to be atomic */
        new->next=node->next;
        node->next=new;
    } else { 
        new->next=NULL;
        node=new;
    }
    return node;
}

PS why isn’t there a standard list like there is in C++? I freaking hate having to write my own little list in C land because my alg needs one.

here it is in MSVC8

p3.c(42) : error C2065: 'new' : undeclared identifierp3.c(42) : error C2296: '*' : illegal, left operand has type 'node *'p3.c(43) : error C2059: syntax error : ')'p3.c(44) : error C2223: left of '->element' must point to struct/unionp3.c(46) : error C2223: left of '->next' must point to struct/unionp3.c(47) : warning C4047: '=' : 'list_element *' differs in levels of indirection from 'int'p3.c(49) : error C2223: left of '->next' must point to struct/unionp3.c(50) : warning C4047: '=' : 'node *' differs in levels of indirection from 'int'

I know it’s C, but you might want to try not using a word that’s reserved in C++. i.e. not ‘new’ but use ‘newNode’.

otherwise:

new=(node*)malloc(sizeof(node*));

should be

new=(node*)malloc(sizeof(node));

-me

ah thank you.

also im a dummy, my error was trying to have a local variable ‘node’ when i already have a global struct ‘node’. go me.

This:

Quote:my error was trying to have a local variable ‘node’ when i already have a global struct ‘node’. go me.

in addition to:

Quote:PS why isn’t there a standard list like there is in C++? I freaking hate having to write my own little list in C land because my alg needs one.

is why C is very much disliked.

C simply doesn’t have some things. Like a useful standard library. Or namespaces.

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Variables: A variable is the name given to a memory location. It is the basic unit of storage in a program.

    • The value stored in a variable can be changed during program execution.
    • A variable is only a name given to a memory location, all the operations done on the variable effects that memory location.
    • All the variables must be declared before use.

    How to declare variables?
    We can declare variables in common languages (like C, C++, Java etc) as follows:
    Variables in Java

    where:
    datatype: Type of data that can be stored in this variable.
    variable_name: Name given to the variable.
    value: It is the initial value stored in the variable.
    

    How to avoid errors while creating variables?

    1. The identifier is undeclared: In any programming language, all variables have to be declared before they are used. If you try to use the name of a such that hasn’t been declared yet, an “undeclared identifier” compile-error will occur.

      Example:

      #include <stdio.h>

      int main()

      {

          printf("%d", x);

          return 0;

      }

      Compile Errors:

      prog.c: In function 'main':
      prog.c:5:18: error: 'x' undeclared (first use in this function)
           printf("%d", x);
                        ^
      prog.c:5:18: note: each undeclared identifier is reported
           only once for each function it appears in
      
    2. No initial value is given to the variable: This error commonly occurs when the variable is declared, but not initialized. It means that the variable is created but no value is given to it. Hence it will take the default value then. But in C language, this might lead to error as this variable can have a garbage value (or 0) as its default value. In other languages, 0 will be its default value.

      Example:

      #include <stdio.h>

      int main()

      {

          int x;

          printf("%d", x);

          return 0;

      }

      Output:

      0
      
    3. Using variable out of its Scope: Scope of a variable is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e.scope of a variable can be determined at compile time and independent of the function call stack.

      Example:

      #include <stdio.h>

      int main()

      {

          {

              int x = 5;

          }

          printf("%d", x);

          return 0;

      }

      Compile Errors:

      prog.c: In function 'main':
      prog.c:5:18: error: 'x' undeclared (first use in this function)
           printf("%d", x);
                        ^
      prog.c:5:18: note: each undeclared identifier is reported
           only once for each function it appears in
      

      How to Correct the above code: Declare the variable x before using it in the outer scope. Or you can use the already defined variable x in its own scope

      Example:

      #include <stdio.h>

      int main()

      {

          {

              int x = 5;

              printf("%d", x);

          }

          return 0;

      }

      Output:

      5
      
    4. Creating a variable with an incorrect type of value: This arises due to the fact that values are implicitly or explicitly converted into another type. Sometimes this can lead to Warnings or errors.

      Example:

      #include <stdio.h>

      int main()

      {

          char* x;

          int i = x;

          printf("%d", x);

          return 0;

      }

      Warning:

      prog.c: In function 'main':
      prog.c:7:13: warning: initialization makes integer
       from pointer without a cast [-Wint-conversion]
           int i = x;
                   ^
      

    Выкладываю исходный код

    ///////////////////////////////////////////////////// Это то что я заполняю
    struct fnode { //структура для
      char *filelist[100];
      long countname;
      long inode;
    };

    struct fnode myfiles[500];
    long countfile = 0;

    ///////////////////////////////////////////////////// Это где я вызывю ф-ю заполнения

    void printdir(char *dir,int depth){
      DIR *dirpath;
      struct dirent *entry;
      struct stat statbuf;
      if((dirpath = opendir(dir)) == NULL){
        fprintf(stderr,»Не могу открыть каталог %s
    «,dir);
        return;
      }
      chdir(dir);
      while((entry = readdir(dirpath)) != NULL){
         memset(&statbuf,0,sizeof(statbuf));
         lstat(entry->d_name,&statbuf);
        if(!S_ISDIR(statbuf.st_mode)){
          initFileData(entry->d_name,statbuf.st_ino); // вот здес я заполняю глобальный массив Массив заполняется не так как надо
          getData(entry->d_name,statbuf.st_ino); // для теста
            printf(«%*s %d %s — этот файл имеет %d жестких ссылок
    «,depth,» «,statbuf.st_ino,entry->d_name,statbuf.st_nlink);  //а здесь нормально все отображается
        }
         if(S_ISDIR(statbuf.st_mode)){
            if(strcmp(«.»,entry->d_name) == 0 || strcmp(«..»,entry->d_name) == 0) continue;
            printf(«%*s%s — это каталог
    «,depth,» «,entry->d_name);
            printdir(entry->d_name,depth+4);
         }
      }//endwhile
      chdir(«..»);
      closedir(dirpath);
    }

    ///////////////////////////////////////////////////// Чем я заполняю
    initFileData(entry->d_name,statbuf.st_ino);
    getData(entry->d_name,statbuf.st_ino); // это так для теста Выходит так что имена файлов получаются какие то нетакие

    ///////////////////////////////////////////////////// Это ф-ии которые отображают заполненные данные (массивы)

         printdir(topdir,0);
         outData();

    ///////////////////////////////////////////////////////////////////////////////////

    Здесь привожу полный текст исходного кода Пож-ста не поленитесь откомпильте В чем ошибка Программной ошибки так таковой я не вижу Ну никак не могу понять почему не так заполняется массив


    Пользователь решил продолжить мысль 04 Декабря 2009, 16:53:16:


    У меня еще один вопрос возник Си подерживает ссылку?

    Понравилась статья? Поделить с друзьями:

    Читайте также:

  • Error new types may not be defined in a return type
  • Error new encoding utf8 is incompatible with the encoding of the template database win1251
  • Error networkmanager is not running
  • Error forming pointer to reference type
  • Error networkerror when attempting to fetch resource перевод

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии