首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

关于构造体数组中指针的小困惑

2013-03-01 
关于结构体数组中指针的小困惑#include stdio.h#include string.h#include stdlib.htypedef struct

关于结构体数组中指针的小困惑

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct test{
  int a;
  int b;
  char *c;
}TEST;


int main()
{
        TEST ts[2];
        TEST *ptr = (TEST *)malloc(sizeof(TEST));
        TEST un;
        un.c = (char *)malloc(10);
        ptr->c = (char *)malloc(10);

        ts[0].c = (char *)malloc(10);
        ts[1].c = (char *)malloc(10);
        memset(ts, 0x0, sizeof(TEST)*2);
        ts[0].a = 1;
        ts[1].b = 1;
        strcpy(&ts[0].c, "abc");//这点为什么是&ts[0].c而不是ts[0].c?

        printf("ts[0].c = 0x%x &ts[0].c = 0x%x \n",ts[0].c, &ts[0].c);

        ts[1].a = 2;
        ts[1].b = 2;
        strcpy(&ts[1].c, "def");
        printf("ts[1].a b c = %d %d %s \n", ts[1].a, ts[1].b, &ts[1].c);

        ptr->a = 3;
        ptr->b = 3;
        strcpy(ptr->c, "hij");
        printf("ptr->a b c = %d %d %s \n",ptr->a, ptr->b, ptr->c);
        printf("ptr->c = 0x%x \n", ptr->c);

        un.a = 4;
        un.b = 4;
        strcpy(un.c, "klm");
        printf("un.a b c = %d %d %s \n",un.a, un.b, un.c);
        return 0;
}


就是在结构体数组中,为什么&ts[0].c这个才是*c的地址 而不是ts[0].c,按照一般理解的话,随意一个结构体变量比如str.c 应该就是c的指针了吧。。。
[解决办法]
memset(ts, 0x0, sizeof(TEST)*2);  你自己把指针清零了
[解决办法]
没有free
胡乱memset
strcpy(&ts[0].c )的做法是错的 

热点排行