1

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;
      }
1
  • Avoid gets as it does not provide any protection against buffer overflows. Use fgets instead: fgets(t, sizeof(t), stdin); Commented Sep 19, 2015 at 11:12

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Its working now! May I know what is the use of the 3rd parameter for scanf_s and when does one need to use it?
@Jackelll The third parameter is to prevent buffer overflows. It is needed when using %s, %c and %[. Otherwise, it is not required.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.