zoukankan      html  css  js  c++  java
  • 结构体复制与赋值

     1 #include <stdio.h>
     2 #include <string.h>
     3 #include <malloc.h>
     4 
     5 int main(int argc, char* argv[])
     6 {
     7     struct data
     8     {
     9         int i;
    10         char c;
    11         int j;
    12         int arr[2];
    13     };
    14 
    15     
    16     struct datawptr
    17     {
    18         int i;
    19         char *c;
    20     };
    21     
    22     struct datawptr dptr1;
    23     struct datawptr dptr2;
    24     struct data svar1; // a normal variable of type struct data
    25     struct data svar2; // a normal variable of type struct data
    26     
    27     svar1.c = 'a';
    28     svar1.i = 1;
    29     svar1.j = 2;
    30     svar1.arr[0] = 10;
    31     svar1.arr[1] = 20;
    32     
    33     svar2 = svar1;
    34     printf("Value of second variable 
    ");
    35     printf("Member c = %c
    ", svar2.c);
    36     printf("Member i = %d
    ", svar2.i);
    37     printf("Member j = %d
    ", svar2.j);
    38     printf("Member arr0th = %d
    ", svar2.arr[0]);
    39     printf("Member arr1st = %d
    ", svar2.arr[1]);
    40     
    41     dptr1.i = 10;
    42     dptr1.c = (char*)malloc(sizeof(char));
    43     *(dptr1.c) = 'c';
    44     dptr2.c = (char*)malloc(sizeof(char));
    45     dptr2 = dptr1;
    46     
    47     /* But, with
    48 the above approach, one needs to be careful when a data structure contains a member of pointer type because the
    49 assignment operator simply copies the value; it will also copy the pointer variable’s value, which is nothing but the
    50 address of some variable it is pointing to.  */
    51     
    52     printf("int member = %d
    ", dptr2.i);
    53     printf("char ptr member = %c
    ", *(dptr2.c));
    54     
    55     return 0;
    56 }
    57 
    58 /* 
    59 Value of second variable
    60 Member c = a
    61 Member i = 1
    62 Member j = 2
    63 Member arr0th = 10
    64 Member arr1st = 20
    65 int member = 10
    66 char ptr member = c 
    67 */

     

  • 相关阅读:
    支持向量机SVM知识点概括
    决策树知识点概括
    HDU 3081 Marriage Match II
    HDU 3572 Task Schedule
    HDU 4888 Redraw Beautiful Drawings
    Poj 2728 Desert King
    HDU 3926 Hand in Hand
    HDU 1598 find the most comfortable road
    HDU 4393 Throw nails
    POJ 1486 Sorting Slides
  • 原文地址:https://www.cnblogs.com/CodeWorkerLiMing/p/9607281.html
Copyright © 2011-2022 走看看