user2481095 user2481095 - 2 months ago 16
C Question

How to initialize a char array using a char pointer in C

Let's say I have a char pointer called string1 that points to the first character in the word "hahahaha". I want to create a char[] that contains the same string that string1 points to.

How come this does not work?

char string2[] = string1;

Answer

"How come this does not work?"

Because that's not how the C language was defined.

You can create a copy using strdup() [Note that strdup() is not ANSI C]

Refs: