Miguel J.
Miguel J.

Reputation: 337

How to use malloc to get memory address for pointer in c, then assign char array at that address?

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

Answers (1)

Erik W
Erik W

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

Related Questions