您的大部分问题已在其他答案中得到解决,但是,我没有看到有人专门解决这个问题:
关于您的问题: ...我可以在修改给定的副本后读取或指向原始字符串吗?如何? em>
以下序列演示了如何在修改副本后阅读原件:
char str[] = "hello world"; //creates original (stack memory)
char *str2 = 0;//create a pointer (pointer created, no memory allocated)
str2 = StrDup(str); populate pointer with original (memory allocated on heap)
str2[5]=0; //edit copy: results in "hello" (i.e. modified) (modifying a location on the heap)
str; //still contains "hello world" (viewing value on the stack)
编辑(回答评论问题)
上述答案 仅解决了在修改副本后访问原始字符串的具体问题。我只是展示了一组可能的步骤来解决这个问题。您也可以编辑原始字符串:
char str[] = "你好世界!"; //在堆栈内存中创建名为“str”的位置,
//并为文字字符串分配足够的空间:
//“Hello world!”,共13个空格(包括\0)
strcpy(str, "新字符串"); //用“新字符串”替换原始内容
//旧内容不再可用。
因此,使用这些步骤,变量 str 中的原始值被更改,不再可用。
我在原始答案中概述的方法(在顶部)显示了一种方法,您可以制作可编辑的副本,同时保持原始变量。
在您的评论问题中,您指的是诸如系统内存和常量内存之类的东西。通常,系统内存是指系统上的 RAM 实现(即多少物理内存)。 常量内存,我猜你指的是在堆栈上创建的变量所使用的内存。 (继续阅读)
首先在开发或运行时环境中,存在堆栈内存。这通常默认为某个最大值,例如 250,000 字节。它是大多数开发环境中的预构建可设置值,可供您创建的任何变量使用 在堆栈上。示例:
int x[10]; //creates a variable on the stack
//using enough memory space for 10 integers.
int y = 1; //same here, except uses memory for only 1 integer value
第二还有所谓的堆内存。堆内存的数量取决于系统,系统可用的物理内存越多,可用于应用程序中可变内存空间的堆内存就越多。当您动态分配内存时会使用堆内存,例如使用malloc()、calloc()、realloc()。
int *x=0; //creates a pointer, no memory allocation yet...
x = malloc(10); //allocates enough memory for 10 integers, but the
//memory allocated is from the _heap_
//and must be freed for use by the system
//when you are done with it.
free(x);
我已经在原始帖子(上图)中标记了每个变量使用的内存类型。我希望这会有所帮助。