我试图弄清楚为什么我不能通过使用strcpy()命令将字符存储到我的char指针中。我在运行下面的代码时遇到了段错误。
#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;
}
谢谢!
答案 0 :(得分:10)
现在,str1
和str2
只是指向某个角色的指针。
当你执行strcpy(str1, "abcdefg")
时,它会尝试将字符串“abcdefg”中的字符写入str1
所指向的内存中,并且str1
指向未知的内存,这可能是你不知道的如果有任何写入权限,则会出现分段错误。
解决这个问题的一种方法是在堆上分配内存,然后存储这些字符串。
#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);
您还可以使用strdup
复制Gangadhar提到的字符串。
另一种方法是在编译期间将str1
和str2
声明为数组{/ 3}}建议
char str1[] = "abcdefg";
char str2[] = "abcdefg";
如果你想动态分配字符串而不是在堆上,你可以使用alloca
(更多详细信息,请阅读Bryan Ash),注明http://man7.org/linux/man-pages/man3/alloca.3.html
答案 1 :(得分:3)
使用-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 */
答案 2 :(得分:1)
鉴于此示例,您甚至不需要strcpy,您可以使用:
char str1[] = "abcdefg";
char str2[] = "abcdefg";
如果您想了解有关指针的更多信息,可以从斯坦福大学CS教育图书馆获得一本名为Pointers and Memory的优秀免费电子书。