如何使用指针打印2维数组

时间:2015-03-26 03:58:50

标签: c arrays pointers

如何使用指针打印数组中的其他元素?我可以用指针所指向的数组的第一个元素来完成它,但我很困惑用二维数组来做它。

#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

2 个答案:

答案 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]);
}