I have a char pointer points to an address of the memory and I need to get the content of that address and put it into an char array?
我有一个指向内存地址的字符指针我需要获取地址的内容并将其放入一个字符数组中?
char *msg;
char cntnt[10];
msg is pointing to "mike" and I need to put this string into cntnt[10]
.
msg指向“mike”,我需要把这个字符串放到cntnt[10]中。
I do like this
我非常喜欢这
*cntnt = *msg;
when I do this, cntnt only get one letter 'm'.
当我这样做时,cntnt只有一个字母“m”。
please help....
请帮助....
4 个解决方案
#1
3
Use strcpy:
使用拷贝字符串:
strcpy(cntnt, msg);
#2
3
Try using strcpy
or memcpy
.
尝试使用strcpy或memcpy。
len = strlen(msg);
if (len >= sizeof(cntnt))
/* Bail out, not enough space. */
memcpy(cntnt, msg, len);
cntnt[len] = 0;
#3
0
Use memcpy
to copy n
number of bytes from that pointer to the array:
使用memcpy从指向数组的指针中拷贝n个字节:
char cntnt[10];
memcpy(cntnt, msg, 9);
using strcpy is recommended only if you have a null terminated string memory pointed by msg
pointer.
只有当msg指针指向空终止字符串内存时,才推荐使用strcpy。
#4
0
pointers and arrays are not equal. They are only similar in some ways. So, after your code you changed only one element of your array.
指针和数组不相等。它们只是在某些方面相似。所以,在你的代码之后,你只改变了数组的一个元素。
If you want to change the place where cntnt is localized, you should write
如果您想更改cntnt本地化的位置,您应该编写
cntnt = msg;
If you want to copy the content of char sequence to array, use strcpy, as Tudor said. here is a nice explanation of the subject: http://c-faq.com/~scs/cclass/notes/sx8.html
如果您想将char序列的内容复制到数组中,请使用strcpy,如Tudor所言。以下是对这个主题的一个很好的解释:http://c-faq.com/~scs/cclass/notes/sx8.html
#1
3
Use strcpy:
使用拷贝字符串:
strcpy(cntnt, msg);
#2
3
Try using strcpy
or memcpy
.
尝试使用strcpy或memcpy。
len = strlen(msg);
if (len >= sizeof(cntnt))
/* Bail out, not enough space. */
memcpy(cntnt, msg, len);
cntnt[len] = 0;
#3
0
Use memcpy
to copy n
number of bytes from that pointer to the array:
使用memcpy从指向数组的指针中拷贝n个字节:
char cntnt[10];
memcpy(cntnt, msg, 9);
using strcpy is recommended only if you have a null terminated string memory pointed by msg
pointer.
只有当msg指针指向空终止字符串内存时,才推荐使用strcpy。
#4
0
pointers and arrays are not equal. They are only similar in some ways. So, after your code you changed only one element of your array.
指针和数组不相等。它们只是在某些方面相似。所以,在你的代码之后,你只改变了数组的一个元素。
If you want to change the place where cntnt is localized, you should write
如果您想更改cntnt本地化的位置,您应该编写
cntnt = msg;
If you want to copy the content of char sequence to array, use strcpy, as Tudor said. here is a nice explanation of the subject: http://c-faq.com/~scs/cclass/notes/sx8.html
如果您想将char序列的内容复制到数组中,请使用strcpy,如Tudor所言。以下是对这个主题的一个很好的解释:http://c-faq.com/~scs/cclass/notes/sx8.html