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?
5 Answers 5
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.
Comments
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.
Comments
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
1 Comment
c is defined as a pointer to an array of 20 char. Array of pointers to char would be without the parens.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);
Comments
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.
cis already initialized because it is an array.chars, chances are you just wantchar *c=malloc(20);.cis just a pointer, and uninitialized.