初始化字符数组与较小的字符串文字 [英] Initializing char Array with Smaller String Literal

查看:159
本文介绍了初始化字符数组与较小的字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我写的:

 改编的char [8] =ABC;

有没有在什么改编[4] 可能是任何规格?我做了一些测试,
铛,似乎在数组中剩余的字符都设置为null。
此外,改编的char [8] =; 零的每个字节。不知道这是一个编译器
方便,规范行为,纯属巧合还是我听错了。


 作废()
{
    炭ARR [8] =ABC; / *断点这里,第3行* /
    的strcpy(ARR,1234567);
}
诠释的main()
{
    一个();
    一个();
    返回0;
}

调试器成绩单:


断点图1中,()在str.c:3
3炭ARR [8] =ABC;
(GDB)■
当前语言:汽车;目前最小的
4的strcpy(ARR,1234567);
(GDB)p ARR
$ 1 =ABC \\ 000 \\ 000 \\ 000 \\ 000
(GDB)C
继续。断点图1中,()在str.c:3
3炭ARR [8] =ABC;
(GDB)p ARR
$ 2 =1234567
(GDB)■
4的strcpy(ARR,1234567);
(GDB)p ARR
$ 3 =ABC \\ 000 \\ 000 \\ 000 \\ 000


解决方案

这是标准行为。

改编[3] 是因为终止0是字符串的一部分初始化为0的文字。

所有剩余的元素都被初始化为0太 - ISO / IEC 9899: 1999年,6.7.8,21:


  

如果有一个大括号括起来的列表更少的初始化值多于元件或部件
  聚合,或在一个字符串更少的字符的字面用于初始化的已知阵列
  尺寸比有数组中的元素,将总的剩余部分应
  初始化隐含一样具有静态存储持续时间的对象。


字符与静态存储对象被初始化为0。

If I write:

char arr[8] = "abc";

Is there any specification over what arr[4] might be? I did some tests with Clang and it seems that the remaining chars in the array are set to null. Also, char arr[8] = ""; zeroes every byte. Not sure if this is a compiler convenience, standard behavior, pure coincidence or I got it wrong.


void a()
{
    char arr[8] = "abc";    /* breakpoint here, line 3 */
    strcpy(arr, "1234567");
}
int main()
{
    a();
    a();
    return 0;
}

Debugger transcript:

Breakpoint 1, a () at str.c:3
3           char arr[8] = "abc";
(gdb) s
Current language:  auto; currently minimal
4           strcpy(arr, "1234567");
(gdb) p arr
$1 = "abc\000\000\000\000"
(gdb) c      
Continuing.

Breakpoint 1, a () at str.c:3
3           char arr[8] = "abc";
(gdb) p arr
$2 = "1234567"
(gdb) s
4           strcpy(arr, "1234567");
(gdb) p arr
$3 = "abc\000\000\000\000"

解决方案

It's standard behavior.

arr[3] is initialized to 0 because the terminating 0 is part of the string literal.

All remaining elements are initialized to 0 too -- ISO/IEC 9899:1999, 6.7.8, 21:

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

And char objects with static storage are initialized to 0.

这篇关于初始化字符数组与较小的字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆