简体   繁体   中英

Allocate memory for a pointer to an array in C

I have a pointer array defined declared as

char (*c)[20]

When allocating memory using malloc

c=malloc(sizeof(char)*20);

or

c=(char*)malloc(sizeof(char)*20);

I get a warning as "Suspicious pointer conversion"

Why?

In this declaration

char (*c)[20];

c object has type char (*)[20] .

We know that in C malloc return type is void * and that there is an implicit conversion between void * to any object pointer types.

So c = malloc(whatever_integer_expression) is valid in C. If you get a warning, you are probably using a C++ compiler or you are using a C compiler but forgot to include the stdlib.h standard header.

But c = (char*) malloc(whatever_integer_expression) is not valid C because there is no implicit conversion between char * type and char (*)[20] type. The compiler has to (at least) warn.

First of all, make sure you have stdlib.h included.

Secondly, try rewriting it as

c = malloc(sizeof *c);

I suspect you're getting the diagnostic on the second case because char * and char (*)[20] are not compatible types. Don't know why the first case would complain (at compile-time, anyway) unless you don't have stdlib.h included.

edit

Remember that you will have to dereference the pointer before applying the subscript; that is, your expressions will have to be

(*c)[i] = val;
printf("%c", (*c)[j]);

etc.

Alternately you could write c[0][i] in place of (*c)[i] , but that's probably more confusing if c isn't supposed to act like a 2-d array.

Because you are defining C as a pointer to a static array of chars, not as a pointer to an array of chars, that is, a pointer to the first char.

Change

char (*c)[20];

for

char * c;

a

just use as

c=(char(*)[20])malloc(sizeof(char)*20);

Reason:

1, as @ouah said.

2, in K&R style compiler, the above one is valid and expected.

For an array of 20 characters, counting the NUL terminator, you don't need a pointer

char array[20];

for a pointer to char, you don't need an array

char *pointer;

A pointer to char can point to an array

pointer = array;

to part of the array (assuming no 'funny' business with the NUL terminator)

pointer = &array[10];

or to a bunch of bytes allocated with malloc

pointer = malloc(20);

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