C 结构体与内存申请的混搭使用

  1 #include <stdio.h>
  2 #include <stdlib.h>       
  3 #include <assert.h>
  4 #include <string.h>       
  5 
  6 typedef struct _tst_t {   
  7     int a;                
  8     char b;               
  9     int c;                
 10 } tst_t;                  
 11 
 12                           
 13 int
 14 main(int argc, char *const argv[])
 15 {
 16     char *ptr = NULL;
 17     tst_t *t1 = NULL;
 18 
 19     ptr = (char *)malloc(sizeof(tst_t) + 10);
 20     assert(NULL != ptr);
 21 
 22     ((tst_t *)(ptr))->a = 1;
 23     ((tst_t *)(ptr))->b = 2;
 24     ((tst_t *)(ptr))->c = 3;
 25     
 26     memcpy(ptr + sizeof(tst_t), "hello", strlen("hello"));
 27     printf("*ptr: %s\n", ptr);
 28     
 29     t1 = (tst_t *)ptr;
 30 
 31 
 32     printf("t1->a = %d, t1->b = %d, t1->c = %d\n", t1->a, t1->b, t1->c);
 33     free(ptr);
 34     return 0;
 35 }
# gcc test2.c 
[root@localhost ~/test]
# ./a.out 
*ptr: 
t1->a = 1, t1->b = 2, t1->c = 3
发布了207 篇原创文章 · 获赞 77 · 访问量 29万+

猜你喜欢

转载自blog.csdn.net/daa20/article/details/103503778