gpt4 book ai didi

C:字符串、数组和指针?阵列故障?

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

我想知道是否可以在不更改地址的情况下更改存储在变量中的字符串。而且我无法编写代码来执行此操作,因为当我编写如下代码时

char* A = "abc";
char* B = "def";
A = B; <-- if I write down this code, then A will point to B and address changes.

那么有没有人知道如何做到这一点,将存储在 A 中的字符串更改为 "def" ,而不更改 A 的初始地址>?

此外,我再次尝试只更改变量 A 中的一个字,而不更改地址。

为此,我编写了以下失败代码。但我不知道为什么会失败。

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

int main(void)
{
char* s = "ABC";

// print value and address of s.
printf("Value of s is %s \n", s);
printf("Address of s is %p \n", s);

s[0] = 'v';

printf("Value of s is %s \n", s);
printf("Address of s is %p \n", s);
}

使用 gdb,我发现 s[0] = 'v' 无效并导致段错误。为什么会这样?谁也能告诉我这背后的原因吗?谢谢。

最佳答案

This answer is based on a similar one of mine from some time ago.

通过以您所拥有的方式声明一个字符串,您已经有效地创建了一个存储在只读内存中的 const 字符串。

简答:


char A[] = "abc";  // 'A' points to a read-write string, which is 4 characters long { 'a', 'b', 'c', '\0' }
char* B; // 'B' is a pointer that currently points to an unknown area since it isn't initialized
B = A; // 'A' and 'B' now point to the same chunk of memory
char C[] = "abc";
snprintf(C, strlen(C)+1, "def"); // Modify the contents of the area 'C' points to, but don't change what 'C' actually points to.

长答案:


考虑下面的例子:

char strGlobal[10] = "Global";

int main(void) {
char* str = "Stack";
char* st2 = "NewStack";
str = str2; // OK
strcpy(str, str2); // Will crash
}

为了安全起见,您实际上应该分配为指向 const 数据的指针,以确保您不会尝试修改数据。

const char* str = "Stack"; // Same effect as char* str, but the compiler
// now provides additional warnings against doing something dangerous

分配内存的第一种方法是在只读内存中进行静态分配(即:与 strstr2 一样)。

第二种分配称为动态分配,它在堆上而不是堆栈上分配内存。可以毫不费力地修改字符串。在某些时候,您需要通过 free() 命令释放这个动态分配的内存。

还有第三种分配字符串的方法,就是在栈上静态分配。这允许您修改保存字符串的数组的内容,并且它是静态分配的。

char str[] = "Stack";

总结:

Example:                       Allocation Type:     Read/Write:    Storage Location:
================================================================================
const char* str = "Stack"; Static Read-only Code segment
char* str = "Stack"; Static Read-only Code segment
char* str = malloc(...); Dynamic Read-write Heap
char str[] = "Stack"; Static Read-write Stack
char strGlobal[10] = "Global"; Static Read-write Data Segment (R/W)

关于C:字符串、数组和指针?阵列故障?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27832619/

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