以下 C 代码在 32 位 Linux 上运行良好,但在 64 位系统上运行不佳:
#define MAX 5
int change(int** ns) {
ns[0] = 111;
ns[1] = 222;
ns[2] = 333;
}
int main() {
int i, nums[MAX];
memset(nums, 0, sizeof(nums));
change((int**) &nums);
for (i = 0; i < MAX; i++)
printf("nums[%d] = %d\n", i, nums[i]);
return 0;
}
Linux 32 位 (x86):
$ uname -a
Linux host-1549776 3.2.0-58-generic-pae #88-Ubuntu SMP Tue Dec 3 18:00:02 UTC 2013 i686 i686 i386 GNU/Linux
$ gcc inta.c -o inta
$ ./inta
nums[0] = 111
nums[1] = 222
nums[2] = 333
nums[3] = 0
nums[4] = 0
Linux 64 位 (x86_64):
$ uname -a
Linux host-1530141 2.6.32-504.12.2.el6.x86_64 #1 SMP Wed Mar 11 22:03:14 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
$ gcc inta.c -o inta
$ ./inta
nums[0] = 111
nums[1] = 0
nums[2] = 222
nums[3] = 0
nums[4] = 333
我读到 C 中的整数指针在 32 位中为 4 个字节,在 64 位中为 8 个字节,但无论如何我都不知道如何解决这个问题以使其成为可移植代码架构。
有什么建议吗?
最佳答案
一个好的调试器将帮助您找到简单问题的编译时错误和警告,例如您的代码中存在的问题。例如:
当我尝试在打开所有警告(CLANG)的情况下编译它时,问题清楚地显示在警告中:
play_6.c - 5 warnings
5,9 warning: incompatible integer to pointer conversion assigning to 'int *' from 'int'[-Wpointer-int-conv]
6,9 warning: incompatible integer to pointer conversion assigning to 'int *' from 'int'[-Wpointer-int-conv]
7,9 warning: incompatible integer to pointer conversion assigning to 'int *' from 'int'[-Wpointer-int-conv]
8,1 warning: function does not return a value [-Wreturn-type]
10,5 warning: function declaration isnt a prototype. [-Wstrict-prototypes]
您正在尝试非法指针转换
int change(int** ns) {
ns[0] = 111; //here
ns[1] = 222; //here
ns[2] = 333; //here
return 0; //add return statement here
}
为了解决这些问题:
在 main 中更改此行:
change((int**) &nums);//nums is already a pointer, no need to dereference
//and casting to int ** is also a problem
到
change( nums);
并更改您的原型(prototype):
int change(int** ns) {
到:
int change(int* ns) {
接下来,在change
函数中添加return语句。
注意:在您的函数定义中:
int change(int* ns);
第一个 int
表示您希望函数返回一个 int
值。如果您想在不需要返回的情况下使用该函数,请将其创建为:
void change(int *ns);
最后,当我运行你的代码时,在 32 位或 64 位目标中进行上述更改,结果是相同的:
nums[0] = 111
nums[1] = 222
nums[2] = 333
nums[3] = 0
nums[4] = 0
关于C 中的代码 : issue on int array function argument in 64-bit systems,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34045306/