Understanding Pointers, memory allocation etc.
Ok, so this is the first time a more complicated concept is introduced in CS50 and I just want to make sure I understand everything very clearly.
When you create a variable or something like when you do int a = 2; at the end of the day you are telling the program, save me some space in memory to store an int (4 bytes), and I will put whatever inside.
The issue gets more complex with strings, which are sequences of characters at the end of the day. Also, to print a string, there is no such thing as a chunk exactly allocated for an string that I can print. So what I need to do is to go to location in memory where string starts, and read from beginning till I fill the Null Terminator value /0 that tells me the string has ended.
*a means : “Whatever is inside “&a” . (Whatever is inside the address of a)
int* a means: “Create a variable a that will store an address”. Which address? Needs to be given to them… usually a way to give it is to give a new one, by allocating it by using malloc.
e.g : a = malloc(sizeof(int))
Or instead of creating a new one, I can give it the address of an already created one. If for instance I have already done x = malloc(sizeof(int)), I can give to a that address by doing a = x.
More examples:
char*s; Means give me a pointer s whose purpose in life is to store an address.
Interesting when doing GetString(), this actually does not return a string… it returns an address. So when i do char* s = GetString(), I am saying… User will input a string, then GetString() will allocate memory and save it in an address. This address will then be passed to “s”, so s will point towards that chunk of memory. And where is that chunk of memory? In &s. And what if now I do *s = saaj, then I am modifying the content in memory! (Here how do you ensure that the new content fits? What happens if you put an int instead of a series of chars?)
So yeah, if I wanna do a change on a string without changing the original, I need more memory a different chunk. So I can for instance do:
char* t = malloc((strlen(s)+1) * sizeof(char)); ( So basically I am allocating same memory as the string + the extra 1 for the /0).
—
Instead of t[i] we can say *(t + i).
*t = *s means … Go to t, first thing there equals whatever is in “go to s, and check first element”.
—
GetString could return NULL if something goes wrong. So need to check before going to addresses…