user3337714
user3337714

Reputation: 673

search a struct in C

void search(struct _data *BlackBox, char *name, int size) - this function will get the dynamic array of struct passed to it, the name we are looking for, and the size of the array. This function will then search the dynamic array for the name.

typedef struct _data
{
    char* name;
    long number;
} _data;

int scan(FILE *(*stream));
struct _data *load(FILE *stream, int size);
void search(struct _data *Blackbox, char *name, int size);

int main()
{
    int size = scan(&stream);    
    rewind(stream);
    _data *data = load(stream, size);

    char input;
    printf("Please Input Search Name: ");
    scanf("%s", input);
    while (input != NULL)
    {
        search(data, input, size);
    }
}

void search(struct _data *Blackbox, char *name, int size)
{
    for (int i=0; i<size; i++)
    {
        if (strcmp(name,Blackbox[i].name) != 0)
        {
            printf("Success");
        }
        else
        {
            printf("Name Not Found");
        }
    }
}

But I am getting the following output

Output:
LINES: 2
ron 7774013
jon 7774014
Please Input Search Name: ron

RUN FINISHED; Segmentation fault: 11; real time: 2s; user: 0ms; system: 0ms

Upvotes: 0

Views: 532

Answers (3)

Xxxo
Xxxo

Reputation: 1931

If you get a segmentation fault then one the following applies:

  1. Your struct Blackbox in search function is not pointing to a valid memory location and thus the Blackbox[i] produces the fault
  2. The name member of the struct is not pointing to a valid memory location and thus the Blackbox[i].name is producing the fault
  3. The size of the Blackbox array is less than size-1.

To do this, use a debugger and check the Blackbox where is pointing. Then check the Blackbox.name where is pointing. Then, check if there is anything to the Blackbox array up to size-1. I assume that either will be null. Perhaps an error in the assignment of the load function or a wrong usage of the size.

Upvotes: 0

bazza
bazza

Reputation: 8404

In your main function you have "char input;", and "scanf("%s",input);". That's wrong, because the %s specifies a string parameter, but input is a char variable. So whatever is typed in by the user is stored at some random place in memory.

Change the declaration of input to something lime "char input[1000];". And you'll have to do something about your while loop too.

Upvotes: 3

sth
sth

Reputation: 229583

You need to declare the search function before you try to use it.

The compiler should even warn you about that implicit declaration.

Upvotes: 0

Related Questions