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!
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.