jeudi 7 septembre 2023

Can someone please explain what is happening here? I tried to get the memory addresses of an array in C++ but it gives me the same character, repeated [duplicate]

I made two arrays. One houses the numbers 0 to 20 and another just stores the character 'Z' twenty times. The code basically sets an array length, assigns each element in the integerArray and charArray either an integer or the character 'Z,' respectively. The arrays are then printed with a line of '-'s to spearate them.

#include <iostream>
using namespace std;

int main()
{
        
    //Use & to find the address locatoin in memory
    
    int arrayLength = 20;
    
    int integerArray[arrayLength];
    
    for (int i = 0; i <= arrayLength; i++){
    
        integerArray[i] = i;
    
    }
    
    cout << "-------------------------" << endl;
    for (int i = 0; i <= arrayLength; i++){
    
        cout << integerArray[i] << " is stored at: " << &integerArray[i] << endl;

    }
    
    char charArray[arrayLength];
    
    for (int i = 0; i <= arrayLength; i++){
    
        charArray[i] = 'Z';
    
    }
    
    cout << "-------------------------" << endl;
    for (int i = 0; i <= arrayLength; i++){
    
        cout << charArray[i] << " is stored at: " << &charArray[i] << endl;

    }
    
    return 0;
}

I tried getting the memory addresses. It worked fine for the integer array, but the character array gave me something I could not understand. It gives me the letter 'Z', just multiple times. I don't know how this is happening or what it means.

-------------------------
0 is stored at: 0x7ffd40dc8f40
1 is stored at: 0x7ffd40dc8f44
2 is stored at: 0x7ffd40dc8f48
3 is stored at: 0x7ffd40dc8f4c
4 is stored at: 0x7ffd40dc8f50
5 is stored at: 0x7ffd40dc8f54
6 is stored at: 0x7ffd40dc8f58
7 is stored at: 0x7ffd40dc8f5c
8 is stored at: 0x7ffd40dc8f60
9 is stored at: 0x7ffd40dc8f64
10 is stored at: 0x7ffd40dc8f68
11 is stored at: 0x7ffd40dc8f6c
12 is stored at: 0x7ffd40dc8f70
13 is stored at: 0x7ffd40dc8f74
14 is stored at: 0x7ffd40dc8f78
15 is stored at: 0x7ffd40dc8f7c
16 is stored at: 0x7ffd40dc8f80
17 is stored at: 0x7ffd40dc8f84
18 is stored at: 0x7ffd40dc8f88
19 is stored at: 0x7ffd40dc8f8c
20 is stored at: 0x7ffd40dc8f90
-------------------------
Z is stored at: ZZZZZZZZZZZZZZZZZZZZZ
Z is stored at: ZZZZZZZZZZZZZZZZZZZZ
Z is stored at: ZZZZZZZZZZZZZZZZZZZ
Z is stored at: ZZZZZZZZZZZZZZZZZZ
Z is stored at: ZZZZZZZZZZZZZZZZZ
Z is stored at: ZZZZZZZZZZZZZZZZ
Z is stored at: ZZZZZZZZZZZZZZZ
Z is stored at: ZZZZZZZZZZZZZZ
Z is stored at: ZZZZZZZZZZZZZ
Z is stored at: ZZZZZZZZZZZZ
Z is stored at: ZZZZZZZZZZZ
Z is stored at: ZZZZZZZZZZ
Z is stored at: ZZZZZZZZZ
Z is stored at: ZZZZZZZZ
Z is stored at: ZZZZZZZ
Z is stored at: ZZZZZZ
Z is stored at: ZZZZZ
Z is stored at: ZZZZ
Z is stored at: ZZZ
Z is stored at: ZZ
Z is stored at: Z

Can someone please explain why there are so many 'Z's?

Aucun commentaire:

Enregistrer un commentaire