結構體的賦值
1.指針的賦值
區分對指針本身賦值和對指針指向的空間進行賦值。
2.數組的賦值
不能對數組名進行賦值,對數組的賦值實質上是數組中元素一個一個的拷貝。
3.結構體的賦值
結構體中的指針
結構體中含有指針時,對結構體賦值類似於指針的賦值,只是淺賦值,如果想深賦值,還需要額外處理。
結構體中的數組
結構體含有數組時,對結構體進行賦值,可以實現數組的直接賦值,而外部的數組不能進行直接賦值,而是一個一個的拷貝。
結構體的直接賦值,實質上是對結構體的完全拷貝,不管結構體中有指針還是數組,拷貝的內容都是結構體本身,也就是說結構體中有指針時,拷貝的是指針本身;結構體中有數組時,拷貝的是數組。
對結構體賦值,可以將結構體內部中的數組進行直接賦值。而直接的數組不能實現數組間的賦值操作。
測試代碼和注釋:
#include <stdio.h> #include <stdlib.h> #include <string.h> struct st1 { char* p; // 指針 }; void print_st1(struct st1* ps) { printf("%s\n", ps->p); } struct st2 { char a[5]; // 數組 }; void print_st2(struct st2* ps) { printf("%s\n", ps->a); } int main() { // 指針的賦值 char p[] = "abc"; char* q = p; // 對指針賦值 printf("%s\n", p); printf("%s\n", q); printf("\n"); strcpy(p, "xyz"); printf("%s\n", p); printf("%s\n", q); printf("\n"); // 分配空間 q = (char*)malloc(strlen(p) + 1); strcpy(q, "abc"); printf("%s\n", p); printf("%s\n", q); printf("\n"); free(q); // 數組的賦值 int a[3] = {1, 2, 3}; // int b[3] = a; // 對數組這種初始化失敗 int b[3]; // b = a; // 賦值失敗,因為不存在對數組的賦值,b是數組名,是一個常量 // 拷貝a中的元素到b中 int i = 0; for (i = 0; i < sizeof (a) / sizeof (*a) && sizeof (b) >= sizeof(a); ++i) { b[i] = a[i]; // 一個一個拷貝 } for (i = 0; i < sizeof (b) / sizeof (*b); ++i) { printf("%d ", b[i]); } printf("\n"); printf("\n"); // 結構體的賦值 // 結構體中的指針 struct st1 s1; s1.p = (char*)malloc(5); strcpy(s1.p, "abc"); struct st1 s2; s2 = s1; // 結構體的賦值,結構體中的指針 printf("%s\n", s1.p); printf("%s\n", s2.p); printf("\n"); strcpy(s1.p, "xyz"); printf("%s\n", s1.p); printf("%s\n", s2.p); printf("\n"); strcpy(s1.p, "abc"); s2.p = (char*)malloc(5); strcpy(s2.p, s1.p); printf("%s\n", s1.p); printf("%s\n", s2.p); printf("\n"); strcpy(s2.p, "xyz"); printf("%s\n", s1.p); printf("%s\n", s2.p); printf("\n"); free(s1.p); free(s2.p); printf("%d\n", (int)s1.p); printf("%d\n", (int)s2.p); printf("\n"); s1.p = NULL; s2.p = NULL; printf("%d\n", (int)s1.p); printf("%d\n", (int)s2.p); printf("\n"); // 結構體的賦值 // 結構體中的數組 struct st2 t1; strcpy(t1.a, "abc"); // 不能對數組進行直接賦值,所以只能逐個拷貝 struct st2 t2; t2 = t1; // 結構體的賦值,結構體中的數組 // 結構體中有數組,如果對結構體進行賦值,那么其里面的數組也被拷貝,可以看做是數組的賦值 // 但是對於外部的數組直接賦值是不可以的 printf("%s\n", t1.a); printf("%s\n", t2.a); printf("\n"); strcpy(t1.a, "xyz"); printf("%s\n", t1.a); printf("%s\n", t2.a); printf("\n"); strcpy(t1.a, "abc"); strcpy(t2.a, "xyz"); printf("%s\n", t1.a); printf("%s\n", t2.a); printf("\n"); return 0; }