![](/img/trans.png)
[英]How to assign pointer of two dimensional array to memory address in C/C++
[英]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);
打印字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.