相关疑难解决方法(0)

可以使用const变量来声明C中数组的大小吗?

为什么以下代码会抛出错误?

const int a = 5;
int b[a]={1,2,3,4,5};
Run Code Online (Sandbox Code Playgroud)

而且当我尝试编译没有"const"关键字的上述代码时,我得到了同样的错误:

int a = 5; 
int b[a]={1,2,3,4,5};
Run Code Online (Sandbox Code Playgroud)

为什么会这样?我在这里做的错误是什么?

还有另一个问题:什么时候常量被代码中的实际值替换,即如果我声明一个变量说:const int x = 5; 我知道在RAM中没有为变量x分配内存,但是ROM中的常量变量区域保持值5,并且x在代码中出现x的地方简单地替换为值5.但这什么时候发生的?编译时间?启动时间?预处理时间?

PS:我说的是嵌入式C(在微控制器上运行等),而不是在桌面上运行的C. 因此嵌入式系统必然会有一个ROM(Flash,EEPROM ......).那会发生什么?

c arrays const

37
推荐指数
3
解决办法
3万
查看次数

我们可以给静态数组的大小一个变量

你好每一个我想问我已经读过我们只能通过使用指针和使用malloc或newlike来声明动态数组

int * array = new int[strlen(argv[2])];
Run Code Online (Sandbox Code Playgroud)

但我写了

int array[strlen(argv[2])];
Run Code Online (Sandbox Code Playgroud)

它没有给我任何错误

我已经读过静态数组只能通过给出常量数组大小来声明,但在这里我给了静态数组一个可变大小

为什么这么谢谢


是否可以安全使用,或者有可能在任何后期阶段它会产生问题我使用gcc linux

c c++

9
推荐指数
2
解决办法
3468
查看次数

C 存储大小不是常数...为什么?

这是简单的示例程序

#include <stdio.h>
#include <string.h>

const char *hello_string = "Hello";

int main(void)
{
char *world_string = " World";
static char hello_world[strlen(hello_string)+strlen(world_string)];
strcpy(&hello_world[0], hello_string);
strcat(&hello_world[0], world_string);
printf("%s\n", hello_world);
return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译器输出:

test.c: In function ‘main’:
test.c:9:13: error: storage size of ‘hello_world’ isn’t constant
static char hello_world[strlen(hello_string)+strlen(world_string)];
            ^
Run Code Online (Sandbox Code Playgroud)

我意识到在这种情况下完全无用和不必要地使用“静态”会导致错误,并且将其删除后,事情将可以正常编译。这只是一个简单的例子来说明我的问题。

我不明白的是为什么当“hello_string”被声明为const char *时,存储大小不是一个常量,并且它的大小在执行过程中不会改变。这只是编译器不够聪明不知道这一点的一个例子吗?

c size storage constants

7
推荐指数
2
解决办法
1万
查看次数

myArray [N],其中N = 1,000,000会返回错误,而myArray [1,000,000]则不会

文件扩展名:.cpp

我有以下代码:

int main() {
    int N; cin >> N;
    int myArray[N];
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果我输入N为1,000,000,那么当我尝试运行该程序时,我会收到错误.但是,当我设置myArray[N]myArray[1000000],它没有.为什么会这样?

c++ variable-length-array

2
推荐指数
1
解决办法
122
查看次数

无法编译固定大小的静态数组

最小代码示例:

#include <stdio.h>
int main()
{
    const int a = 5;
    static int b[a];
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

看起来很好,是吗?变量a是不变的.也适用于4.4.

gcc -v
gcc version 6.2.1 20160830 (GCC)
gcc 1.c
1.c: In function ‘main’:
1.c:6:16: error: storage size of ‘b’ isn’t constant
     static int b[a];
Run Code Online (Sandbox Code Playgroud)

顺便说一下,clang很好地编译了这段代码.

c gcc clang

1
推荐指数
1
解决办法
218
查看次数

标签 统计

c ×4

c++ ×2

arrays ×1

clang ×1

const ×1

constants ×1

gcc ×1

size ×1

storage ×1

variable-length-array ×1