Question

The question: Read up to 6 pairs of names and ages into TWO separate arrays, and use a linear search to locate a target name and to print that person’s age. The two arrays are called names and ages:

I am getting lots of errors .. I am not sure about passing the arrays into functions..

  #include <stdio.h>
#define ASIZE 20
#define RECSIZE 6

struct record {
    char name[ASIZE];
    int age[ASIZE];
};
struct record na[RECSIZE];

int linearSearch(struct record *a, char *find)
{
int x;
for(x=0; x<RECSIZE; x++)
{
//  if(na[x].name==find[x])
if(a->name[x]==find[x])
    {
        return x;
    }
}
return -1;
 }

int main()
{
    int i;

    for (i=0; i<RECSIZE; i++)
{
printf("Enter name: ");
scanf("%s",na[i].name);
printf("Enter age: ");
scanf("%i",&na[i].age);
}   

printf("Enter the Search name: ");
char temp[ASIZE];
scanf("%s",temp[ASIZE]);


int result;
result=linearSearch(&na, &temp[]);
printf("%i", result);
    return 0;
    }

Please help.

The error is in: result=linearSearch(&na, &temp[]);

Was it helpful?

Solution

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

#define ASIZE 20
#define RECSIZE 6

struct record {
    char name[ASIZE];
    int age;
};

struct record na[RECSIZE];

int linearSearch(struct record *a, char *find){
    int x;
    for(x=0; x<RECSIZE; x++){
        if(strcmp(a[x].name, find)==0)
            return x;
    }
    return -1;
}

int main(){
    int i;

    for (i=0; i<RECSIZE; i++){
        printf("Enter name: ");
        scanf("%s", na[i].name);//No protection when entered past the buffer
        printf("Enter age: ");
        scanf("%i", &na[i].age);
    }

    printf("Enter the Search name: ");
    char temp[ASIZE];
    scanf("%s", temp);

    int result;
    result=linearSearch(na, temp);
    printf("%i", result);
    return 0;
}

OTHER TIPS

On my system, the compiler gave me these errors for your exact code. Just look at the line numbers (should be exactly like yours) and address each error by looking at the error description. Once you address these, you will be further down the path of understanding your execution flow:

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top