运行此代码时遇到错误。将有一个"程序停止工作"窗口一旦到达循环就扫描用户输入的名称(" scanf_s(%s",& nameptr [i]);)。 任何帮助或建议将不胜感激!
#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;
}
答案 0 :(得分:1)
此:
scanf_s("%s", &nameptr[i]);
应该是
scanf_s("%s", nameptr[i], sizeof(nameptr[i]));
/* Or better */
scanf_s("%79s", nameptr[i], sizeof(nameptr[i]));
或
scanf_s("%s", nameptr[i], _countof(nameptr[i]));
/* Or better */
scanf_s("%79s", nameptr[i], _countof(nameptr[i]));
因为%s
中的scanf_s
需要第三个参数来表示所使用的字符串参数的最大大小。有关这方面的更多信息,请访问msdn documentation of scanf_s