I’m very new to C and I’ve used strcpy() for updating the race having not read the hint regarding using char*. Browsing other solutions on these forums using char* doesn’t require defining the array size. This wasn’t explained in the pointer chapter and i’m confused how does the compiler know how much memory to allocate for the string behind the pointer? How does all this work?
Thank you very much
Can you give some examples to clarify what you want to know about?
By nature when you don’t define the size of something in compiled languages there is a trade-off. This is the difference between declaring things on the stack vs. the heap (or free-store).
With a pointer, you don’t really allocate memory at compile time. The only reason you can “indefinitely” grow a pointer is that whenever anything is allocated through it, it finds whatever memory is free on the heap and allocates it. But then you lose the nice property that contiguous memory has (that it’s right next to each other, so you don’t need any indirection calculations to reach it, you just index it as needed). Compilers can highly optimize performance when things are predictable. Furthermore, continous use of the heap can lead to memory fragmentation which incurs overhead as well.
tldr pre-allocated static stuff fast, not always flexible. dynamic stuff slow, but flexible.
Thank you for the explanation, this clarifies things. It will sound weird, but I did read some about Rust before this C course, so that’s my point of reference (no pun intended). Is it fair to say that char* stored string is more like a Vec<> in Rust - an array that can be extended at runtime?
Once again, your input is very much appreciated.
Hm, i don’t see the connection with the rust example (particularly because of the safety guarantees in rust). But also with pointers it’s good to have concrete examples.
My earlier statement “With a pointer, you don’t really allocate memory at compile time.” can be wildly misleading if not tied to examples.
char *str = "Hello, World!";
Hello, World! is a string literal, that is stored in read-only memory (how string literals are handled), so it is done at compile time. But the allocation is not because of the pointer, the pointer just points to that space in memory. (this is probably what you were asking about)
int *ptr = malloc(sizeof(int));
here we use malloc which allocates to the free store dynamically at run time (not compile time).
Essentially we don’t need to know the argument of malloc() until we get to it, and it will allocate accordingly (given that there is enough memory).
Naturally we have to free that memory afterwards.