Reputation: 337
I am trying to create a string in C, which is just an array of data type char. I am trying to have a pointer and then assign the value of a char array. This is what I have so far:
char *string;
string = (char *)malloc(sizeof(char));
// Now I have a pointer, so if I wanted to print out the pointer of the spot
// in memory that is saved I can do the following:
printf("%p", string);
// That gives me the pointer, now I want to assign an array at that address
// *string gives me that data stored at the pointer
*string = "Array of chars?";
printf("%s", *string);
I am wondering what I am doing wrong with that?
I need to use malloc unfortunately, but please feel free to tell me a better way to do this as well with along with the solution using malloc.
Thank you guys!
Upvotes: 0
Views: 2520
Reputation: 2628
Instead of the two variables you declared, you should write:
char* string = malloc(sizeof(char) * <insert number of chars plus one here>);
You should write:
string = "Array of chars";
printf("%s", string);
to print the string.
Upvotes: 3