I am new to c and learning pointers
Pointers are tough for beginners. Make sure you get a solid foundation.
at the moment what I know is that pointer points to the memory address of whatever it points to.
Though that is in practice correct, that's not how I like to think of it. What you are describing is how pointers are typically implemented, not what they are conceptually. By confusing the implementation with the concept you set yourself up for writing bad code later that makes unwarranted assumptions. There is no requirement that a pointer be a number which is an address in a virtual memory system.
A better way to think of a pointer is not as an address, but rather:
- A pointer to t is a value.
- Applying the
*
operator to a pointer to t gives you a variable of type t.
- Applying the
&
operator to a variable of type t gives you a pointer to t.
- A variable of type t can fetch or store a value of type t.
- An array is a set of variables each identified by an index.
- If a pointer references the variable associated with index i in an array then p + x gives you a pointer that references the variable associated with index i + x.
- Applying the
[i]
operator to a pointer is a shorthand for *(p+i)
.
That is, rather than thinking of a pointer as a number that refers to a location in memory, just think of it as something that you can force to give you a variable.
is this how you allocates memory exactly the length of the scanned string or it will take 50 bytes?
char *title = malloc(50 * sizeof(char));
scanf(" %[^\n]s", title);
malloc(50*sizeof(char))
gives you an array of 50 chars.
title
is a pointer to char
.
When dereferenced, title
will give you the variable associated with the first item in the array. (Item zero; remember, the index is the distance from the first item, and the first item has zero distance from the first item.)
scanf
fills in the characters typed by the user into your array of 50 chars.
If they type in more than 49 chars (remembering that there will be a zero char placed at the end by convention) then arbitrarily bad things can happen.
As you correctly note, either you are wasting a lot of space or you are possibly overflowing the buffer. The solution is: don't use scanf for any production code. It is far too dangerous. Instead use fgets
. See this question for more details:
How to use sscanf correctly and safely