[英]malloc char array pointer in c gives error
char (*cHighValue)[20];
cHighValue = malloc (X * sizeof(char *));
for (i = 0; i < X; ++i)
{
cHighValue [i] = (char *) malloc (20 * sizeof(char));
}
gives me error : Expression must be a modifiable lvalue, for "cHighValue [i] = (char *) malloc (20 * sizeof(char));" 给我一个错误:表达式必须是可修改的左值,因为“ cHighValue [i] =(char *)malloc(20 * sizeof(char));” Why?
为什么?
cHighValue
is a pointer to a char
array. cHighValue
是指向char
数组的指针。
Allocate as 分配为
cHighValue=malloc(sizeof(char)*20*X);
You are declaring cHighValue as a pointer to an array of 20 chars. 您将cHighValue声明为指向20个字符的数组的指针。 However in your code you use it as being a pointer to array of pointers.
但是,在您的代码中,您将其用作指向指针数组的指针。 What you probably want is to declare cHighValue as an array of pointers and because you allocate it on heap you have to declare it as a pointer to pointer.
您可能想要的是将cHighValue声明为指针数组,并且由于您在堆上分配了cHighValue,因此必须将其声明为指向指针的指针。 Ie:
即:
char **cHighValue;
cHighValue
is a pointer to 20-char array, so cHighValue[i]
is an i-th 20-byte-long array of chars. cHighValue
是指向20个字符的数组的指针,因此cHighValue[i]
是第i个20字节长的char数组。
And the array of chars is not a modifiable lvalue, which could be assigned a pointer value returned by malloc(). 而且char数组不是可修改的左值,可以将其分配给malloc()返回的指针值。
To achieve what you (probably) want, remove parentheses from the cHighValue
declaration. 要实现您(可能)想要的功能,请从
cHighValue
声明中删除括号。
The proper way to allocate a two-dimensional array would be: 分配二维数组的正确方法是:
char (*cHighValue)[Y];
cHighValue = malloc( sizeof(char[X][Y]) );
In particular, you should note: 特别要注意的是:
It's the type of the array, 这是数组的类型
char* cHighValue[20];
cHighValue[0] = malloc (X * sizeof(char *));
for (i = 0; i < X; ++i)
{
cHighValue[i] = (char *) malloc (20 * sizeof(char));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.