JWH_
JWH_

Reputation: 267

Error when reading user input and storing into array

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

Upvotes: 1

Views: 47

Answers (1)

Spikatrix
Spikatrix

Reputation: 20244

This:

scanf_s("%s", &nameptr[i]); 

should be

scanf_s("%s", nameptr[i], sizeof(nameptr[i])); 
/* Or better */
scanf_s("%79s", nameptr[i], sizeof(nameptr[i])); 

or

scanf_s("%s", nameptr[i], _countof(nameptr[i])); 
/* Or better */
scanf_s("%79s", nameptr[i], _countof(nameptr[i])); 

because the %s in scanf_s expects a third argument denoting the maximum size of the string argument used. More information on this can be found at the msdn documentation of scanf_s

Upvotes: 1

Related Questions