在字符串中使用下划线

时间:2012-12-08 13:23:24

标签: c string

我试图在字符串中使用下划线,但它似乎使编译器为char数组分配更少的字节并运行结束字符(' \ 0')。

是什么导致这个? 有没有办法逃脱下划线的字符?

感谢。

有关详细信息,请参阅此代码:

code:
#include<stdio.h>
#define ARRSIZE 6

char str_ex[][ARRSIZE] = {"aaaa", "bbbb_bbbb", "cccc", "dddd", "ffff_ffff", "eeee"};

int main(void)
{
    int i;
    for(i=0; i<ARRSIZE; i++)
        printf("%s\n", str_ex[i]);
    return 0;
}

compile:
user@ubuntu:~/test$ gcc -g test.c -o test -Wall -ansi
test.c:4:1: warning: initializer-string for array of chars is too long [enabled by default]
test.c:4:1: warning: (near initialization for ‘str_ex[1]’) [enabled by default]
test.c:4:1: warning: initializer-string for array of chars is too long [enabled by default]
test.c:4:1: warning: (near initialization for ‘str_ex[4]’) [enabled by default]

output:
user@ubuntu:~/test$ ./test
aaaa
bbbb_bcccc
cccc
dddd
ffff_feeee
eeee

6 个答案:

答案 0 :(得分:4)

在您的代码中ARRSIZE不确定数组的大小,而是每个子数组的大小。所以你告诉它将bbbb_bbbb存储在6个字符中。也许你可以存储指针:

const char *str_ex[] = {....};

答案 1 :(得分:3)

这不是因为下划线,而是因为您调整数组大小的方式:您将元素限制为六个字符,带下划线的元素是唯一运行该长度的元素;其他四个字符串只需要五个char s,因此它们适合六个元素。

您应该将此声明为指针数组,如此

char *str_ex[ARRSIZE] = {"aaaa", "bbbb_bbbb", "cccc", "dddd", "ffff_ffff", "eeee"};

或给你的字符串更多空间,如下:

char str_ex[10][ARRSIZE] = {"aaaa", "bbbb_bbbb", "cccc", "dddd", "ffff_ffff", "eeee"};

答案 2 :(得分:1)

您将str_ex声明为数组数组,每个子数组为6个字符,这意味着字符串只能是5个字符(加上终止'\0')。你有几个超过5个字符的字符串,这是编译器警告的。

答案 3 :(得分:1)

每个字符串的长度最多应为ARRSIZE字符,但带下划线的字符串较大。

答案 4 :(得分:1)

您正在设置错误的尺寸。 试试这个:

char *str_ex[ARRSIZE] = ....

这将起作用,因为您使用静态数据初始化C字符串数组。

答案 5 :(得分:0)

ARRSIZE是指为每个字符串分配的字符数。问题是ARRSIZE6,而"bbbb_bbbb""ffff_ffff"都超过六个字符。下划线无关紧要。