2

I have a pointer to a character array:

space=(char**)calloc(100000,sizeof(char*));
for(i=0;i<100000;i++){
    space[i]=(char*)calloc(1,sizeof(char));
}

such that when I use the following command

printf("%s\n",space[0]);

I get "a b c d e"

I want to assign "a b c d e" to

char c[10];

such that

printf("%s",c) yields

"a b c d e"

but when I try

c=space[0]

I get the following error:

incompatible types in assignment

What am I doing wrong?

3
  • 1
    You can't assign to an array. Use a char * instead, or use strcpy to copy the contents of space[0] into c. Commented Aug 17, 2012 at 19:46
  • Don't cast the return value of malloc in C Commented Aug 17, 2012 at 20:04
  • I don't see how you can get "a b c d e" from that printf with the above code. And I don't see what exactly you're trying to do. Commented Aug 17, 2012 at 20:29

2 Answers 2

2

First, you need to allocate enough space to hold the entire string at location space[0]. Currently you are allocating a single character. After you do that you would use strcpy() to copy the string into the newly allocated buffer.

space=(char**)calloc(100000,sizeof(char*));
...
space[0]=(char*)calloc(10,sizeof(char));
strcpy(space[0], "a b c d e");

PS: Don't forget to free() any prior allocated strings at space[0] (like the one you create in the for() loop) before you allocate for the new string. Or you could use realloc() instead.

Sign up to request clarification or add additional context in comments.

Comments

0

c[0] is of the type char *. You either need to do c[0][0] or (char) c.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.