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!
(char *)cast; it isn't needed in C), then do what Paul suggested; lookup thestrcpyfamily of functions. Also,printfusing%srequires aconst char*compatible argument; you're giving it achar. Maybe fix that too.strlenwill come in handy there (or juststrdup()if allowed by your prof). If you're doing this in a linked list you're going to end up with two allocations per node (one for the node; one for the string field in the node). There are many examples of linked list node management on the web, not related to your question.