What is the difference between declaring: char* s and char *s?
None. Aesthetics, only. It’s less confusing to write:
char *s, *r
than char* s, *r
, p.and.
2º It is always necessary to use the malloc function whenever declaring a Pointer?
No, you’re confusing things. A pointer is nothing more than a
variable that stores an address. In the same way as an integer aramazena
a number. As the various types (int, char, etc.) have different sizes,
there is a different pointer for each type. This occurs because of
arithmetic with pointers, which I explain later.
char c = 'a';
char *s = &a;
The above code declares a variable c
which stores a character and a variable
s
which stores the address of c
. We could still create a variable for
store the address of
s
:
char **ss = &s;
Staying:
Variável Endereço (hipotético) Valor Tamanho
c 0x0002 'a' sizeof(char) bytes
s 0x0010 0x0002 sizeof(char *) bytes
ss 0xFF10 0x0010 sizeof(char **) bytes
malloc is a function that reserves a continuous memory space on the heap,
returning the address of the beginning of this space (pointer type, as it is a
address). P.e.
char *s = malloc(2);
Reserve two bytes, and the initial address is assigned to the variable s:
Variável Endereço (hipotético) Valor Tamanho
s 0x0001 ? 2 bytes
If we print:
printf("%p\n", s + 1);
We’ll see 0x0002
, s address one more. That’s because the size of char
is
1 byte (s + 1
translates to sizeof(*s) + 1
). For this arithmetic question
(used in arrays, among other things) is that each type has a "pointer type"
equivalent including pointer hands of ...
3º Declaring a char* s variable is like declaring a
string? Can I use this as a String?
Not. char *s
contains an address. Dot. A string is a character array,
which can be declared in several ways (search for when to use malloc, or
ask a new question, and read the manual on the use of malloc):
char *s = malloc(10 * sizeof(*s));
char s2[10];
strncpy(s, "123456789", 10);
strncpy(s2, "123456789", 10);
char s3[] = "123456789";
char *s4 = strdup("123456789");
free(s);
free(s4);
Read the manual of the above functions if you want to understand more about them. In
Linux/OSX: man FUNCAO
.
char* s; char s;
As already explained, one guard a character and the other an address.
5th What is the real use of pointers? Besides solving some bugs?
Perhaps this answer gave an initial idea about pointers. They are used
for absolutely everything, as you will see when learning more.
About item 4, very well described. Generally people tend not to explain the difference correctly.
– felipsmartins