gpt4 book ai didi

c - 如何使用指针打印二维数组

转载 作者:行者123 更新时间:2023-11-30 15:22:13 26 4
gpt4 key购买 nike

如何使用指针打印数组中的其他元素?我可以使用指针指向的数组的第一个元素来完成此操作,但我对使用二维数组执行此操作感到困惑。

#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

最佳答案

注释

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));
}
}

关于c - 如何使用指针打印二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29270870/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com