C语言:字符串存在哪?

0x1

0x11 栈上(Stack)

局部变量(包括在函数内部定义的数组和变量)通常存储在栈上。
当你在函数内部定义一个字符数组并初始化一个字符串时,这个字符串就存储在栈上。

void function() {
    char str[] = "Hello, World!";
    // str 存储在栈上
}

0x12 堆上(Heap)

使用动态内存分配函数,如 malloc 或 calloc,分配的内存位于堆上。
如果你使用这些函数为字符串分配内存,字符串将存储在堆上。

char *str = malloc(20 * sizeof(char));
if (str != NULL) {
    strcpy(str, "Hello, World!");
    // str 存储在堆上
}

0x13 常量存储区(Constant)

使用字符串字面量(如 “Hello, World!”)通常存储在只读的数据段中,这个区域有时被称为常量存储区。
这些字符串是不可修改的,尝试修改它们将导致未定义行为。

char *str = "Hello, World!";
// 字符串字面量存储在常量存储区

0x2

0x21 常量区

#include <stdio.h>
char * func01(void) {
        char *s = "hell world";
        char buf[] = "hello world";
        return s;
}
int main(void) {
        char *p = func01();
        printf("char ptr is %s\n", p);
}

编译:
gcc -o demo demo.c
运行:
char ptr is hell world

0x22 栈区

#include <stdio.h>
char * func01(void) {
        char *s = "hell world";
        char buf[] = "hello world";
        return buf;
}
int main(void) {
        char *p = func01();
        printf("char ptr is %s\n", p);
}

编译:
gcc -o demo demo.c

demo.c: In function ‘func01’:
demo.c:7:15: warning: function returns address of local variable [-Wreturn-local-addr]
    7 |        return buf;

运行:
char ptr is (null)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值