如何使用 malloc 获取 c 中指针的内存地址,然后在该地址分配 char 数组?

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

我想在 C 中创建一个字符串,它只是一个数据类型为 char 的数组。我试图有一个指针,然后分配一个 char 数组的值。这是我目前所拥有的:

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);

我想知道我做错了什么?

不幸的是,我需要使用 malloc,但请随时告诉我更好的方法以及使用 malloc 的解决方案。

谢谢大家!

而不是你声明的两个变量,你应该写:

char* string = malloc(sizeof(char) * <insert number of chars plus one here>);

你应该写:

string = "Array of chars";
printf("%s", string); 

打印字符串。