可能重复:
Why do I get a segmentation fault when writing to a string?麻烦简单的字符串连接
我写在那里我试图连接两个字符串在for循环中一个非常简单的程序。字符串连接中的第一个字符串是固定的,第二个字符串是通过使用itoa
函数获得的。该程序正在成功建立,但是当我尝试运行程序时,它无法运行并停止。我只是调试程序,并在调试时意识到程序在字符串连接操作中陷入困境。我正在发布下面的程序。感谢您的支持:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char *argv[])
{
char *str="NULL" ,dec[] = "NULL";
int i,num;
printf("Enter a number : \n");
scanf("%d",&num);
for (i=0;i<num;i++)
{ str = "test_file_num_";
itoa(i,dec,10);
strcat(str,dec);
printf("%s\n",str);
}
return 0;
}
嗨! 感谢您的支持。当我将char * str声明为char str [128]时,我在语句str =“test_file_num_”中收到错误;并且错误是错误C2106:'=':左操作数必须是l值 – duttasankha
更改'strcpy(str,“test_file_num _”);'。 – imreal
完美!奇妙的作品。你是否会改变你的答案并添加这个答案,以便我可以接受它作为答案。再次感谢。 – duttasankha