What's 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
, eg
2nd Is it 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 aramazena integer
a number. Because the various types (int, char, etc.) have different sizes,
there is a different pointer for each type. This is because of
arithmetic with pointers, which I'll explain later.
char c = 'a';
char *s = &a;
The above code declares a c
variable that stores a character and a variable
s
that stores the c
address. We could also create a variable for
store the address of
s
:
char **ss = &s;
Getting:
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 space of memory in the heap,
returning the address of the beginning of this space (of the type pointer, because it is a
Address). P.
char *s = malloc(2);
Reserves two bytes, and the starting address is assigned to the variable s:
Variável Endereço (hipotético) Valor Tamanho
s 0x0001 ? 2 bytes
If we are going to print:
printf("%p\n", s + 1);
We will see 0x0002
, address of s plus one. This is 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 pointers of pointers to ...
3º Declaring a variable char * s is as if I were declaring a
string? Can I use this as a String?
No. char *s
contains an address. Score. A string is an array of characters,
which can be declared in various ways (search for when to use malloc, or
ask a new question, and read the manual on using 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 one character and the other an address.
5th What's the real use of pointers? Besides solving some bugs?
Maybe this answer gave you an initial idea about pointers. They're used
for absolutely everything, as you will see when you learn more.