C: main() 返回一个数组总是等于 56

标签 c shell program-entry-point exitstatus

我想知道当我使用 main 函数的返回值时会发生什么。

我发现如果我从 main 返回一个数组变量(应该是退出状态)并在 shell 中打印退出状态,输出总是 56。我想知道为什么?

C 程序:

int* main(void) {
    static int x[3];
    x[0]=89;
    x[1]=15;
    x[2]=10;
    return x;
} 

我测试如下:

gcc array_return.c -o array_return
./array_return
echo $?

输出始终是 56,即使我更改数组的大小或更改其中的数字也是如此。数字 56 是什么意思?

最佳答案

您的程序返回一个指针。它不是您在问题中提出的“数组”。因为数组的名称计算为其第一项的地址(与数组本身的地址相同)。

在 C 中,main 函数返回的值被解释为 exit status ,即您的示例中使用的 $? 变量。

我猜,您正在运行 Bash shell,因为在 Bash 中,退出状态存储在 $? 变量中。指针通常是一个大数字,至少大于255,这是最大值exit code in Bash。 :

Out of range exit values can result in unexpected exit codes. An exit value greater than 255 returns an exit code modulo 256. For example, exit 3809 gives an exit code of 225 (3809 % 256 = 225).

现在让我们通过打印变量的地址和地址 modulo 来修改您的程序。 256:

#include <stdio.h>

int main(void) {
    static int x[3];
    printf("%ld ==> %d\n", (size_t)x, (size_t)x % 256);
    return (int)x;
}

让我们编译它并测试我是否正确:

$ gcc -Wall -g test.c -o test && ./test; echo $?
test.c: In function ‘main’:
test.c:6:12: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
     return (int)x;
            ^
6295620 ==> 68
68

如我们所见,返回状态等于 6295620 % 256,如 official documentation 中所述.

关于C: main() 返回一个数组总是等于 56,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39933240/

相关文章:

c - Beaglebone Black 启用 PRU 问题

c - 循环二维数组中所有邻居对(2 点团)的高效算法

C - 在 999 以上加小数位和四舍五入

c - 编译器如何知道我的 main 函数在哪里?

c - 如何使用.so文件作为c中的主要参数?

c++ - 如何从核心转储文件中识别导致崩溃的完整命令

arrays - Bash 数组 : Unexpected Syntax error

linux - bash - 将 ls 重定向到自定义脚本

c - 用 C 写一个 shell,不返回任何东西

c++ - Cpp main 方法 const 声明