C中动态分配的二维(双)数组 [英] Dynamically allocated two dimensional (double) array in C
问题描述
我正在尝试动态分配二维数组 N+1xN,所有元素都加倍.然后我想为数组的每个元素放置值 (1.6).最后一步是打印这个数组.我的功能
I'm trying to dynamically allocate two dimensional array N+1xN with all elements double. Then I want to put value (1.6) for each element of an array. The last step is to print this array. My function
void inic(double **t)
{
for(int y=0;y<N;y++)
{
for(int x=0;x<N+1;x++)
{
t[x][y]=1.5;
}
}
}
无法正常工作,我不知道为什么.
isn't working as it should and I don't know why.
例如(对于 n=3)结果是:
For example the (for n=3) result is:
[0][0][0][0]
[0][0][0][0]
[0][0][0][0]
我期望:
[1.6][1.6][1.6][1.6]
[1.6][1.6][1.6][1.6]
[1.6][1.6][1.6][1.6]
[1.6][1.6][1.6][1.6]
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
int N;
void inic(double **t)
{
for(int y=0;y<N;y++)
{
for(int x=0;x<N+1;x++)
{
t[x][y]=1.5;
}
}
}
void print(double **t)
{
for(int y=0;y<N;y++)
{
for(int x=0;x<N+1;x++)
{
printf("%i ",t[x][y]);
}
printf("\n");
}
}
int main()
{
double **t;
N=3;
t=malloc((N+1)*sizeof(double*));
for(int i=0;i<N+1;i++)
{
t[i]=malloc(N*sizeof(double));
}
inic(t);
print(t);
printf("\n");
}
推荐答案
您使用了不正确的转换说明符.试试下面的
You are using incorrect conversion specifier. Try the following
printf("%lf ",t[x][y]);
此外,使用另一个索引顺序会更自然,即本声明
Also it would be more natural to use another order of the indices that is when this statement
t=malloc((N)*sizeof(double*));
分配N行",然后在循环中分配N+1列"
allocates N "rows" and then the N + 1 "columns" are allocated in the loop
for(int i=0;i<N;i++)
{
t[i]=malloc( ( N + 1 )*sizeof(double));
}
在这种情况下,其他函数看起来像
In this case other functions will look like
void inic(double **t)
{
for(int x = 0; x < N; x++)
{
for( int y = 0; y < N + 1; y++ )
{
t[x][y]=1.5;
}
}
}
void print(double **t)
{
for( int x = 0; x < N; x++ )
{
for( int y = 0; y < N + 1; y++)
{
printf("%lf ",t[x][y]);
}
printf("\n");
}
}
此外,您应该在程序结束时释放所有分配的内存.
Also you should free all the allocated memory at the end of the program.
这篇关于C中动态分配的二维(双)数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!