1

I want to determine the frequency of words passed in the command line arguments, so I defined a structure with a string and it's count, now the problem is when I'm trying to search for the string in the Structure array by comparing the strings using strcmp() function, I'm getting Segmentation Fault, Here's the code :-

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct{
  char* word;
  int count;
} argsArray;

int search(argsArray array[] , char* Word , int len){
  for(int i=0; i < len; i++){
    if(strcmp(array[i].word , Word)==0){
        return i;
    }
  }
  return -1;
}

int main( int argc , char* argv[] ){
  argsArray inputArgs[50];
  int i,p=0,a;
  for(i=0;i<50;i++){
    inputArgs[i].word=NULL;
    inputArgs[i].count=0;
  }
  for( i=1 ; i < argc ; i++ ){
    a = search(inputArgs , argv[i] , argc);

    if(  a== -1 ){
        inputArgs[p].word=argv[i];
        inputArgs[p].count++;
        p++;
    }
    else{
        inputArgs[a].count++;
    }
  }
  for(i = 0; i < p; i++){
    printf("%s %d\n",inputArgs[i].word,inputArgs[i].count);
  }
  return 0;
}
dragosht
  • 3,237
  • 2
  • 23
  • 32
Aashish Kumar
  • 115
  • 2
  • 13

2 Answers2

4

I am going to suggest you some corrections.

Firstly, I think you were trying to initialize the array of structures when you wrote this.

for(i=0;i<50;i++){
    inputArgs[i].word=NULL;
    inputArgs[i].count=0;
}

As mentioned in the other answer, this will cause segmentation fault. You can initialize the input[i].word with "".

Or, in the search function, you can check whether array[i].word is a NULL; and if you find NULL, then you immediately return -1 from the function.

For the second suggestion, your search function will become something like this.

int search(argsArray array[] , char* Word , int len){
  for(int i=0; i < len; i++){
    if(array[i].word == NULL)
        return -1;
    if(strcmp(array[i].word , Word)==0){
        return i;
    }
  }
  return -1;
}

Reference for second suggestion

Community
  • 1
  • 1
Muntasir
  • 798
  • 1
  • 14
  • 24
0

inputArgs[i].word=NULL; and then search(inputArgs , argv[i] , argc); which invokes strcmp(array[i].word , Word)

meaning you just called strcmp(NULL, Word) --> segfault

CIsForCookies
  • 12,097
  • 11
  • 59
  • 124
  • Then how to do it, because i want to search for that string and if it's not found, add it and if found then return it's position and increase it's count by 1 – Aashish Kumar Mar 09 '17 at 09:11