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;
}
时间: 2024-08-02 02:17:08

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

C语言及程序设计进阶例程-11 体验结构体

贺老师教学链接  C语言及程序设计进阶 本课讲解 结构体类型变量的定义方法 #include <stdio.h> struct Student { int num; char name[20]; char sex; int age; float score; char addr[30]; }; int main( ) { struct Student student1, student2; printf("%d\n", sizeof(student1)); return 0

C语言及程序设计进阶例程-15 指向结构体的指针

贺老师教学链接  C语言及程序设计进阶 本课讲解 指向结构体变量的指针的应用 #include <stdio.h> #include <string.h> struct Student { int num; char name[12]; char sex; float score; }; int main( ) { struct Student stu; stu.num=10301; strcpy(stu.name, "Wang Fun"); stu.sex='

C语言及程序设计进阶例程-12 结构体成员的引用

贺老师教学链接  C语言及程序设计进阶 本课讲解 结构体作函数参数 #include <stdio.h> struct Student { int num; char name[20]; char sex; int age; double score; char addr[30]; }; void print(struct Student s) { printf("%d %s %c\n", s.num, s.name, s.sex); //可再加-- return; } i

C语言及程序设计进阶例程-13 结构体数组及其应用

贺老师教学链接  C语言及程序设计进阶 本课讲解 结构体数组应用举例 #include <stdio.h> #include <string.h> typedef struct { char name[20]; int count; } Person; int main( ) { Person person[3]= {{"Li",0},{"Zhang",0},{"Fun",0}}; int i,j; char name[2

《从缺陷中学习C/C++》——6.16 结构体成员内存对齐问题

6.16 结构体成员内存对齐问题 从缺陷中学习C/C++ 代码示例 struct{ char flag; int i; } foo; int main() { foo.flag = 'T'; int pi = (int )(&foo.flag + 1); *pi = 0x01020304; printf("flag=%c, i=%x\n", foo.flag, foo.i); return 0; } 现象&后果 代码中定义了一个结构体,包括一个字符成员flag和整型成员

C语言及程序设计进阶例程-27 贪心法问题求解

贺老师教学链接 C语言及程序设计进阶 本课讲解 找零钱问题及其求解 #include <stdio.h> int main ( ) { int money[10]={100,50,10,0}; /*最大面额的硬值面值排在最前面,将被优先处理*/ int x; /*找零金额*/ int i=0, n=0, m; scanf("%d", &x); /*输入找零金额*/ while(x>0 && money[i]!=0) /**/ { m=x/mon

C语言及程序设计进阶例程-5 认识递归

贺老师教学链接  C语言及程序设计进阶 本课讲解 认识递归:求阶乘 #include <stdio.h> long fact(int n) { long f; if (n==1) f=1; else f=n*fact(n-1); return f; } int main( ) { int n; long y; scanf("%d", &n); y=fact(n); printf("%ld\n", y); return 0; }

C语言及程序设计进阶例程-7 递归经典:汉诺塔

贺老师教学链接  C语言及程序设计进阶 本课讲解 汉诺塔问题解决方案 #include <stdio.h> #define discCount 4 void move(int, char, char,char); int main() { move(discCount,'A','B','C'); return 0; } void move(int n, char A, char B,char C) { if(n==1) printf("%c-->%c\n", A, C

C语言及程序设计进阶例程-2 一个程序,多个文件

贺老师教学链接  C语言及程序设计进阶 本课讲解 演示:建立多文件的项目main.c #include <stdio.h> int max(int x,int y); int main( ) { int a,b,c; printf("输入两数:"); scanf("%d %d", &a, &b); c=max(a,b); printf("max=%d\n", c); return 0; } max.c int max(