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[]);

有帮助吗?

解决方案

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

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top