作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我无法打印使用读取函数中的动态内存分配构建的矩阵。请指导我将值从 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/
Feel free to skip straight to TL/DR if you're not interested in details of the question 简短的序言: 我最近决定
我一直在阅读 A Tour of Go学习Go-Lang到目前为止一切顺利。 我目前在 Struct Fields类(class),这是右侧的示例代码: package main import "fm
Last time I got confused顺便说一下PowerShell急切地展开集合,基思总结了它的启发式如下: Putting the results (an array) within a
我是一名优秀的程序员,十分优秀!