0

How can I print the other elements in the array using pointers? I can do it with the first element of the array which the pointer is pointing to but I am confused in doing it with two dimensional arrays.

#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 Answers 2

1

Notes

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 should be char ** pID to traverse over the matrix

  • To print all of the array content inside the function dispInfo you need to pass size of the array

Solution

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));
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

in your program, pID and pHP will be pointing to the last inputs entered by you so don't use pID and pHP to print data. You are maintaining number of inputs entered in Ecount variable, use it to print data like below.

for(int i=0;i<Ecount;i++)
{
    dispInfo(ID[i],&HP[i]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.