Answer the question
In order to leave comments, you need to log in
How does this piece of C code work?
There is the following piece of code:
#include <stdio.h>
typedef struct
{
int age;
char *name;
} Person;
int main(void)
{
Person people[4];
int n = sizeof(people)/sizeof(people[0]);
for(int i=0; i<n; i++)
{
people[i].name = "John";
people[i].age = 23;
}
for(int i=0; i<n; i++)
{
printf("Name: %s \t Age: %d \n", people[i].name, people[i].age);
}
return 0;
}
Answer the question
In order to leave comments, you need to log in
You should still turn to the book, and not to this resource.
To clear memory, if it means to free, it is necessary only after memory allocation. If your program calls malloc somewhere, etc., then you need to call free, not otherwise.
Dynamic arrays and large arrays should not be allocated on the stack. You can catch a stack overflow at run time. And when allocating an array, remember that the memory is not infinite, and you may not have enough of it. Again, if you read the documentation, then you can call realloc only after the mandatory call to malloc. This is all work with allocators that work with dynamic memory.
The maximum size of name. Name is a pointer that stores an address, a memory address. It does not store either the size or data about what it points to, it does not matter to it, it will always be the same size. In your case, when compiling in the program, memory is pre-allocated for all the text data that is specified in your code, and the pointer points to them. If you want to save the entered data, then you will have to use memory allocation.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question