【发布时间】:2019-10-05 22:33:29
【问题描述】:
作为标题,我做了一个演示来描述我的困惑。
如果我将 [strcat] 替换为 [stacpy],我可以得到显而易见的结果,即
@
@
@
所以我怀疑问题出在 [strcat] 上。
void main(){
for(int i=0; i<3 ;i++){
char* str = (char*)malloc(200*sizeof(char));
if(str == NULL){
printf("malloc failed. \n");
return;
}
strcat(str, "@ ");
printf("%s\n", str);
free(str);
str = NULL;
}
}
在我的期望中,我应该得到:
@
@
@
但我得到的是:
(1) @
xK`▒
xK`▒
而且每次都不一样:
(2) @
x▒
x▒
(3) @
xk▒▒
xk▒▒
【问题讨论】:
-
请先谷歌。我找到的重复答案是我对
strcpy strcat的第一个谷歌搜索结果。 -
对不起,谢谢。下次我会尽量不要这么懒。
标签: c pointers malloc free dynamic-memory-allocation