Let's take the following basic program which creates a single item for a linked list of Movies:
#include <stdio.h>
#include <stdlib.h>
#define TLEN 45
struct film {
char title[TLEN];
int rating;
};
typedef struct film Item;
typedef struct node {
Item item;
struct node *next;
} Node, *List;
int main(void)
{
Item avatar = {"Avatar", 7};
List movies = malloc(sizeof(Item));
movies->item = avatar;
printf("Movie: %s\n", movies->item.title);
}
In the above, I create a new movie by doing:
List movies = malloc(sizeof(Item));
Would it be possible to add this struct film
item directly on the stack without using a malloc
? This is mainly for educational/academic purposes, but I'm wondering if I can do something along the lines of:
int main(void)
{
Item avatar = {"Avatar", 7};
List movies; // possible to add to stack instead? = malloc(sizeof(Item));
movies->item = avatar;
printf("Movie: %s\n", movies->item.title);
}
Update: it seems I can do it by declaring a normal (non-pointer) struct:
Node movies2;
movies2.item = avatar;
printf("Movie: %s\n", movies->item.title);
Is that the only way to do this? I know this is stupid, but in an academic sense, can I have the pointer on the stack, refer to a(nother) non-pointer struct on the stack?