如何使用指针打印数组中的其他元素?我可以用指针所指向的数组的第一个元素来完成它,但我很困惑用二维数组来做它。
#include <stdio.h>
#include <stdlib.h>
void getInfo(char* pID, int* pHP);
void dispInfo(char* pID, int* pHP);
int main()
{
//declarations
char ID[100][15] = {""}; //char* pID[100];
char* pID = &ID[0][0];
int HP[100] = {0};
int* pHP = &HP[0];
int answer = 0;
int Ecount = 0;//keep count of engines input/processed
//input
do {
getInfo(pID + Ecount, pHP + Ecount);
Ecount++;
printf("More? 1 for yes 0 for no: ");
scanf("%d", &answer);
}while(answer != 0);
//output
dispInfo(pID, pHP);
return 0;
}
void getInfo(char* pID, int* pHP)
{
printf("Enter engine ID: ");
scanf("%s", pID);
printf("Enter engine HP: ");
scanf("%d", pHP);
}//end getInfo
void dispInfo(char* pID, int* pHP)
{
printf("Engine ID: %s\n", pID);
printf("Engine HP: %d\n", *pHP);
}//end dispInfo
答案 0 :(得分:1)
备注强>
int main()
{
char ID[100][15] = {""};
char* pID = &ID[0][0];
int HP[100] = {0};
int* pHP = &HP[0];
..
dispInfo(pID, pHP);
return 0;
}
void dispInfo(char* pID, int* pHP)
{
printf("Engine ID: %s\n", pID);
printf("Engine HP: %d\n", *pHP);
}
char * pID
应该char ** pID
遍历矩阵
要打印函数dispInfo
内的所有数组内容,您需要传递数组的大小
<强>解决方案强>
int main()
{
const int SIZE = 100;
char ID[SIZE][15] = { "" };
char ** pID = &ID[0];
int HP[SIZE] = { 0 };
int * pHP = &HP[0];
..
dispInfo(pID, pHP, SIZE);
return 0;
}
void dispInfo(char ** pID, int * pHP, const int SIZE)
{
for (int i=0; i<SIZE; i++)
{
printf("Engine ID: %s\n", *(pID+i));
printf("Engine HP: %d\n", *(pHP+i));
}
}
答案 1 :(得分:0)
在您的程序中,pID和pHP将指向您输入的最后输入,因此请勿使用pID和pHP打印数据。您正在维护在Ecount变量中输入的输入数量,使用它来打印如下数据。
for(int i=0;i<Ecount;i++)
{
dispInfo(ID[i],&HP[i]);
}