gpt4 book ai didi

c - 我究竟做错了什么?如何将 read 函数中分配的内存传递给 disp 函数?

转载 作者:行者123 更新时间:2023-11-30 19:01:47 25 4
gpt4 key购买 nike

我无法打印使用读取函数中的动态内存分配构建的矩阵。请指导我将值从 read 传递到 disp 函数。

我尝试过在单指针中传递指针到指针,但我不知道双指针,请帮助我。

int i; //global
struct pass{
int row,col,ele;
} a1;

void disp(int** , struct pass);
void read(int** , struct pass);

void disp(int** p, struct pass a)
{
printf("the triplet representation is\n"); //program stops here everytime
for(i=0;i<=a.ele;i++){
if(i==0){
printf("row\t column\t element\n");
printf("%d\t %d\t %d\n", p[i][0], p[i][1], p[i][2] );
}
else
printf("%d\t %d\t %d\n", p[i][0], p[i][1], p[i][2] );
}
}

void read(int** p, struct pass a)
{
int i;
printf("enter no. rows, columns, elements\n");
scanf("%d %d %d", &a.row, &a.col, &a.ele);

p=(int* *)malloc(sizeof(int*)*(a.ele+1));

for(i=0;i<=a.ele;i++)
p[i]=(int *)malloc(3*sizeof(int));

p[0][0]=a.row; p[0][1]=a.col; p[0][2]=a.ele;

printf("enter rows, columns, and elements\n");
for(i=1;i<=a.ele;i++){
scanf("%d %d %d", &p[i][0], &p[i][1], &p[i][2]);
}
}

int main()
{
int **p1;
read(p1, a1);
disp(p1,a1);
}

预期的输出应该是要打印的稀疏矩阵,但在扫描元素后拒绝这样做。

最佳答案

我对您的程序做了一些更改。请参阅我在代码中的注释。

#include "stdio.h"
#include "stdlib.h"

/* It is better to declare counter variable like i locally. */
/*int i; //global*/

/* This struct is not really needed since its contents is part of the sparse matrix. */
/*struct pass {
int row, col, ele;
} a1;*/

void disp(int ** p)
{
printf("the triplet representation is\n"); //program stops here everytime
for (int i = 0; i <= p[0][2]; i++) {
if (i == 0) {
printf("row\t column\t element\n");
printf("%d\t %d\t %d\n", p[i][0], p[i][1], p[i][2]);
}
else
printf("%d\t %d\t %d\n", p[i][0], p[i][1], p[i][2]);
}
}

/* Reads sparse matrix and returns int ** pointer to it.
m[0] -> #rows, #cols, #elements
m[1] -> row index, col index, value
m[2] -> etc.
m[#eleents] -> ...

By returning pointer to sparse matrix, it makes code easier
to understand than passing a pointer to the sparse matrix,
that is int ***.
*/
int** read()
{
int i;
printf("enter no. rows, columns, elements\n");
int row, col, ele;;
scanf("%d %d %d", &row, &col, &ele);

int ** p = (int**)malloc(sizeof(int*)*(ele + 1));

for (i = 0; i <= ele; i++)
p[i] = (int *)malloc(3 * sizeof(int));

p[0][0] = row; p[0][1] = col; p[0][2] = ele;

printf("enter rows, columns, and elements\n");
for (i = 1; i <= ele; i++) {
scanf("%d %d %d", &p[i][0], &p[i][1], &p[i][2]);
}
return p;
}

int main()
{
int **p1 = read();
disp(p1);
}

关于c - 我究竟做错了什么?如何将 read 函数中分配的内存传递给 disp 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57235588/

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