这个C程序从键盘读取一行文本,然后在行中写入最长的单词。下面我的代码的问题是它只打印除了它的长度之外的最后一个单词,尽管一切看起来都很好。任何人都可以看到我的代码有问题吗?
#include<stdio.h>
#include<string.h>
#define MAX 132
#define MAXW 30
int Len_w[MAXW];
int Max_V(int vf[], int len);
main()
{
char s[MAX+1], w[MAXW], *Ind_w[MAXW],*p,out[MAXW];
int k=0, i=0, Maximum, g=0;
printf("\nInsert the line....\n");
p=fgets(s, MAX, stdin);
while(sscanf(p, "%s%n", w, &k)==1){
Len_w[i] = strlen(w);
Ind_w[i] = w; //the issue is here!!
p+=k+1;
i++;
}
Maximum = Max_V(Len_w,i);
for(g=0;g<i;g++){
if(Len_w[g] == Maximum){
//sscanf(Ind_w[g],"%s",out);
printf("\n%s", Ind_w[g]);
}
}
return 0;
}
/*----------------------------------------------------------------------------*/
int Max_V(int vf[], int len)
{
int j; int Max;
Max=*vf;
for(j=1; j < len; j++)
{
if(*(vf+j) > Max)
{
Max=*(vf + j);
}
}
return Max;
}
/*----------------------------------------------------------------------------*/
答案 0 :(得分:5)
Ind_w[i] = w;//the issue is here!!
让Ind_w
中的所有指针指向同一个缓冲区,每个输入的单词都会覆盖该缓冲区。因此,只有最后输入的单词仍然是“可见的”。
如果你有,
Ind_w[i] = strdup(w);
是一个简单的解决方案。否则
Ind_w[i] = malloc(strlen(w)+1);
strcpy(Ind_w[i], w);
两种方式都需要在不再使用指向内存时释放它。
答案 1 :(得分:2)
Ind_w[i] = strdup(w);//the issue is here!!
每次读取缓冲区时都必须复制w
缓冲区,而不是对所有读取使用相同的缓冲区。以你的方式,你将所有的数组元素指向同一个缓冲区,这个缓冲区包含相同的字符串,这是最后一个用sscanf
注意:当它们变得无用时,你必须free
所有重复的缓冲区。你可以通过遍历指针数组并释放每个元素(指针)