gpt4 book ai didi

c - 为什么 Visual Studio C 编译器不喜欢这样呢?

转载 作者:行者123 更新时间:2023-12-01 18:59:40 24 4
gpt4 key购买 nike

以下代码在 Linux 上使用 gcc -std=c99 可以正常编译,但在 Visual Studio 2010 C 编译器上出现以下错误:

Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86Copyright (C) Microsoft Corporation.  All rights reserved.fib.cfib.c(42) : error C2057: expected constant expressionfib.c(42) : error C2466: cannot allocate an array of constant size 0fib.c(42) : error C2133: 'num' : unknown size

The user inputs the amount of Fibonacci numbers to generate. I'm curious as to why the Microsoft compiler doesn't like this code.

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

void fib(int max);

int main(int argc, char *argv[])
{
int argument;

if (argc != 2)
{
puts("You must supply exactly one command line argument.");
return 0;
}

argument = atoi(argv[1]);

if (argument == 0)
{
puts("You gave us 0 or an invalid integer.");
return 0;
}
else if (argument < 0)
{
puts("You gave us a negative integer.");
return 0;
}
else if (argument == INT_MAX)
{
puts("You gave us a number that's too big to fit in an integer.");
return 0;
}

printf("%d\n", argument);
fib(argument);
return 0;
}

void fib(int max)
{
int num[max]; /// <- Line 42

int i;
for (i = 0; i < max; i++)
{
if (i == 0)
num[i] = 0;
else if (i == 1)
num[i] = 1;
else
num[i] = num[i-1] + num[i-2];

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

最佳答案

void fib(int max)
{
int num[max];

微软的 C 编译器不支持 C99,我相信他们已经说过永远不会支持。这意味着数组只能声明为常量大小。

关于c - 为什么 Visual Studio C 编译器不喜欢这样呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8146280/

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