【发布时间】:2017-08-27 13:20:39
【问题描述】:
嘿)我有成员作为指针的结构, 我也想创建结构变量作为指针。
我希望 malloc() 中的效率,我们不将 struct var 存储在堆栈中,并在 HDD 中保留可执行文件“a.out”字节少。仅动态内存使用。请检查,这个程序可以写成更有效的方式吗?我对记忆的看法正确有效吗?谢谢!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct pbookInfo { // define the struct pbookInfo here
char * title;
char * author;
};
int main(){
/* vars */
char esc = 'X'; // exit point
int i; // for loop counter
// struct with member as * pointers, and struct var as * pointer
struct pbookInfo * books; // struct var pointer
/* code - memory allocation */
books = (struct pbookInfo *)malloc(sizeof(struct pbookInfo)); // memory for struct var
// if memory fail
if(books == 0){
puts("\nmallocate fail - memory not enough");
exit(1);
}
books -> title = (char *)malloc(10); // memory for member 'title'
books -> author = (char *)malloc(5); // memory for member 'autor'
// if memory fail
if(books->title == 0 || books -> author == 0){
puts("\nmallocate fail - memory not enough");
exit(1);
}
/* some expression mock, for example: */
strcpy(books->title,"Storenth");
strcpy(books->author,"Kira");
// mock
/* allocated memory free */
free(books->title);
free(books->author);
free(books);
puts("All memory free!");
// exit point
puts("\nexit point:");
scanf(" %c", &esc);
return 0;
}
【问题讨论】:
-
为初学者声明
struct pbookInfo { // define the struct pbookInfo here char title[10]; char author[5]; };,而不是为标题和作者字段分配固定大小。或者先计算大小,然后 malloc。 -
与间距保持一致。点
.运算符或箭头->运算符周围不应该有空格。它们结合得非常紧密。