Hey) I have struct with members as pointers, And I want to create struct variable as pointer too.
I hope efficiency in malloc() that we do not store struct var in the Stack and keep executable file "a.out" byte less in HDD. Only Dynamic memory use. Please check, is this program can be more effective way written? Is my vision on memory correct and effective? Thx!
#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;
}