[英]How to copy an array of characters to a char pointer without using strcpy
[英]How to store characters into a char pointer using the strcpy() function
我試圖找出為什么我不能通過使用strcpy()命令將字符存儲到我的char指針。 當我運行下面的代碼時,我得到一個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;
}
謝謝!
現在, 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
聲明為數組,如Bryan Ash建議的那樣
char str1[] = "abcdefg";
char str2[] = "abcdefg";
如果你想動態地分配字符串而不是在堆上,你可以使用alloca
(更多細節閱讀http://man7.org/linux/man-pages/man3/alloca.3.html ),因為kfsone注意到
使用-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 */
在這個例子中,你甚至不需要strcpy,你可以使用:
char str1[] = "abcdefg";
char str2[] = "abcdefg";
如果你想了解更多有關指針的信息,可以從斯坦福CS教育圖書館獲得一本名為Pointers and Memory的優秀免費電子書。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.