我们可以将更长的字符串分配给数组吗? [英] Can we assign longer string to array?

查看:74
本文介绍了我们可以将更长的字符串分配给数组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在线阅读后,我知道以下是C中未定义的行为:

After reading online, I have come to know that following are undefined behaviors in C:

  1. 访问数组外部的元素

  1. Accessing element outside array

char a2[4] = {'g','e','e','k','s'}; 
printf("a2[4]:%d,%c\n",a2[4],a2[4]); //last index of a2 is 3
                                     //so a2[4] is undefined

  • 数组初始化列表中有多余的元素

  • Having excess elements in array intializing list

    int arr[3] = {1, 2, 3, 4, 5}; //size of arr is 3, but we specified 5 elements
                                  //undefined behavior
    

  • 我想问以下相关场景中涉及指针和字符串的行为是否未定义:

    I want to ask if behavior in the following related scenario's involving pointers and strings are undefined or not:

    1. 将更长的字符串分配给字符数组:

    1. Assigning longer string to character array:

    char arr[5] = "geeks"; //"geeks" contains 6 characters including `\0`
                           //but arr has size 5
    

  • 使用指针访问更远的索引.

  • Accessing farther index with pointer.

    char * arrptr = arr; //variable arr from point 1
    

    char * arrptr = "geeks";
    

    然后做

    printf("%c",arrptr[7]); 
    

    我相信这肯定是不确定的,因为索引7在当前上下文中不属于任何内容.

    I believe this must be surely undefined as index 7 does not belong to anything in current context.

    任何人都可以澄清这一点或将我指向C标准的相关部分吗?

    Can anyone clarify this or point me to the relevant section in C standard?

    推荐答案

    char arr1[5] = "geeks"; // extra '\0': ok
    char arr2[4] = "geeks"; // extra 's' and '\0': error
    

    '\0'作为一个额外元素将char数组初始化是一种特殊情况.参见 C11 6.7.9p14 (强调是我的)

    Initialization of char arrays with '\0' as one extra element is a special case. See C11 6.7.9p14 (emphasis is mine)

    可以通过字符串文字或UTF-8字符串文字来初始化字符类型的数组,并可选地将其括在大括号中.字符串文字的连续字节(,如果有空间,或者如果数组的大小未知,则包括终止空字符;)会初始化数组的元素.

    An array of character type may be initialized by a character string literal or UTF-8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

    这篇关于我们可以将更长的字符串分配给数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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