Choco Fernandez Choco Fernandez - 3 months ago 9
C Question

Searching a string from an array of strings

I created a program that accepts strings and stores them in a two-dimensional array, It also has a function that searches for a string(inputted by the user) in the array. But whenever I run the program, it stops working when it reaches the searching part. Can anyone point out my error?

Here's my code

#include <stdio.h>
#include <string.h>
#define maxname 40
#define maxlength 70

int acceptSize()
{
int sizeOf;
printf("How many students?");
scanf("%d",&sizeOf);
return sizeOf;
}

void acceptNames(char names[maxname][maxlength],int size)
{
int ctr;
for(ctr=0; ctr<size; ctr++)
{
printf("Student %d:", ctr+1);
scanf("%s",&names[ctr]);
}

}

int searchName(char names[maxname][maxlength], char sname[maxname]){
int ctr2;
for(ctr2=0; ctr2<maxname; ctr2++)
{
if(strcmp(names[ctr2], sname[maxname])==0)
{
return ctr2;
}
}
return -1;
}

int main(){
int ctr,size, choice, result;
char names[maxname][maxlength], sname[maxlength];

size=acceptSize();
acceptNames(names,size);
printf("Enter name to be searched: ");
scanf("%s", &sname[maxlength]);
result=searchName(names, sname);
if(result == -1)
printf("Match is not found.");
else
printf("Match is found!");
}

Answer
char sname[maxname] // in int searchName()

should've been

char sname[maxlength]

Also

if(strcmp(names[ctr2], sname[maxname])==0)

should've been

if(strcmp(names[ctr2], sname)==0) // sname[maxname] is not a string, sname is !!

finally

scanf("%s", &sname[maxlength]);

shoud've been

scanf("%s", sname); // reading a string is a case where you could omit &

And a suggestion : Use [ fgets ] instead of scanf

use

Comments