[英]Finding an element in multi dimensional array in C Programming
當我嘗試在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”。 相反,它給我帶來了No - no這樣的名字:-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;
}
}
}
}
你不想使用nameptr[row][col] == target
,你想用strcmp(nameptr[row][col],target) == 0
替換它。 ==
比較指針(內存地址), strcmp
比較字符串的實際值,並在匹配時返回0
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.