简体   繁体   English

c中的malloc char数组指针给出错误

[英]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: 特别要注意的是:

  • Do not use multiple mallocs, because they will not give you a true 2D array, but instead a fragmented pointer-to-pointer lookup table which is allocated all over the heap. 不要使用多个malloc,因为它们不会为您提供真正的2D数组,而是分配给整个堆的零散的指针对指针查找表。 Such a lookup table cannot be used with fundamental functions like memset, memcpy etc. 这样的查找表不能与诸如memset,memcpy等基本功能一起使用。
  • Casting the result of malloc is pointless in C. 在C中强制转换malloc的结果毫无意义。

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.

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