Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当字符指针指向字符串时,如何分配内存? #包括 内部主(空) { /*在这个消息中,是一个足够大的数组 *保留字符和“\0”的序列*/ char amessage[]=“现在是时候了”; /*在这种情况下,将使用字符指针 *指向字符串常量*/ char*pmessage=“现在是时候了”; 返回0; }_C_String_Memory_Pointers_Memory Management - Fatal编程技术网

当字符指针指向字符串时,如何分配内存? #包括 内部主(空) { /*在这个消息中,是一个足够大的数组 *保留字符和“\0”的序列*/ char amessage[]=“现在是时候了”; /*在这种情况下,将使用字符指针 *指向字符串常量*/ char*pmessage=“现在是时候了”; 返回0; }

当字符指针指向字符串时,如何分配内存? #包括 内部主(空) { /*在这个消息中,是一个足够大的数组 *保留字符和“\0”的序列*/ char amessage[]=“现在是时候了”; /*在这种情况下,将使用字符指针 *指向字符串常量*/ char*pmessage=“现在是时候了”; 返回0; },c,string,memory,pointers,memory-management,C,String,Memory,Pointers,Memory Management,我不知道第二种情况下内存是如何分配的??内存的副本是私有的吗?我的意思是,作为第二个stmt写入一些内容,并确保其他内容不会覆盖相同的内存,这样安全吗。它们将在堆栈上分配。 amessage和pmessage之间唯一的区别是pmessage是只读的 #include<stdio.h> int main(void) { /* in this amessage is an array big enough to * hold the sequence of char

我不知道第二种情况下内存是如何分配的??内存的副本是私有的吗?我的意思是,作为第二个stmt写入一些内容,并确保其他内容不会覆盖相同的内存,这样安全吗。它们将在堆栈上分配。 amessage和pmessage之间唯一的区别是pmessage是只读的

#include<stdio.h>

int main(void)
{
    /* in this amessage is an array big enough to
     * hold  the sequence of character and '\0' */
    char amessage[] = "now is the time";

    /* in this case a character pointer is
     * pointing to a string constant */
    char *pmessage = "now is the time";

    return 0;
}
创建字符串文字,字符串的内存分配在只读位置的某个位置,具体取决于编译器的实现细节


修改它将导致未定义的行为。因此,如果您使用字符串文字,您有责任确保不尝试写入此只读内存。

字符串文字可以是不同的,也可以不是不同的:这是编译器的选择(声明未指定)

假设,在一分钟内,更改字符串文字本身并不是一件容易的事

char *pmessage = "now is the time";

至于您的具体问题:只要您不调用UB,它就安全了。编译器分配的内存考虑了所有其他对象的所有其他用途。

不,您不能确定。你应该通过自己的工作来照顾好这件事programming@Mr.DDD:你确定吗?我认为大多数编译器会将数据加载到进程内存的不同部分,而不是堆。@Mr.DDD-不会有任何加载(复制)。它很可能会指向可执行文件的数据部分的某个位置使用microsoft c和默认的优化选项,字符串数据本身分配在静态数据段中。在这两种情况下,堆栈上都没有分配任何内容。指向数据段的指针在寄存器中分配。这两个字符串都是可变的。编译器实际上应该警告或拒绝该字符串。字符串文字是只读的,因此,您不应该将它们分配给非常量指针。字符串文本的空间不必来自只读位置:在系统上有C的实现,对于这些实现来说,只读位置毫无意义。@pmg:答案是:
编译器的具体细节取决于实现。
对。。。我的观点是,它不必是只读位置。实现可以为字符串文本“选择”良好的旧读/写内存。
int main(void) {
    char *p = "now is the time";
    /* compiler makes sure there is a place with "now is the time"
    ** and makes p point there */
    char *q = "time";
    /* possibly, the compiler reuses the time from
    ** the previous string literal */

    q[0] = 'd'; /* technically UB: don't do this */
    puts(p);    /* possibly writes "now is the dime" */
}