我正在尝试使用指针实现矩阵。代码似乎是正确的,但程序在打印数组的第一行后挂起。
int main ()
{
int **a;
int i,j;
int count = 1;
for (i = 0; i < 4; i++)
{
for(j = 0; j < 4; j++)
{
*(*(a + i) + j) = count;
count += 1;
printf("%d\t", *(*(a + i) + j));
}
}
}
最佳答案
这会起作用!
#include<stdio.h>
#include<stdlib.h>
int main ()
{
int **a;
int i,j;
int count = 1;
// Allocate memory and populate
a = malloc(4*sizeof(int*));
for (i = 0; i < 4; i++)
{
a[i] = malloc(4*sizeof(int));
for(j = 0; j < 4; j++)
{
*(*(a + i) + j) = count;
count += 1;
printf("%d\t", *(*(a + i) + j));
}
printf("\n");
}
//Now free the allocated memory
for ( i = 0; i < 4; i++)
{
free(a[i]);
}
free(a);
return 0;
}
**a
只是指向指针的指针,但是在您的代码中您没有指定该指针应指向的位置。
首先,您需要在使用前分配内存,然后执行所需的操作(填充、读取、写入等),一旦您不再需要它,请释放分配的内存。
关于代码似乎是正确的,但程序在打印数组的第一行后挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25593754/