因此用户可以创建他的方阵并输入所需的值。问题是矩阵是通过函数创建的,似乎当函数完成其任务时,我们返回主函数,我尝试重新打印矩阵的元素,以检查在第一次在函数内部打印,程序崩溃了。请记住,我仅使用指针而不是 []。此外,大小变量将在检查矩阵的各种属性(稀疏等)的函数中使用,这就是我这样使用它的原因。
#include <stdio.h>
#include <stdlib.h>
int CreateArray(int **ptr);
int main()
{
int **ptr = NULL;
int size = 0;
int i,j;
size = CreateArray(ptr);
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
printf("%d",*(*(ptr+i)+j));
if(j == (size-1))
{
printf("\n");
}
}
}
system("PAUSE");
return 0;
}
int CreateArray(int **ptr)
{
int i=0;
int j=0;
int size = 0;
printf("Input the size of your square matrix\n");
scanf("%d", &size);
ptr = malloc(sizeof(int*)*size);
for(i=0; i< size; i++)
{
*(ptr + i) = malloc(sizeof(int)*size);
}
printf("Enter the values to be stored in your array\n");
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
scanf("%d", &*(*(ptr+i)+j));
}
}
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
printf("%d",*(*(ptr+i)+j));
if(j == (size-1))
{
printf("\n");
}
}
}
return size;
}
最佳答案
您的指针是按值传递的。如果要从函数内部进行修改,则需要传递其地址。然后,您需要重新调整 CreateArray 中访问 ptr 的所有行以再次取消引用它:
int main()
{
int **ptr = NULL;
int size = 0;
int i,j;
size = CreateArray(&ptr);
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
printf("%d ",*(*(ptr+i)+j));
if(j == (size-1))
{
printf("\n");
}
}
}
return 0;
}
int CreateArray(int ***ptr)
{
int i=0;
int j=0;
int size = 0;
printf("Input the size of your square matrix\n");
scanf("%d", &size);
*ptr = malloc(sizeof(int*)*size);
for(i=0; i< size; i++)
{
*((*ptr) + i) = (int*)malloc(sizeof(int)*size);
}
printf("Enter the values to be stored in your array\n");
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
scanf("%d", (*((*ptr)+i)+j));
}
}
return size;
}
关于c - 为什么我无法打印存储在创建的数组中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22212963/