I have encounter an error when running this code. There will be a "program stop working" windows once it reaches the loop to scan for user input for the names ("scanf_s(%s", &nameptr[i]); ). Any help or advice will be greatly appreciated!
#include <stdio.h>
#include <string.h>
#define SIZE 10
int findTarget(char *target, char nameptr[SIZE][80], int size);
int main()
{
char nameptr[SIZE][80];
char t[40];
int i, result, size;
printf("Enter no. of names: ");
scanf_s("%d", &size);
printf("Enter %d names: ", size);
for (i = 0; i < size; i++)
scanf_s("%s", &nameptr[i]);
printf("Enter target name: ");
scanf_s("\n");
gets(t);
result = findTarget(t, nameptr, size);
printf("findTarget(): %d\n", result);
return 0;
}
int findTarget(char *target, char nameptr[SIZE][80], int size)
{
int i;
for (i = 0; i<size; i++) {
if (strcmp(nameptr[i], target) == 0)
return i;
}
return -1;
}
getsas it does not provide any protection against buffer overflows. Usefgetsinstead:fgets(t, sizeof(t), stdin);