搜索数组中的字符串并返回索引

时间:2013-02-17 11:52:57

标签: c

我的代码中存在问题。输入我要搜索的字符串后,程序崩溃。

我检查了我的代码,但我仍然无法弄清楚出了什么问题。

需要你的建议。

#include <stdio.h>
#include <string.h>

int findTarget(char *string, char *nameptr[], int num);
int main()
{
int index, index2;
int size;
char *nameptr[100];
char *string[100];

printf("Enter the number of names: ");
scanf("%d",&size);

for(index=0; index<size; index++)
{
    printf("Enter A Name: ");
    scanf("%s", &nameptr[index]);
}

printf("\nEnter a string to search:");
scanf("%s", &string);

index2 = findTarget(string[100], nameptr, size);

if ( index2 == -1 )
{
  printf("\nNo - no such name\n");
}
else
{
  printf("\nYes - matched index location at %d\n", index2);
 }
return 0;

}

 int findTarget(char *string, char *nameptr[], int num)
 {
int i=0;

for ( i = 0 ; i < num ; i++ )
{

    if (strcmp(nameptr[i],string)==0)
    {
        return i;
        break;
    }
}

return -1;

}

4 个答案:

答案 0 :(得分:2)

您从未向&nameptr[index]分配内存,因此在scanf中使用它是未定义的行为。在致电malloc之前,您应该尝试scanf。此外,您应该删除&

答案 1 :(得分:0)

你有一个char*的数组,但当你对它进行scanf时,你实际上并没有分配缓冲区。

相反,您应该首先通过以下方式为缓冲区保留内存:

for(i=0; i<100; i++) {

    nameptr[i] = malloc(STRING_BUFFER_SIZE);
}

答案 2 :(得分:0)

代码中的问题通常可以描述为“内存管理”:

  • 您不为单个字符串分配内存
  • 您将错误内容的地址传递给scanf
  • 您使用scanf允许缓冲区溢出
  • 您将string声明为包含100个字符串的数组,而不是单个字符串
  • 您正在将string[100]传递给搜索功能

要解决此问题,您需要使用malloc动态分配单个字符串。您可以使用临时缓冲区,然后使用strdup进行复制,或预先分配100个字符,并将scanf限制为该字符。

以下是您需要更改的程序的一部分:

char *nameptr[100];
char string[100]; // The asterisk is gone

printf("Enter the number of names: ");
scanf("%d",&size);

for(index=0; index<size; index++) {
    char buf[100];
    printf("Enter A Name: ");
    scanf("%99s", buf); // Note the limit of 99
    buf[99] = '\0'; // Just to make sure it's terminated
    nameptr[index] = strdup(buf);
}

printf("\nEnter a string to search:");
scanf("%99s", string); // No ampersand

index2 = findTarget(string, nameptr, size); // string, not string[100]

for (index=0; index<size; index++) {
    free(names[i]);
}

其余的只是“风格点”:

  • 在搜索功能<{li>中break之后,您不需要return
  • 您不需要在循环循环之前初始化i
  • 不鼓励在行的开头打印\n

答案 3 :(得分:0)

嗯,这是因为你还没有为你的字符串分配内存而崩溃的原因。

使用char nameprt[100];代替*char nameptr[100];。你声明的是一个指向字符的指针数组,而不是一个包含100个字符的数组。

在scanf中你必须这样做scanf("%s", nameptr); 原因是,scanf需要一个指向数组的指针。因此,如果变量已经是指针,则没有理由&