2015-09-05 80 views
3

我在尝试循环通过C编程中的多维数组时遇到了一些问题。预期结果应该是这样:在C编程中查找多维数组中的元素

Enter no. of names: 4 
Enter 4 names: Peter Paul John Mary 
Enter target name: John 
Yes - matched at index location: 2 

Enter no. of names: 5 
Enter 5 names: Peter Paul John Mary Vincent 
Enter target name: Jane 
No – no such name: -1 

这里是我的代码:

int main() 
{ 
char nameptr[SIZE][80]; 
char t[40]; 
int i, result, size; 

printf("Enter no. of names: "); 
scanf("%d", &size); 
printf("Enter %d names: ", size); 
for (i = 0; i<size; i++) 
    scanf("%s", nameptr[i]); 
getc(stdin); 
printf("\nEnter target name: "); 
gets(t); 
result = findTarget(t, nameptr, size); 
if (result != -1) 
    printf("Yes - matched at index location: %d\n", result); 
else 
    printf("No - no such name: -1\n"); 
return 0; 
} 

int findTarget(char *target, char nameptr[SIZE][80], int size) 
{ 
    int row, col; 
    for (row = 0; row < SIZE; row++) { 
     for (col = 0; col < 80; col++) { 
      if (nameptr[row][col] == target) { 
       return col; 
      } 
     } 
    } 
    return -1; 
} 

然而,当我进入“彼得·保罗·约翰·玛丽”,并试图进行搜索,它不返回我与“是 - 在索引位置匹配:2”。相反,它以“不 - 没有这样的名字”返回给我:-1。所以我在想我的代码哪部分出错了。有任何想法吗?

在此先感谢。

修改部分

int findTarget(char *target, char nameptr[SIZE][80], int size) 
{ 
int row, col; 
for (row = 0; row < size; row++) { 
    for (col = 0; col < size; col++) { 
     if (strcmp(nameptr[row]+col, target)) { 
      return row; 
      break; 
     } 
     else { 
      return -1; 
     } 
    } 
} 
} 

回答

4

你不想使用nameptr[row][col] == target,你想与strcmp(nameptr[row][col],target) == 0来取代它。 ==比较指针(内存地址),strcmp比较字符串的实际值,并在匹配时返回0

+0

当我将其更改为字符串比较后,当我尝试执行搜索时,cmd刚停止工作,并且在输出处没有错误消息。有任何想法吗? – hyperfkcb

+0

对不起,只是再看看你的代码。 'nameptr [row] [col]'不是一个字符串;它是一个单一的字符。试试'nameptr [row] + col' –

+0

好吧,但现在问题是返回的索引位置不正确。另外,如果我试图找到一个不在数组中的名称,它仍然返回给我,是的,任何想法?你能帮我检查一下修改过的部分吗? – hyperfkcb