[英]Updating char[] field in a struct with strcpy. Pointer issue in C
[英]Issue with char pointer being assigned to another location and using strcpy()?
在這里,我試圖將字符串數組“ s”中的“你好”一詞替換為“ woo”。 但是它在運行時突然退出。 請幫忙
char *s[] = {"hi there","how are you","Fine Ok!"};
char str1[4] = "how" ;char str2[4] = "woo";
char *j = NULL; //(char *)malloc(100*sizeof(char));
int i,k; char n[100] = "hi";
//printf("%d",strlen(s));
for(i = 0;i<3;i++ )
{
j = strstr(s[i],str1);
if(j==0)
continue;
else
{
printf("j is %s",j);
printf("j is %s",j+10);
strcpy(j,str2);
printf("j is %s",j);
break;
}
}
printf("%s",s[1]);
return 0;
您的代碼中有多個問題。 讓我們從一個更明顯的例子開始:記住strcpy
添加了字符串終止符。 您可能要改用memcpy
:
memcpy(j, str2, strlen(str2));
要繼續,請分配內存並將其分配給j
,然后在循環中將其重新分配給j
使j
指向其他位置,然后釋放已分配的原始內存,從而導致內存泄漏。 同樣, 在C語言中,您不應該轉換malloc
的結果 。
最后,還有可能導致崩潰的原因:您嘗試修改字符串文字,並且所有字符串文字均為只讀 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.