gpt4 book ai didi

可以使用 char 指针来操作它所指向的 char 数组吗?

转载 作者:行者123 更新时间:2023-11-30 15:29:38 25 4
gpt4 key购买 nike

我只是制作了一个字符数组str。后来我制作了一个char *p,它只是指向它,我可以从开始到结束str访问(旅行) ,我可以使用 p 操作 str 吗?p[i]='x'; (其中 i:有效索引,x:任何字符)有效吗?实际上我尝试过它正在工作,我的问题是是否不需要使用 malloc 为其提供内存(即 p=malloc(l*sizeof(char));)。

#include<stdio.h>
#include<string.h>
int main()
{
char str[20];
char *p;
scanf("%s",str);
printf("%s\n",str);
int l=(int)strlen(str);
// printf("l= %d\n",l);
//p=str;
//p=malloc(l*sizeof(char));
p=str;
int i;
for(i=0;i<l;++i)
printf("%c-",*(p+i));
printf("\nNow p=%s\n",p);
p[1]='x'; // it is valid , but difficult to understand?? we didnot give it memory,but it can manipulate the str as well.
printf("After changes made\n",p);
printf("p=%s\n",p);
printf("str=%s\n",str);
return 0;
}

最佳答案

在这种情况下就不需要为p分配内存。当您执行以下操作时,内存已在堆栈上为 str 分配:char str[20];。执行完 p=str; 后,pstr 都指向堆栈上的同一内存地址。只要 str 位于作用域内,strp 都可以用来操作它们共享的内存地址处的值。因此,p[1]='x';str[1]='x'; 是等效的。

但要小心,如果将 p 的值保留在 str 左范围之后并尝试使用它,将会发生未定义的行为。当str离开作用域时,内存将被释放,并且p将指向堆栈上可能被其他东西使用的地址。使用 p 可能无法获得您想要的结果,并且对 p 进行更改可能会干扰不相关的值。

执行p=malloc(l*sizeof(char));会在堆上分配新内存。由于它在堆上,您负责释放该内存,因此当处理退出分配它的范围时,它仍然会被分配。

您可以在这里找到更多相关内容:What is the difference between char s[] and char *s in C?

关于可以使用 char 指针来操作它所指向的 char 数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26140461/

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