Hick
Hick

Reputation: 36404

incompatible declaration in built in function malloc and incompatible types in assignment error in c

 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

Upvotes: 1

Views: 4352

Answers (5)

faizan
faizan

Reputation: 11

you have to #include <stdlib.h>

Upvotes: 1

Patrick Schl&#252;ter
Patrick Schl&#252;ter

Reputation: 11841

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

Upvotes: 0

nos
nos

Reputation: 229098

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

Upvotes: 1

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181280

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

Upvotes: 0

Mark Rushakoff
Mark Rushakoff

Reputation: 258188

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

Upvotes: 0

Related Questions