简体   繁体   中英

malloc'ing a multidimensional array in C

I am making a C function to integrate into Python that basically creates a two-dimensional array of chars (each row has constant, known length), reads some data into it, builds a numpy array from it, and returns it to the calling function in Python. I'm not an expert with C, but I believe that in order to preserve the array in memory after exiting the function where it was created, I need to allocate it on the heap with malloc. So I am trying this line:

//rowSize and interleaved are both integers; bytesPerTable is equal to rowSize * interleaved
char arrs[interleaved][rowSize] = (char **)malloc(bytesPerTable * sizeof(char));

Which gives me the compiler error

error: variable-sized object may not be initialized

I'm not sure how to make this work. I want to allocate a block of memory that is the size I need (bytesPerTable) and then organize it into the required two-dimensional array. If I simply declare

char arrs[interleaved][rowSize];

Then it works, but it's on the stack rather than the heap. Can anyone help?

What you need is this:

char** arrs = (char **)malloc(interleaved * sizeof(char*));
for(i = 0; i < bytesPerTable; i++)
    arrs[i] = (char*)malloc(rowSize * sizeof(char));

This: char arrs[interleaved][rowSize]; is just a typical stack allocation.

Do it like this

char (*arrs)[rowSize] = malloc(bytesPerTable);

arrays can't be assigned to, pointers and arrays are really different kinds of objects.

Also:

  • don't cast the return of malloc
  • sizeof(char) is 1 by definition

您需要将其分配给指针,然后可以将其转换为数组。

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