J
J
Johnem2020-12-04 21:48:39
C++ / C#
Johnem, 2020-12-04 21:48:39

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;
}

I can't understand how *name works, in theory we create a pointer to name of type char, but what is the maximum length of name then? Is it necessary to clear the memory after using a particular structure (for example, people[0]), if it is no longer needed, but the remaining elements of the array are still needed? In the future, I want to try to write a dynamic array of structures (quite large (up to 10^6 structures)), do I need to use realloc?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
X
xorknown, 2020-12-04
@Johnem

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 question

Ask a Question

731 491 924 answers to any question