简体   繁体   中英

Error using malloc for multiple 2D arrays

I have the following code segment:

        int  i;

        double** endpt1 = (double**)malloc(sizeof(double*)*(MAXVAR+1));
        for (i=0; i<(MAXVAR+1); i++)
          endpt1[i] = (double*)malloc(sizeof(double)*MAXFILES);

-->     double** endpt2 = (double**)malloc(sizeof(double*)*(MAXVAR+1));
        for (i=0; i<(MAXVAR+1); i++)
          endpt2[i] = (double*)malloc(sizeof(double)*MAXFILES);

I get the following error when compiling in Microsoft Visual Studio 2010 on Windows 7:

error C2143: syntax error: missing ';' before 'type'

error C2065: 'endpt2': undeclared identifier

error C2109: subscript requires array or pointer type

The error points to the line with the arrow. I only get this if I am trying to allocate more than one 2D array in a given file. The error always occurs at the start of the second definition. Any ideas as to why I'm getting this compiler error. Thanks for the help.

In C (C89, anyway), variables are declared at the top of a function. Use:

int i;
double **endpt1;
double **endpt2;
endpt1 = malloc(sizeof(double*)*(MAXVAR+1));
for (i=0; i<(MAXVAR+1); i++)
    endpt1[i] = malloc(sizeof(double)*MAXFILES);

endpt2 = malloc(sizeof(double*)*(MAXVAR+1));
for (i=0; i<(MAXVAR+1); i++)
    endpt2[i] = malloc(sizeof(double)*MAXFILES);

Also, no need to cast the malloc in C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM