我的代码不起作用。在我接受字符串时出现运行时错误。这段代码有什么问题?
//this is what i have in main()
char *ele,*s[max];
int *count,temp=0;
count=&temp;
printf("Enter string to insert: ");
scanf("%s",ele);
addleft(s,ele,count);
//following is the function definition
void addleft(char *s[max],char *ele,int *count)
{
int i;
if((*count)==max)
{
printf("Queue full!\n");
return;
}
for(i=*count;i>0;i--)
strcpy(s[i],s[i-1]);
strcpy(s[0],ele);
(*count)++;
printf("String inserted at left!\n");
}
最佳答案
ele
是一个未初始化的 char*
,没有与之关联的内存,scanf()
将尝试写入它,导致未定义行为,可能会出现段错误。
您需要为 ele
动态分配内存,或者在使用 scanf()
时声明一个本地数组并防止缓冲区溢出:
char ele[1024];
if (1 == scanf("%1023s", ele))
{
/* Process 'ele'. */
}
此外,函数 addleft()
在 s
上使用 strcpy()
,它是一个 char*< 数组
并且数组中的每个 char*
都是统一初始化的。这是未定义的行为,并且可能是段错误。要更正,您可以使用 strdup()
(如果可用),否则 malloc()
和 strcpy()
:
/* Instead of:
strcpy(s[0],ele);
use:
*/
s[0] = strdup(ele);
请注意,addleft()
函数内的 for
循环很危险,因为 s
中包含 char*
> 的长度不一定相同。这很容易导致写入超出数组末尾。但是,由于元素是动态分配的 char*
的地址,因此您可以只交换元素而不是复制其内容。
关于c - 读取字符串时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12804450/