[英]How to store characters into a char pointer using the strcpy() function
I am trying to figure out why I can't store characters into my char pointer by using the strcpy() command. 我试图找出为什么我不能通过使用strcpy()命令将字符存储到我的char指针。 I get a seg fault when I run the code below.
当我运行下面的代码时,我得到一个seg错误。
#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[])
{
char *str1, *str2;
int ret;
strcpy(str1, "abcdefg"); // stores string into character array str1
strcpy(str2, "abcdefg");
printf("contents of %s \n", str1);
ret = strncmp(str1, str2, strlen(str2)); /* compares str1 to str2 */
if (ret > 0) {
printf("str1 is less than str2\n");
}
else if (ret < 0) {
printf("str2 is less than str1\n");
}
else if (ret == 0) {
printf("str1 is equal to str2\n");
}
return 0;
}
Thank you! 谢谢!
Right now, str1
and str2
are just pointers to a character. 现在,
str1
和str2
只是一个字符的指针。 When you do strcpy(str1, "abcdefg")
, it attempts to write the characters in the string "abcdefg" into the memory that str1
points to and since str1
points to an unknown memory, which probably you don't have any write permissions, you get a segmentation fault. 当你执行
strcpy(str1, "abcdefg")
,它会尝试将字符串“abcdefg”中的字符写入str1
指向的内存中,因为str1
指向未知内存,这可能是你没有任何写权限,你得到一个分段错误。
One way to fix it is to allocate memory on the heap and then store these strings. 修复它的一种方法是在堆上分配内存,然后存储这些字符串。
#include <stdlib.h>
...
/* assuming the max length of a string is not more than 253 characters */
char *str1 = malloc(sizeof(char) * 254);
char *str2 = malloc(sizeof(char) * 254);
You can also use strdup
to duplicate the string like Gangadhar has mentioned. 您也可以使用
strdup
复制像Gangadhar所提到的字符串。
Another way is to declare str1
and str2
as arrays during the compiling as Bryan Ash suggested 另一种方法是在编译期间将
str1
和str2
声明为数组,如Bryan Ash建议的那样
char str1[] = "abcdefg";
char str2[] = "abcdefg";
In case, you want to allocate the string dynamically but not on the heap, you can use alloca
(for more details read http://man7.org/linux/man-pages/man3/alloca.3.html ) as kfsone noted 如果你想动态地分配字符串而不是在堆上,你可以使用
alloca
(更多细节阅读http://man7.org/linux/man-pages/man3/alloca.3.html ),因为kfsone注意到
compiling this with the -Wall
command gives a useful hint 使用
-Wall
命令编译它会给出一个有用的提示
test.c:12:10: warning: 'str1' is used uninitialized in this function [-Wuninitialized]
printf("contents of %s \n", str1);
^
test.c:14:17: warning: 'str2' is used uninitialized in this function [-Wuninitialized]
ret = strncmp(str1, str2, strlen(str2)); /* compares str1 to str2 */
Given this example, you don't even need strcpy, you could use: 在这个例子中,你甚至不需要strcpy,你可以使用:
char str1[] = "abcdefg";
char str2[] = "abcdefg";
If you want to learn more about pointers, there's an excellent free e-book titled Pointers and Memory from Stanford CS Education Library. 如果你想了解更多有关指针的信息,可以从斯坦福CS教育图书馆获得一本名为Pointers and Memory的优秀免费电子书。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.