[英]Why can't I print the values that are stored in the created array?
So a user can create his square matrix and enter the desired values. 因此,用户可以创建他的方矩阵并输入所需的值。 The thing is that the matrix is created via a function and it seems that when the function is done with its task and we return to the main function and I try to reprint the elements of the matrix,to check if everything is ok again after the first printing inside the function, the program crashes.
事实是,矩阵是通过一个函数创建的,似乎当函数完成其任务后,我们返回到主函数,我尝试重新打印矩阵的元素,以检查矩阵生成后是否一切正常首先在函数内部打印,程序崩溃。 Have in mind that I'm using pointers only and not []s.
请记住,我仅使用指针,而不是[]。 Also the size variable is going to be used in functions that check various properties of the matrix(sparse etc) so that's why I use it like this.
另外,size变量将用在检查矩阵的各种属性(稀疏等)的函数中,这就是为什么我这样使用它。
#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;
}
Your pointer is passed by value. 您的指针按值传递。 If you want to modify from within the function, you need to pass its address.
如果要从函数内部进行修改,则需要传递其地址。 You then need to re-adjust all lines within CreateArray that accessed ptr to dereference it once more:
然后,您需要重新调整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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.