gpt4 book ai didi

c - 字符数组的 strlen 和大小

转载 作者:行者123 更新时间:2023-12-02 07:33:43 24 4
gpt4 key购买 nike

我有以下代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char p[5];
char q[]="Hello";
int i=0;

strcpy(p,"Hello");
printf("strlen(p)=%d\n",strlen(p));
printf("sizeof(p)=%d\n",sizeof(p));
printf("strlen(q)=%d\n",strlen(q));
printf("sizeof(q)=%d\n",sizeof(q));
for(i=0;i<6;i++)
{
printf("p[%d]=%c\tq[%d]=%c\n",i,p[i],i,q[i]);
}
return 0;
}

我得到的输出是:

strlen(p)=5
sizeof(p)=5
strlen(q)=5
sizeof(q)=6
p[0]=H q[0]=H
p[1]=e q[1]=e
p[2]=l q[2]=l
p[3]=l q[3]=l
p[4]=o q[4]=o
p[5]= q[5]=
  1. 我知道像 q[]="some string"这样声明数组会将数组的大小设置为字符串 const 中的字符数,但为什么这两种类型的 sizeof() 输出不同数组声明?
  2. strlen() 和 printf() 如何知道何时停止,声明这两个数组时没有添加空字符。

最佳答案

您的问题中有多个问题。

strcpy(p,"Hello");
  • 这是非法的,因为 p 只有 5 个字符长,所以 没有空间留给 strcpy 添加的终止 0。因此它是要么不是以 0 结尾,要么是 0 字节被添加到可用的之外空格 - 在其上调用 strlen 也是未定义的行为或有问题最少

  • p 上调用 sizeof 没问题,并产生正确的值 5。

  • 调用 strlen(q) 产生 5 因为 q 确实包含一个 0 终止符 - 通过使用字符串文字初始化隐式添加 - 之前有 5 个字符0

  • 因为它包含一个 0 终止符,q 实际上是一个 6 的数组字符 所以 sizeof 产生 6.

关于c - 字符数组的 strlen 和大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19148940/

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