gpt4 book ai didi

我们可以将更长的字符串分配给数组吗?

转载 作者:太空宇宙 更新时间:2023-11-04 06:49:21 25 4
gpt4 key购买 nike

在网上看了之后,我了解到以下是C中未定义的行为:

  1. 访问数组外的元素

    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
  2. 数组初始化列表中有多余的元素

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

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

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

    char arr[5] = "geeks"; //"geeks" contains 6 characters including `\0`
    //but arr has size 5
  2. 使用指针访问更远的索引。

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

    char * arrptr = "geeks";

    然后做

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

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

谁能澄清这一点或指出 C 标准中的相关部分?

最佳答案

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

使用 '\0' 作为一个额外元素来初始化 char 数组是一种特殊情况。参见 C11 6.7.9p14 (重点是我的)

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.

关于我们可以将更长的字符串分配给数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53682351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com