成员变量指针指向 文字常量区、堆区空间、栈区空间
成员指针指向文件常量区
#include <stdio.h>
#include <string.h>
struct Student
{
int age;
char * name;
int score;
};
int main()
{
struct Student s;
char *p = (char *)"abc";//注意要强制转换类型,不然某些编译器会不通过
printf("%p\n", "abc");
printf("%p\n", p);
s.age = 18;
s.name = NULL;
s.name = (char *)"abc";//注意要强制转换类型,不然某些编译器会不通过
s.score = 100;
printf("%d %p %d\n", s.age, s.name, s.score);
printf("%d %s %d\n", s.age, s.name, s.score);
return 0;
}
成员指针指向堆区空间
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Student
{
int age;
char * name;
int score;
};
int main()
{
struct Student s;
s.age = 18;
s.name = (char *)malloc((strlen("mike")+1) * sizeof(char));
strcpy(s.name, "mike");
s.score = 80;
printf("%d %s %d\n", s.age, s.name, s.score);
if(s.name != NULL)
{
free(s.name);
s.name = NULL;
}
return 0;
}
成员指针指向栈区空间
#include <stdio.h>
#include <string.h>
struct Student
{
int age;
char * name;
int score;
};
int main()
{
struct Student s;
s.age = 18;
char buf[100];
s.name = buf;//指向栈区
strcpy(buf, "mike");
s.score = 59;
printf("%d %s %d", s.age, s.name, s.score);
return 0;
}
注意事项:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Student
{
int age;
char *name;
int score;
};
int main(int argc, char const *argv[])
{
struct Student *p;
//给p分配内存
p = (struct Student *)malloc(sizeof(struct Student));
if(p == NULL)
{
printf("分配失败");
return -1;
}
//需要给mike\0分配足够的空间
p->name = (char *)malloc(strlen("mike") + 1);
p->age = 18;
strcpy(p->name, "mike");
p->score = 99;
printf("%d, %s, %d\n", p->age, p->name, p->score);
//因为结构体的name是个指针,在堆区分配了一个区域给它
//释放结构体中的name所指向的堆区内存
if(p->name != NULL)
{
free(p->name);
p->name = NULL;
}
//释放结构体的堆区内存
if(p != NULL)
{
free(p);
p = NULL;
}
return 0;
}