tags:

views:

105

answers:

4

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

How does this give an incompatible declaration in built in function warning and and incompatible types in assignment error in the line where i have declared malloc . According to the syntax of malloc , i shouldnt have any error

A: 

c is an array of pointers. Then you're trying to assign a single pointer to the entire array.

Try

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

Or if you really need 30 elements, each pointing to a malloced array of 30 characters, you'll have to make a loop.

#define CHUNKSIZE 30
int i;
char *c[CHUNKSIZE];
for (i = 0; i < CHUNKSIZE; i++)
{
    c[i] = malloc(CHUNKSIZE * sizeof(char));
}
Mark Rushakoff
still the warning persists..
mekasperasky
A: 

Use this:

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

What you were declaring is an array of 30 char pointers. That's why you were getting incompatible declaration on the malloc sentence.

You could have done this though:

c[0] = (char*)malloc(30*sizeof(char) );
c[1] = (char*)malloc(30*sizeof(char) );
...
Pablo Santa Cruz
+1  A: 

You have declared c as an array. You can't change the value of an array, and an array is not a pointer.

c has the type (char*)[30](i.e. an array of 30 char pointers) , not char* as your cast suggests.

If you're trying to create a dynamically allocated char "array" for 30 chars, use

char *c = malloc(30);

If you really want an array of 30 char pointers, and e.g. allocate space for 30 chars in each of its elements, use

int i;
for(i = 0; i < sizeof c/sizeof c[0]; i++) {
  c[i] = malloc(30);
  if(c[i] == NULL) {
    //handle error
   }
}
nos
+1  A: 

sizeof (char) per definition is always 1, so you don't need to write it.

In C malloc returns a void * so the typecast is unnecessary (even harmful as it suppress useful warnings, don't forget to #include <stdlib.h> or #include <memory.h>).

char char* c[30]; 

declares an array of 30 char *, probably not what you had in mind.

If you wanted an array of 30 char you should have declared

char c[30]; 

and forget about the malloc.

If you wanted a pointer on a char array which happens to have a length of 30, then you should have written:

char *c;
c = malloc(30);
tristopia