C语言结构体内指针的存储问题

原创
2024/07/31 13:22
阅读数 109
#include <stdio.h>
struct Student
{
    int age;
    char * name;
    // how to change name's value?
};
int main() {
    struct Student stu= {12,"lisi"};//此时值为lisi的name变量申请在了静态存储区而不是堆上,是只读的
    stu.age=3;
    //当视图修改lisi为Yisi时
    stu.name[0]='Y';//此时会报段错误:Signal: SIGSEGV (Segmentation fault)
    stu.name="hangman";//直接赋值是可以的,相当于从静态存储区又申请了一块
    printf("stu's name:%s",stu.name);
    return 0;
}

如何实现修改l改为Y呢?

#include <stdio.h>
#include <stdlib.h>
#define N 50 //max size of student'name
struct Student
{
    int age;
    char * name;
    // how to change name's value?
};
int main() {

    struct Student stu2;
    stu2.age=12;
    if((stu2.name=malloc(N*sizeof(char))) == NULL)
    {
        return 0;
    }
    strcpy(stu2.name,"lisi");
    stu2.name[0]='Y';
    printf("stu2's name:%s",stu2.name);
    free(stu2.name);
    return 0;
}

malloc与free务必成对使用。

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部