2013-01-05 43 views
1

我尝试以下:C中的数组初始化:tmp.c:5:错误:预期表达之前 '{' 令牌

#include <stdio.h> 

int main(void) { 
    char multi[3][10]; 
    multi[0] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; 
    multi[1] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}; 
    multi[2] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'}; 
    printf("&multi[2][2]: %d \n", (int) &multi[2][2]); 
    printf("(*multi + 2) + 2: %d \n" , (int) (*multi + 2) + 2); 
} 

并且得到以下输出:

[email protected]:~$ gcc tmp.c 
tmp.c: In function ‘main’: 
tmp.c:5: error: expected expression before ‘{’ token 
tmp.c:6: error: expected expression before ‘{’ token 
tmp.c:7: error: expected expression before ‘{’ token 

我已经做了一些研究和发现this thread其中弗拉基米尔陈述“你应该初始化你的阵列在你宣布他们的同一行”。这仍然让我感到困惑,难道我不应该这样做,因为你不应该写意大利面代码,或者这意味着你不能这样做。

或者我可以做其他事情完全错误吗?

+3

这意味着你必须在与声明相同的语句中初始化它。合并四个陈述。 – chris

+1

http://stackoverflow.com/a/202277/1824407 – user1824407

+0

注意;使用'%p'来打印指针,而不要'(int)'。 –

回答

2

以这种方式可以初始化数组,但是不分配数组。

#include <stdio.h> 

int main(void) { 
    char multi[3][10] = { 
     {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}, 
     {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}, 
     {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'} 
    } 
    printf("&multi[2][2]: %d \n", (int) &multi[2][2]); 
    printf("(*multi + 2) + 2: %d \n" , (int) (*multi + 2) + 2); 
} 

另请注意,这会截断至少在64位系统上打印出的堆栈地址。你想打印出堆栈地址吗?这样做:

printf("&multi[2][2]: %p\n", (char *) &multi[2][2]); 
printf("(*multi + 2) + 2: %p\n" , (char *) (*multi + 2) + 2); 

在我的系统,这种变化将导致其打印出正确的地址,这是不到2 (以上0x7fff00000000),这超出int范围。

+0

如果它们是_really_堆栈地址,那么对于打印目的而言截断可能并不重要。 –

+1

@JanDvorak:为什么?在我的系统中,这些高位有数据... –

+0

同意 - 但低位32位通常非常擅长区分变量。也就是说,在开始接近4GB限制之前,您不会开始获取虚假副本。 –

相关问题