what happens when an array is instantiated?

  • Thread starter Thread starter Nyap
  • Start date Start date
  • Views Views 875
  • Replies Replies 3

Nyap

HTML Noob
Banned
Joined
Jan 13, 2016
Messages
971
Reaction score
347
Trophies
0
Age
57
Location
That Chaos Site
XP
529
Country
take this statement
Code:
int eof[5];
it makes a pointer to store the address of the first integer and the 5 integers are created seperately, and next to each other in memory
is that correct?
 
I'm confused because the guy who wrote my tutorial says otherwise
No, int test[5] makes a fixed array with 5 elements, and takes 20 bytes. In most cases, when test is evaluated, it will decay into a temporary pointer.

There’s nothing stopping you from indexing an array out of range due to the way the subscript index works -- this is discussed in more detail in the lesson on pointer arithmetic.
for example:
Code:
testFunction(arrayArgument) //the array thats being passed to testFunction is implicitly converted to the address of the first element in the array
 
Declaring the array divvies up 20 bytes (5 * int (4b)) of memory, split into buckets for each int. Evaluating it will give you a pointer which points only to the array, not to the first int.

Code:
#include <iostream>

using namespace std;
int main(int argc, char *argv[]) {
    int eof[5];

    printf("Incorrect: %i\n", eof); 
    printf("Correct: %i\n", eof[0]);
 
 
    eof[2] = 3;
    printf("Item 2: %i\n", eof[1]);
    printf("Item 3: %i\n", eof[2]);
}

Which results in:

Code:
Untitled 4.cpp:7:28: warning: format specifies type 'int' but the argument has type 'int *' [-Wformat]
        printf("Incorrect: %i\n", eof);
                           ~~     ^~~
1 warning generated.
Incorrect: 1496237840
Correct: 0
Item 2: 0
Item 3: 3
 
  • Like
Reactions: cots

Site & Scene News

Popular threads in this forum