简体   繁体   中英

How to search for a string in an array of structures?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM