gpt4 book ai didi

代码在 Windows 中有效,但在 Linux 中无效!为什么? 【简单的指针问题】

转载 作者:可可西里 更新时间:2023-11-01 10:39:45 24 4
gpt4 key购买 nike

这是运输问题的工作代码片段(删除了实际功能。这里只有输入和输出功能。顺便说一句,这是不正确的)

# include <stdio.h>
# include <stdlib.h>

typedef struct transport
{
int cost;
int alloc;
}TRAN;

void problem_input (TRAN **, int *, int *, int, int);
void problem_display (TRAN **, int *, int *, int, int);

int main()
{
int n_dest;
int n_org;
int i;
int j;

printf("\n\n\tEnter Number Of Destinations : ");
scanf("%d", &n_dest);

printf("\n\n\tEnter Number Of Origins(Sub-stations) : ");
scanf("%d", &n_org);

TRAN ** array = (TRAN **)calloc(n_org, sizeof(TRAN *));

int * dest = (int *)calloc(n_dest, sizeof(int));
int * origins = (int *)calloc(n_org, sizeof(int));

for(i = 0; i < n_org; i++)
{
array[i] = (TRAN *)calloc(n_dest, sizeof(TRAN *));
}

problem_input (array, dest, origins, n_dest, n_org);
problem_display (array, dest, origins, n_dest, n_org);

printf("\n\n");

return 0;
}

void problem_input (TRAN ** array, int * dest, int * origins, int n_dest, int n_org)
{
int i;
int j;

printf("\n\n\tEnter The Amount Of Supplies Required At The Destinations : ");

for(i = 0; i < n_dest; i++)
{
printf("\n\n\t\tDestination %d : ", (i+1));
scanf("%d", &dest[i]);
}

printf("\n\n\tEnter The Amount Of Supplies Available At The Origins : ");

for(i = 0; i < n_org; i++)
{
printf("\n\n\t\tOrigin %d : ", (i+1));
scanf("%d", &origins[i]);
}

printf("\n\n\tEnter The Cost Matrix : ");

for(i = 0; i < n_org; i++)
{
printf("\n\n\t\tOrigin %d", (i+1));

for(j = 0; j < n_dest; j++)
{
printf("\n\n\t\t\tDestination %d : ", (j+1));

scanf("%d", &array[i][j].cost);
}
}
}

void problem_display (TRAN ** array, int * dest, int * origins, int n_dest, int n_org)
{
int i;
int j;

printf("\n\n\tThe Given Transportation Problem : ");

for(i = 0; i < n_org; i++)
{
printf("\n\n\t");

for(j = 0; j < n_dest; j++)
{
printf("\t%d", array[i][j].cost);
}

printf("\t[%d]", origins[i]);
}

printf("\n\n\t");

for(i = 0; i < n_dest; i++)
{
printf("\t[%d]", dest[i]);
}
}

这在 Windows 中运行良好,但在 Linux 中显示不正确的输出。 (我在家里使用 Windows,但在大学里使用 Linux。想象一下当我在教授面前得到错误的输出时我的感受。但她一点也不聪明。)

例如,我在 TRAN ** array 中输入的 'cost' 是

1 2 3
4 5 6
7 8 9

但是输出是这样的

1 2 4
4 5 7
7 8 9

我的错误是在创建结构的过程中。我像这样创建二维数组(非常标准)

    TRAN ** array   = (TRAN **)calloc(n_org, sizeof(TRAN *));

for(i = 0; i < n_org; i++)
{
array[i] = (TRAN *)calloc(n_dest, sizeof(TRAN));
}

但错误的是,我在 for 循环中这样做了

    for(i = 0; i < n_org; i++)
{
array[i] = (TRAN *)calloc(n_dest, sizeof(TRAN *));
}

那是 sizeof(TRAN *) 而不是 sizeof(TRAN)

所以我的问题是,为什么这个明显的错误没有在 Windows 中显示?

最佳答案

可能发生的情况是类型在不同操作系统上的大小不同。结果可能是,在 Windows 上,sizeof(TRAN) == sizeof(TRAN*)(基于 TRAN 和 sizeof(int) 中的元素),而在 linux 上,情况显然不是这样。

关于代码在 Windows 中有效,但在 Linux 中无效!为什么? 【简单的指针问题】,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6081214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com