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