maziar parsaeian
maziar parsaeian

Reputation: 51

String pointer issue in C code

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

Upvotes: 0

Views: 157

Answers (2)

MOHAMED
MOHAMED

Reputation: 43518

Ind_w[i] = strdup(w);//the issue is here!!

You have to duplicate the w buffer each time you read the buffer and not use the same buffer for all reading. with the way you did you will have all the array elements pointing to the same buffer and this buffer is containing the same string which is the last one read with sscanf

Note: you have to free all the duplicated buffers when they come useless. You can do it by go over the array of pointers and free each element (pointer)

Upvotes: 2

Daniel Fischer
Daniel Fischer

Reputation: 183868

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.

Upvotes: 5

Related Questions