繁体   English   中英

在C中动态分配的二维(双精度)数组

[英]Dynamically allocated two dimensional (double) array in C

我正在尝试动态分配所有元素都加倍的二维数组N + 1xN。 然后,我想为数组的每个元素添加值(1.6)。 最后一步是打印此数组。 我的功能

void inic(double **t)
{
    for(int y=0;y<N;y++)
    {
        for(int x=0;x<N+1;x++)
        {
            t[x][y]=1.5;
        }
    }
}

无法正常工作,我也不知道为什么。

例如,(对于n = 3)结果为:

[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");
}

尝试将t[x][y]替换为t[y][x]

您使用了错误的转换说明符。 尝试以下

printf("%lf ",t[x][y]);

同样,使用另一种索引顺序(当该语句

t=malloc((N)*sizeof(double*));

分配N个“行”,然后在循环中分配N +1个“列”

for(int i=0;i<N;i++)
{
    t[i]=malloc( ( N + 1 )*sizeof(double));
}

在这种情况下,其他功能看起来像

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");
    }
}

另外,您应该在程序末尾释放所有分配的内存。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM