我有以下C
个代码:
int *a;
size_t size = 2000*sizeof(int);
a = malloc(size);
这很好用.但如果我有以下几点:
char **b = malloc(2000*sizeof *b);
其中b
的每个元素都有不同的长度.
怎么可能对b
做与我对a
做的相同的事情;也就是说,下面的代码是正确的?
char *c;
size_t size = 2000*sizeof(char *);
c = malloc(size);
我有以下C
个代码:
int *a;
size_t size = 2000*sizeof(int);
a = malloc(size);
这很好用.但如果我有以下几点:
char **b = malloc(2000*sizeof *b);
其中b
的每个元素都有不同的长度.
怎么可能对b
做与我对a
做的相同的事情;也就是说,下面的代码是正确的?
char *c;
size_t size = 2000*sizeof(char *);
c = malloc(size);
首先,您需要分配指针数组,比如char **c = malloc( N * sizeof( char* ))
,然后为每一行分配一个对malloc
的单独调用,可能是在循环中:
/* N is the number of rows */
/* note: c is char** */
if (( c = malloc( N*sizeof( char* ))) == NULL )
{ /* error */ }
for ( i = 0; i < N; i++ )
{
/* x_i here is the size of given row, no need to
* multiply by sizeof( char ), it's always 1
*/
if (( c[i] = malloc( x_i )) == NULL )
{ /* error */ }
/* probably init the row here */
}
/* access matrix elements: c[i] give you a pointer
* to the row array, c[i][j] indexes an element
*/
c[i][j] = 'a';
如果您知道元素的总数(例如N*M
个),则可以在单个分配中执行此操作.