Salve a tutti,
ho composto un programma in cui dichiaro un array di caratteri e ho imposto degli output significativi per capire il collegamento tra array e puntatori:
Gli output sono:#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
char string[] = "ciao Mondo";
cout << "The address of string is " << &string << endl;
cout << "The value of string is " << string << endl;
cout << "The value pointed of string is " << *string << endl;
cout << "The address of string[0] is " << &string[0] << endl;
cout << "The value of string[0] is " << string[0] << endl;
//cout << "The value pointed of string[0] is " << *string[0] << endl;
//Restituisce un errore
cout << "The address of string[1] is " << &string[1] << endl;
cout << "The address of string[2] is " << &string[2] << endl;
cout << "The address of string[8] is " << &string[8] << endl;
cout << "The value of string[1] is " << string[1] << endl;
cout << "The value of string[2] is " << string[2] << endl;
cout << "The value of string[8] is " << string[8] << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
The address of string is 0x23ff68
The value of string is ciao Mondo
The value pointed of string is c
Fin qui tutto ok, il libro afferma che il nome di un array è un puntatore al suo primo elemento, quindi il valore puntato è giustamente string[0]=c.
Proseguendo, però, mi sorgono dei dubbi e il libro non dice nulla su ciò.
Quindi usando l'operatore & davanti ad un elemento del vettore indicizzato, ad esempio &string[0] come sopra, non restituisce l'indirizzo della cella di memoria di string[0], ma il valore di string, cioè ciao Mondo. D'altra parte la scrittura *string[0] restituisce un errore.The address of string[0] is ciao Mondo
The value of string[0] is c
//cout << "The value pointed of string[0] is " << *string[0] << endl;
//Restituisce un errore
[...]
The address of string[8] is do
[...]
The address of string[8] is d
Ora, visto che gli indirizzi di memoria in un array sono tutti immediatamente consecutivi, come faccio ad accedere agli indirizzi di memoria dei vari elementi del vettore, se usando l'operatore & mi viene restituito non l'indirizzo della singola cella, ma il valore del vettore a partire dall'n+1 elemento indicizzato?
Es: &string[8]=do, ossia tutto quello che c'è in string dall'8+1 elemento compreso in su.
E come mai la scrittura *string[0] non ha senso?
Grazie mille!!