0

This C program reads a line of text from keyboard and then writes the longest word in the line. The issue with my code below is that it only prints the last word apart from its length, although everything seems fine. Can anyone see a problem with my code?

#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;
}
/*----------------------------------------------------------------------------*/
4

2 回答 2

5
Ind_w[i] = w;//the issue is here!!

You let all pointers in Ind_w point to the same buffer, which is overwritten for each entered word. So only the last entered word remains "visible".

If you have it,

Ind_w[i] = strdup(w);

is a simple solution. Otherwise

Ind_w[i] = malloc(strlen(w)+1);
strcpy(Ind_w[i], w);

Both ways require the pointed-to memory to be freed when it is no longer used.

于 2013-01-03T16:00:17.313 回答
2
Ind_w[i] = strdup(w);//the issue is here!!

w每次读取缓冲区时都必须复制缓冲区,并且不要对所有读取使用相同的缓冲区。使用您所做的方式,您将拥有指向同一个缓冲区的所有数组元素,并且该缓冲区包含相同的字符串,这是最后一个读取的字符串sscanf

注意:当它们无用时,您必须使用free所有重复的缓冲区。您可以通过遍历指针数组并释放每个元素(指针)来完成

于 2013-01-03T16:01:38.773 回答