C语言及程序设计进阶例程-16 当结构体成员为指针

贺老师教学链接  C语言及程序设计进阶 本课讲解


有问题吗?

#include <stdio.h>
#include <string.h>
struct Test
{
    int x;
    char *str;
};

int main()
{
    struct Test a;
    a.x=100;
    char s[]="Hello";
    strcpy(a.str,s);
    printf("%d %s\n", a.x, a.str);
    return 0;
}


正解——当有指针数据成员,必须先为其分配空间!
#include <stdio.h>
#include <string.h>
#include <malloc.h>
struct Test
{
    int x;
    char *str;
};


int main()
{
    struct Test a;
    a.x=100;
    char s[]="Hello";
    a.str=(char*)malloc(strlen(s)+1);
    strcpy(a.str,s);
    printf("%d %s\n", a.x, a.str);
    return 0;
}



上一篇:zab协议


下一篇:C语言结构体数组同时赋值的另类用法