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

标签 c arrays pointers memory

我试图在 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); 

打印字符串。

关于c - 如何使用 malloc 获取 c 中指针的内存地址,然后在该地址分配 char 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29464563/

相关文章:

arrays - R中的字符串数组组合

sql - 2 列上的 Postgresql 约束,因此 "col_a"不能共享 "col_b"的任何值

C 通过取消引用或地址运算符分配指针

在 uint32_t 计算中转换为 float

c - 为什么我能够复制比 char 数组中定义的字节更多的字节?

c - 仅使用主函数查找数字阶乘的程序

python - 重新分配 numpy.array()

c++ - 将 Lab 值转换为 opencv 中的 RGB 值

c - 不兼容的指针类型警告

C - 使用指针的自定义快速排序 + 比较器不起作用