A.J
A.J

Reputation: 735

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));" Why?

Upvotes: 0

Views: 1893

Answers (5)

Lundin
Lundin

Reputation: 213306

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. Such a lookup table cannot be used with fundamental functions like memset, memcpy etc.
  • Casting the result of malloc is pointless in C.

Upvotes: 0

Marian
Marian

Reputation: 7472

You are declaring cHighValue as a pointer to an array of 20 chars. 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. I.e.:

char **cHighValue;

Upvotes: 1

CiaPan
CiaPan

Reputation: 9571

cHighValue is a pointer to 20-char array, so cHighValue[i] is an i-th 20-byte-long array of chars.
And the array of chars is not a modifiable lvalue, which could be assigned a pointer value returned by malloc().

To achieve what you (probably) want, remove parentheses from the cHighValue declaration.

Upvotes: 0

angeek86
angeek86

Reputation: 108

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));
}

Upvotes: -1

HelloWorld123456789
HelloWorld123456789

Reputation: 5359

cHighValue is a pointer to a char array.

Allocate as

cHighValue=malloc(sizeof(char)*20*X);

Upvotes: 3

Related Questions