Choco Fernandez Choco Fernandez - 1 year ago 41
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?");
return sizeOf;

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


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

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

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

should've been

char sname[maxlength]


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

should've been

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


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