39.成員指標指向棧區和堆區記憶體
阿新 • • 發佈:2022-03-24
**非法使用記憶體導致的錯誤 **
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct test{
char *str;
int a;
int b;
int c;
};
int main(){
struct test obj;
strcpy(obj.str, "mike");//報錯
printf("str = %s\n", obj.str);
}
成員指標指向data區或者棧區
#include<stdio.h> #include<string.h> struct Student{ int age; char *name; int score; }; int main01(){ struct Student s; s.age = 18; s.name = "mike";//指標變數儲存了字元常量的首地址 s.score = 59; }
**成員變數指向棧區空間 **
#include<stdio.h>
#include<string.h>
int main02(){
struct Student s;
s.age = 18;
char buf[100];
s.name = buf;
strcpy(s.name, "mike");
s.score = 59;
//我們定義了一個字元型的陣列,將name指向的棧區的buf
}
成員指標指向堆區空間
#include<stdio.h> #include<string.h> int main03(){ struct Student s; s.age = 18; s.name = (char *)malloc(strlen("mike") + 1); strcpy(s.name, "mikejinagabcsb"); s.score = 59; printf("%d, %s, %d\n", s.age, s.name, s.score); if(s.name != NULL) { free(s.name); s.name = NULL; } }