由variable-sized  may not be initialized想到的

由variable-sized may not be initialized想到的

作者:LAMP小白  点击:4867  发布日期:2012-09-25 01:52:00  返回列表

今天照着例子写了段代码

#include mio_lt;stdio.hmio_gt;
const size_t SIZE = 20; // 4bytes in 32OS 8bytes in 64OS
int main(void)
{
    const size_t SIZE = 20;
    int valueCount = 10;
    int byteCount = 0;
    int i = 0;
    int j = 0;
    float fpl = 0.0;
    char words1[SIZE] = "";
    char words2[SIZE] = "";
    valueCount = scanf("%f %d %d %[abcdefghijklmnopqrstovwxyz] %*ld %s%n", mio_amp;fpl, mio_amp;i, mio_amp;j, words1, words2, mio_amp;byteCount);
    printf("nCount of bytes read=%dn", byteCount);
    printf("nCount of values read=%dn", valueCount);
    printf("nfpl=%f i=%d j=%dn", fpl, i, j);
    printf("nwords1=%s words2=%sn", words1, words2);
    return 0;
}

错误:可变大小的物体可能不被初始化但是编译时报错
c:12: error: variable-sized object may not be initialized

检查发现是我的数组声明出错了,出错的原因是使用了char words1[SIZE] = mio_quot;mio_quot;;
但是SIZE我明明定义是size_t 20啊

查了下帖子总结的原因如下:
C使用gcc编译器,C++使用g++编译器。虽然const就是常量(constant)。但这并不是真的。在C中,const仅仅表示其所修饰对象不可修改。常量和所谓“不可修改”有什么区别呢?C中,const int N = 10; 这样的语句声明了一个整型数据,声明之后你不能再为其赋值,此即为不可修改。但在C中,N却不是常量,而诸如372, 3.72, ‘A’之类才是常量,在C中定义常量通常使用#define。而在C++中,const int N = 10; 就会定义N为常量。
所以gcc报错

但用define去定义呢?同样不行

int ii = SIZE;
float fpl = 0.0;
char words1[ii] = "";
char words2[ii] = "";

必须在函数内部用一个变量去接住这个SIZES才行

这个是什么原因还有待查询(查不到啊!!!)


解决的方法其实不可思议,定义一个变量反而就可以了,不过这样做并不好,理由是
gcc生成的汇编代码:
有90多行

.file "main.c"
.text
.globl main
.type main, @function
main:
leal 4(%esp), %ecx
andl $-16, %esp
pushl -4(%ecx)
pushl %ebp
movl %esp, %ebp
pushl %esi
pushl %ebx
pushl %ecx
subl $60, %esp
movl %ecx, %eax
movl 4(%eax), %eax
movl %eax, -44(%ebp)
movl %gs:20, %eax
movl %eax, -28(%ebp)
[ ... ] # 此处略去n行
movl %ecx, %esp
movl -28(%ebp), %edx
xorl %gs:20, %edx
je .L3
call __stack_chk_fail
.L3:
leal -12(%ebp), %esp
addl $0, %esp
popl %ecx
popl %ebx
popl %esi
popl %ebp
leal -4(%ecx), %esp
ret



使用g++(常量方式)编译生成的汇编文件只有23行

换编译器?或者默默忍受?或者找到更好的办法?希望如此..

.file "main.c"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
.cfi_personality 0x0,__gxx_personality_v0
pushl %ebp
.cfi_def_cfa_offset 8
movl %esp, %ebp
.cfi_offset 5, -8
.cfi_def_cfa_register 5
subl $48, %esp
movl $10, -4(%ebp)
movl $0, %eax
leave
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (Ubuntu 4.4.3-4ubuntu5) 4.4.3"
.section .note.GNU-stack,"",@progbits




上一篇:SecureCRT7.0 64位下载 下一篇:快递查询API
0