Arrays and Pointers - Reference Only!

Original Question from: Kourosh23
Answered by: Chervil

@Kourosh23

Also, I don't understand why it is an error ? I am simply passing value to the pointer which is accessing it from the struct. Later after I am done with it, I delete it. If you could maybe show me the correct code , in that case I can relate stuff because I am new to C++ :D
the variable arr.array is an uninitialised pointer.
It is an error to dereference an uninitialised pointer like this:

arr.array[i] = savingArray;




@Chervil:


Let's look at a simple example.
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
    int a;         // define an ordinary integer variable
    int * p;       // define a pointer to an int
    p = &a;        // assign address of variable a to pointer p  
    *p = 3;        // store value 3 in the variable pointed to,
                   // that is, store 3 in variable a.  

That code is ok.
But the code in your example was more like this:
1
2
3
4
5
6
1
2
3
    int * p;       // define a pointer to an int
    *p = 3;        // store value 3 in the variable pointed to,
                   // but what does p point to ????  

In the last example, the pointer contains garbage, it could point to anything at all. If you attempt to store a value there, the program will attempt to modify the contents of some memory location somewhere. Sometimes the program will crash, but this is not guaranteed to happen, the program could silently corrupt some part of computer memory which may have unpredictable effects, not necessarily immediately.






In one of my posts, I found great examples, but explanations got really messy that it was hard to follow for other poeple. I hope now people can follow it easier. :)
Last edited on
Topic archived. No new replies allowed.