在字符串中使用下划线[关闭]

问题描述 投票:-2回答:6

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

是什么造成的?有没有办法逃脱下划线的char?

谢谢。

有关更多信息,请参阅此代码:

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
c string
6个回答
4
投票

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

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

3
投票

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

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

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"};

1
投票

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


1
投票

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


1
投票

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

char *str_ex[ARRSIZE] = ....

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.