Question about the efficiency of using an array or individual variables

In summary, the conversation discusses the efficiency of using array A[10] versus individual variables B(0..9) in a program. The individual variables may be faster due to their one-step access, while the array requires additional steps to access the desired value. The conversation also touches on the limitations of declaring arrays with a constant size and the use of vector as a workaround. Finally, the conversation explains the difference in initialization between {1} and {1, 1, 1, 1, 1, 1, 1, 1, 1, 1} for an array of boolean values.
  • #106
What is the physical address location of a float variable.

Maybe this analogy can help: A 24 kOhms resistor is a resistor. An 8 Ohms resistor is a resistor. Will you think it is fine to use a 24 kOhms resistor where the schematic specifies an 8 Ohms resistor should go? Both are resistors, isn't it the same thing? Or do you think that a schematic will just say resistor? Or if your employee wrote a schematic and it just said resistor here, and you read it, you will give it the thumbs up? The book said it's a resistor so the book must be wrong?
 
Last edited:
Technology news on Phys.org
  • #107
I am not arguing whether the C++ language allow you to do this or not. I have to obey the C++ regardless. BUT what I am trying to say is the book said &myfloat is the physical address of the float myfloat. So why can't I use pointer to point to the first byte of myfloat?
C++:
// address of float variable
#include <iostream>
using namespace std;

int main()
{
    float test;
    int* ptr;
    cout << "the address of float test is " << &test << "\n\n";

    return 0;}

You can see the program actually return with the physical address of the variable myFloat.

My question is why C++ don't allow to use pointer for a float? Why have to restrict to int variable. what if I need to work with a float variable?

If we are allow to initiate float *pint; for pointer for float, I would not have a problem.

I guess I am very literal, when you say *pint is an address pointer, you should be able to point to anything within the physical memory.

Are you telling me if I work with float variable, I can forget the whole chapter of pointers as it won't work?
 
  • #108
yungman said:
what I am trying to say is the book said &myfloat is the physical address of the float myfloat

Yes.

yungman said:
why C++ don't allow to use pointer for a float?

It does. I just told you how to write the code in post #105.

yungman said:
If we are allow to initiate float *pint; for pointer for float, I would not have a problem.

Apparently you have not read post #105, since that's exactly the code I wrote there (except that I said float *pFloat to make the pointer variable name more descriptive).
 
  • Like
Likes yungman
  • #109
@yungman, you are having difficulty understanding the difference between an integer value and a pointer value. In the past, on machines with segmented memory, pointers were stored in a form with a part that indicated the memory segment, and another part that indicated the offset within that segment. The onset of 32-bit programming led to a so-called "flat" memory model, with bytes labelled from 0 to some relatively large number.
The fact that these memory addresses are now integers does not mean that they are of type int or long or whatever. As already mentioned C and C++ are strongly typed, and compilers distinguish between the addresses of an int or of a float, which is something I pointed out a few posts back.
If you have an int variable, and add 1 to it, you get an int value that is 1 larger. The same is not true in general for pointers.
Here's an example.
C++:
double val = 3.75;
double * dPtr, * dPtr2;
dPtr = &val;
dPtr2 = dPtr + 1;
cout << "dPtr: " << dPtr << "\n";
cout << "dPtr2: " << dPtr2 << "\n";
When I ran this, the output was
Code:
dPtr: 00EFFEC8
dPtr2: 00EFFED0
Notice that by adding 1 to the address in dPtr, I got a value that was larger by 8, which should not happen if dPtr was an ordinary integer.
 
  • Like
Likes pbuk
  • #110
PeterDonis said:
Yes.
It does. I just told you how to write the code in post #105.
Apparently you have not read post #105, since that's exactly the code I wrote there (except that I said float *pFloat to make the pointer variable name more descriptive).
Sorry I did not see that when I was busy responding. Now I am happy. that there is a float *ptr for &myFloat.

Why the book did not say that in the same sentence? I am not arguing, but who give a C#$% whether the *ptr is pointing to the address of an int, a float or char, just point at the first address of the variable!

I hope there's no char *ptr just for pointing at a char variable!o_Oo_Oo_O

Thanks
 
  • #111
I was joking too soon, they sure use different ones for different variabes! I wrote a quicky:
C++:
#include <iostream>
using namespace std;

int main()
{
    char testC;        char* ptC;        ptC = &testC;
    cout << "the address of char testC is = " << &testC << "    The content of ptC is  = " << ptC << "\n\n";

    float test;        float* ptr;        ptr = &test;
    cout << "the address of float test is = " << &test << "    The content of ptr is  = " << ptr << "\n\n";

    double* ptD;    double testD;   ptD = &testD;
    cout << "the address of double testD is = " << &testD << "    The content of ptD is  = " << ptD << "\n\n";

    const int* ptCS;    const int testCS=7;   ptCS = &testCS;
    cout << "the address of const int testCS is = " << &testCS << "    The content of ptCS is  = " << ptCS << "\n\n";

    return 0;
}

All except char work.

If you run this, the address of char looks funny, all the other ones work.
 
  • #112
yungman said:
All except char work.

If you run this, the address of char looks funny, all the other ones work.
The cout class has member functions called operator <<. One of them takes a char * as an argument, and considers it as a c-string (null terminated array of char), so it tries to output the characters pointed to by the pointer rather than the pointer itself. They chose this behaviour so it's convenient to print c-strings.
 
Last edited:
  • Like
Likes yungman
  • #113
Jarvis323 said:
The cout class has member functions called operator <<. One of them takes a char * as an argument, and considers it as a c-string (null terminated array of char), so it tries to output the characters pointed to by the pointer rather than the pointer itself. They chose this behaviour so it's convenient to print c-strings.
Didn't think of "*" is a character! So how do you define a char pointer? I flip through half the chapter on pointers, no mention on any of these. and this is the best book I have so far.
 
  • #114
yungman said:
Didn't think of "*" is a character!
In the context of your example, * is not a character. The type char * is a pointer to a character.

If you do this, your first section works.
C++:
char testC = 'a';
char* ptC = &testC;
cout << "the address of char testC is = " << (void *)ptC << "    The character pointed to is  = " << *ptC << "\n\n";
The overload of ostream:: operator << that takes a char * expects what is pointed to be a C string, and this operator inserts all of the characters starting from that address until and including a terminating null character.
If you add the cast that I showed, you get just the pointer's address value.
 
Last edited:
  • #115
yungman said:
I hope there's no char *ptr just for pointing at a char variable

yungman said:
they sure use different ones for different variabes

For different types, as I already told you:

PeterDonis said:
for each type in C, C also has a corresponding pointer type; the C type "pointer to X" represents the address of something with type X
 
  • #116
Hi @yungman, let's try this.

In your Notes you have: *Page 496: Pointer variable: int* ptr;
Which is fine.

A point that has not been mentioned is that internally the C compiler keeps track of what kind of object is being pointed to. Here is the reason.
If you write x= &ptr + y, the compiler has to know whether the variables are Integers, Floats, Longs, and so on. That way it can call the correct Add routine, or maybe first call a conversion if the types are not all the same.

In the int* ptr; you are declaring a variable called ptr, telling the compiler to treat it as a Pointer to something by using the *, then telling it that it is pointing to a variable that is an Integer.

When ptr is entered into the compilers symbol table for later use, it has attached to it the information that it is a Pointer, and that it refers to an Integer. So yes, PART of the information saved in ptr is an address (these days it looks like an unsigned integer, or maybe an unsigned long), but it also contains that "Hey, it's an Integer There" information. So referring to ptr returns all of this, not just the address (which may look like an integer).

(A rather lame equivalent, like reading a mystery novel where all the players and suspects are not introduced!)

Hope this helps!

Cheers,
Tom
 
  • Like
Likes yungman
  • #117
PeterDonis said:
The OP's confusion is not about different ways bytes stored in memory can be interpreted. His confusion is about how the addresses of those bytes are interpreted.
Yes, I was confused because the way the book is written for this chapter. I decided to stop talking and went through most of chapter 9. It is NOT a well written chapter. It just gave the example that pointing to a float is an error and left it at that. The book later just talk about each type one at a time and mostly with example instead of listing pointers of different type from the beginning. That cause my confusion and concern. Like it spread these through 20 to 30 pages and never have a summation of all the pointers and their reason of why to have different types.

Yes, I did jump to conclusion after reading the next few pages that did not talk about other types of pointers. I thought that was it? That I apologize. Sorry.
 
  • #118
Hi Everyone

I want to apologize for being so stubborn. I finished a lot of Chapter 9, it did explain those later and I understand a lot more. It's NOT a well written chapter. But that doesn't excuse the fact that I jumped the gun. That I am sorry and apologize to everyone that tries so hard to help me.

I think the first thing I am doing is to slow down and take it easy for a day or two. I guess I am very driven and want to push to learn as fast as I can. I used to think I can learn a new language in like two or three weeks back in the days. I have been on this C++ for over a month and still have some ways to go. That kind of putting the pressure on me to work harder. C++ just have so much more things than assemble, FORTRAN, Basic and Pascal. That it's not a two weeks thing and frustration starting to get to me. To that, again, I am sorry.
 
  • #119
I want to check with you guys how much I need to cover in the Gaddis. I understand of cause I should finish the whole book. But I also know from my grandson that his class covered up to chapter 11 only, and they skipped around also.

Here is an online copy of the book:https://cplusplushelp.weebly.com/st...-control-structures-through-objects-book.html

I definitely want to cover chapter 12 on files, that's my interest. Sounds like from response here, I better study Chapter 13 on introduction of Classes. Do I need to study chapter 14 and 15?

My goal is to learn computer science, not necessary be expert in C++. It is only the first modern language I decided to learn. I want to know what is the next logical step of my learning. Please advice.

In the olden days, people advice me to learn data structure and algorithm that is not language specific. Are the later chapters in Classes, structures have anything to do with these? That if I study chapter 13, 14 and 15 will help on my programming regardless of what language? I really don't know exactly what I am asking as the advice was from 40 years ago, obviously things have changed tremendously in programming already.

Thanks
 
  • #120
yungman said:
I definitely want to cover chapter 12 on files, that's my interest. Sounds like from response here, I better study Chapter 13 on introduction of Classes. Do I need to study chapter 14 and 15?
My advice is to definitely study Ch. 13. The concepts presented in that chapter start to cover what makes C++ an object-oriented language. Without it, what you've been doing is pretty much C plus the C++ take on I/O (i.e., using the cout and cin stream objects). The fact that your grandson's class covered only the first 11 chapters shouldn't enter into your decision. After all, his class was constrained by time, with either 10 weeks for a quarter of 15 weeks or so for a semester. No doubt his class was in Intro to Programming with C++. You don't have those constraints.
I would also advise that you study at least the first half of Ch. 14, where it discusses writing your own classes. If you don't want to do the whole chapter, you could skip that latter part where Gaddis goes over operator overloading. Since you don't intend to become an expert, you could skip Ch. 15, which gets into the concepts of inheritance, polymorphism, and virtual functions.
yungman said:
My goal is to learn computer science, not necessary be expert in C++. It is only the first modern language I decided to learn. I want to know what is the next logical step of my learning. Please advice.

In the olden days, people advice me to learn data structure and algorithm that is not language specific. Are the later chapters in Classes, structures have anything to do with these?
Not very much. You'll need another book for data structures and algorithms, but what you learn from the book you're working in will be helpful, as it will likely show examples in C++ (unless you get a book that is Java-based). The data structures will include things like singly- and doubly-linked lists, binary trees, and other structures, plus algorithms for searching through the various structures or sorting them. A fair amount of the presentation on algorithms will be focused on how efficient various algorithms are.
yungman said:
That if I study chapter 13, 14 and 15 will help on my programming regardless of what language?
Ch. 13 and at least the parts in Ch. 14 that are about writing classes will definitely help.
 
  • Like
Likes yungman
  • #121
jedishrfu said:
The ++ pre and post operators can make some interesting reading as compilers differ as to how they are interpreted. As an example, (++x - x++) = ? where x is some integer.
That reminded me to check. Yes, the obsfucated C contest is still active.

https://www.ioccc.org/
 
  • Like
Likes jedishrfu
  • #122
Mark44 said:
My advice is to definitely study Ch. 13. The concepts presented in that chapter start to cover what makes C++ an object-oriented language. Without it, what you've been doing is pretty much C plus the C++ take on I/O (i.e., using the cout and cin stream objects). The fact that your grandson's class covered only the first 11 chapters shouldn't enter into your decision. After all, his class was constrained by time, with either 10 weeks for a quarter of 15 weeks or so for a semester. No doubt his class was in Intro to Programming with C++. You don't have those constraints.
I would also advise that you study at least the first half of Ch. 14, where it discusses writing your own classes. If you don't want to do the whole chapter, you could skip that latter part where Gaddis goes over operator overloading. Since you don't intend to become an expert, you could skip Ch. 15, which gets into the concepts of inheritance, polymorphism, and virtual functions.
Not very much. You'll need another book for data structures and algorithms, but what you learn from the book you're working in will be helpful, as it will likely show examples in C++ (unless you get a book that is Java-based). The data structures will include things like singly- and doubly-linked lists, binary trees, and other structures, plus algorithms for searching through the various structures or sorting them. A fair amount of the presentation on algorithms will be focused on how efficient various algorithms are.
Ch. 13 and at least the parts in Ch. 14 that are about writing classes will definitely help.
Thank you for the advice. I will study cpt 13 and at least the part you suggested on cpt 14. What is the next logical thing I should study after that? I suspect I will finish those by Christmas.

I don't know what to expect and what I should do, what direction I should take (not that it is important for me as I am not looking for a career). I just don't know enough about computers now a days. Part of the reason I even get into this is because my grandson is CS major. I was even joking with him when he said he need more motivation. I said maybe the best motivation is when grandpa nipping on the grandson's heel on programming!

I am not into gaming, what intriguing to me is when I watch tv on shows people deal with virus attack, how they kill the virus in the tv shows. I want to learn more about the inner working of computers and virus prevention stuffs. They even had a show called CSI Cyber.
 
  • #123
I have a problem I just cannot solve. This is about passing pointer as reference to a function to create an array in the function, then passing the pointer( NOT by return ptr;) as parameter back to main(). No matter how I try, there is always error in compile. The difficulty is I want to use arr = new int[5] in the function to get memory from computer, then later to delete[] in main().
C++:
//Function return pointers
#include <iostream>
using namespace std;

void getRNum(int*, int);//return a pointer from the functionint main()
{
    int size = 5;
    int *number;//initiate a pointer number
    getRNum(number, size);//get the pointer to array of 5 random numbers
    for (int count = 0; count < 5; count++)// display the numbers
        cout << *(number + count) << "\n\n";
    delete[] number;//free the memory of 5 element array number[5]
    return 0;
}
void getRNum(int *arr, int num)//receive an integer 5 to num, return a pointer to array arr.
{
    arr = new int[num]; //request 5 elements of int of memory from computer
    for (int count = 0; count < num; count++)// input 5 integers
    {
        cout << " Enter number " << count + 1 << " = ";
        cin >> arr[count]; cout << "\n\n";
        cout << " In memory location: " << (arr + count) << "\n\n";
    }
}

I don't like to use return ptr to return the pointer as shown in the book. I want to do this through passing parameters. Is there any way to do that?

Thanks
 
  • #124
yungman said:
This is about passing pointer as reference

You're not passing the pointer by reference, you're passing it by value. If you want to pass the pointer by reference, you need to define a variable that holds a pointer to the pointer; that variable is what then would get passed to the function.

For example, you would initialize the variable in your main function like this:

C:
int** pNumber;

The signature of the function you call would look like this:

C:
void getRNum(int** pArr, int num);

And inside the getRNum function you would have to do this to pass the address of the array of 5 numbers back to the main function:

C:
*pArr = arr;

[Note: the above code has been edited from the original version of this post.]

yungman said:
I don't like to use return ptr to return the pointer as shown in the book.

Why not? It's a lot simpler than the above rigmarole, for no benefit that I can see.
 
Last edited:
  • #125
yungman said:
I don't like to use return ptr to return the pointer as shown in the book.

Why not?
 
  • Like
Likes jedishrfu
  • #126
PeterDonis said:
Why not?
Thanks for the reply.

You deleted the other post! I actually tried and it did not work. All the difficulty is because I want to do dynamic memory allocation, that I use *arr = new int [num] in the function and I want to delete[] number to free up the memory in main after getting the values of the array from the function.

The reason I want to do that is because I don't want to restrict to one parameter passing. I want to have the freedom to pass multiple pointers to array to the function.

I have been search up and down the chapter the whole last night, I have not found a way to do that. Passing pointers of array to function is easy, BUT with dynamic memory allocation is a different story.

Thanks
 
  • #127
yungman said:
You deleted the other post! I actually tried and it did not work.

What went wrong? What error messages did you get?
 
  • #128
yungman said:
want to have the freedom to pass multiple pointers to array to the function.

The usual way to do this would be to define a struct containing multiple array pointers, and return a pointer to an instance of the struct created with new.
 
  • #129
yungman said:
You deleted the other post!

I've undeleted it now, with a correction.
 
  • #130
PeterDonis said:
The usual way to do this would be to define a struct containing multiple array pointers, and return a pointer to an instance of the struct created with new.
Thank
Maybe I should move on as I have not learn that, I don't want to trouble you to teach me ahead where I can learn in the later chapters. I am just being adventurous.

I kind of suspect this is beyond my level for the moment. But I did practice a lot trying to find a way to make it work, it's like reviewing the chapter over and over again.

thanks
 
  • #131
yungman said:
I did practice a lot trying to find a way to make it work

Without any specific information on what error messages you saw when you tried different things, there's not much we can do to help.
 
  • #132
yungman said:
Thanks for the reply.

You deleted the other post! I actually tried and it did not work. All the difficulty is because I want to do dynamic memory allocation, that I use *arr = new int [num] in the function and I want to delete[] number to free up the memory in main after getting the values of the array from the function.

The reason I want to do that is because I don't want to restrict to one parameter passing. I want to have the freedom to pass multiple pointers to array to the function.

I have been search up and down the chapter the whole last night, I have not found a way to do that. Passing pointers of array to function is easy, BUT with dynamic memory allocation is a different story.

Thanks

Allocating memory in one function and deleting later in the calling function is a bad paradigm to follow. Users of your function or even yourself may forget to delete the allocated memory.

Best practice is to have two functions that are paired like my_alloc() / my_free() where memory is allocated in one and freed in the other and then the calling function calls my_alloc() does something with the data and the calls my_free() when finished.

C:
// pseudo code example

my_function(...) {

    data = my_alloc()

    .. do something with data...

    data.my_free();  // alternatively my_free(data);

}
 
  • Like
Likes yungman
  • #133
jedishrfu said:
Allocating memory in one function and deleting later in the calling function is a bad paradigm to follow. Users of your function or even yourself may forget to delete the allocated memory.

Best practice is to have two functions that are paired like my_alloc() / my_free() where memory is allocated in one and freed in the other and then the calling function calls my_alloc() does something with the data and the calls my_free() when finished.

C:
// pseudo code example

my_function(...) {

    data = my_alloc()

    .. do something with data...

    data.my_free();  // alternatively my_free(data);

}
Thanks

I just follow the book, this is the exercise in the book that I did, it got the memory in the function and release the memory in main. The difference is the program uses return arr instead of passing back as parameter. This is the original program:
C++:
#include <iostream>
#include <cstdlib>//for rand and srand
#include <ctime>//for time function
using namespace std;

int *getRNum(int);//return a pointer from the functionint main()
{
    int *number; // to point to number
    number = getRNum(5);//get the pointer to array of 5 random numbers
    for (int count = 0; count < 5; count++)// display the numbers
        cout << number[count] << "\n\n";
    delete[] number;//free the memory of 5 element array number[5]
    number = 0;//set pointer to 0
    return 0;
}
int *getRNum(int num)//receive an integer 5 to num, return a pointer to array arr.
{
    int *arr;// initialize point to array arr to hold 5 elements, num = 5
    if (num <= 0)
        return NULL;
    arr = new int[num]; //request 5 elements of int of memory from computer
    srand(time(0)); // Seed the random number
    for (int count = 0; count < num; count++)
        arr[count] = rand();
    return arr;//return the starting address of arr.
}
 
  • #134
PeterDonis said:
Without any specific information on what error messages you saw when you tried different things, there's not much we can do to help.
I tried what you suggested, this is the program and the error message:
C++:
#include <iostream>
using namespace std;

void getRNum(int**, int);//return a pointer from the functionint main()
{
    int size = 5;
    int **pNumber;//initiate a pointer number
    getRNum(pNumber, size);//get the pointer to array of 5 random numbers
    for (int count = 0; count < 5; count++)// display the numbers
        cout << *(pNumber + count) << "\n\n";
    delete[] pNumber;//free the memory of 5 element array number[5]
    return 0;
}
void getRNum(int **pArr, int num)//receive an integer 5 to num, return a pointer to array arr.
{

    int *Arr = new int[num]; //request 5 elements of int of memory from computer
    *pArr = Arr;
    for (int count = 0; count < num; count++)// input 5 integers
    {
        cout << " Enter number " << count + 1 << " = ";
        cin >> *pArr[count]; cout << "\n\n";
        cout << " In memory location: " << (pArr + count) << "\n\n";
    }
}
Compile error Listing 7.2.jpg


There are just different error messages for different way, I kind of understand the error messages, I just cannot fix it.

What is the ** mean? Like I said, if it is something I have not learned yet, I just let this go and wait until the time comes to learn struct.

Thanks
 
  • #135
yungman said:
I kind of understand the error messages, I just cannot fix it.

The pNumber variable needs to be initialized. The obvious way to initialize it is with a null pointer: int** pNumber = NULL;.

yungman said:
What is the ** mean?

As I said before, it's a pointer to a pointer. In other words, it's a pointer that stores the address of a variable that stores a pointer. In this case the variable that stores the pointer is pNumber, and you are passing the address of that variable to the getRNum function so the function can assign a value to it, namely the address of the array you allocate with new.
 
  • Like
Likes yungman
  • #136
PeterDonis said:
The pNumber variable needs to be initialized. The obvious way to initialize it is with a null pointer: int** pNumber = NULL;.
As I said before, it's a pointer to a pointer. In other words, it's a pointer that stores the address of a variable that stores a pointer. In this case the variable that stores the pointer is pNumber, and you are passing the address of that variable to the getRNum function so the function can assign a value to it, namely the address of the array you allocate with new.
Thanks, I did not know about assigning NULL to pointer. Yes, that eliminates the error. But it still did not return the pointer back to main.

I did try assigning NULL in my original program that doesn't use pointer to a pointer. I eliminated the error and it ran BUT the same thing, it cannot return the pointer from function back to main. This is the program, if you can help me fixing this, I am good.
C++:
//Function return pointers
#include <iostream>
using namespace std;

void getRNum(int*, int);//return a pointer from the functionint main()
{
    int size = 5;
    int* pNumber = NULL;//initiate a pointer number
    getRNum(pNumber, size);//get the pointer to array of 5 random numbers
    cout << " Back in main from getRNum.\n\n";
    for (int count = 0; count < 5; count++)// display the numbers
        cout << *(pNumber + count) << "\n\n";
    delete[] pNumber;//free the memory of 5 element array number[5]
    return 0;
}
void getRNum(int* pArr, int num)//receive an integer 5 to num, return a pointer to array arr.
{
    pArr = new int[num]; //request 5 elements of int of memory from computer
    for (int count = 0; count < num; count++)// input 5 integers
    {
        cout << " Enter number " << count + 1 << " = ";
        cin >> pArr[count]; cout << "\n\n";
        cout << " In memory location: " << (pArr + count) << "\n\n";
    }
}

Again thanks for you time to help me.
 
  • #137
yungman said:
it still did not return the pointer back to main.

That's because the type of the parameter pArr in the function signature for getRNum is still wrong; it needs to be int**, not int*. Then you pass the address of pNumber to the function using that parameter.
 
  • #138
PeterDonis said:
That's because the type of the parameter pArr in the function signature for getRNum is still wrong; it needs to be int**, not int*. Then you pass the address of pNumber to the function using that parameter.

To expand on this a bit, consider:

What your code is doing now:

(1) Initializing a variable whose type is "pointer to a variable of type int" to be a null pointer.

(2) Passing that null pointer to a function.

(3) That function treats the null pointer as the value of a local variable.

(4) The function then overwrites the null pointer stored in that local variable with the return value of new.

(5) When the function returns, the value stored in the local variable gets thrown away, since that variable is local to the function, and never gets passed back to the caller.

What the code will do if you change the types as I suggest:

(1) Initializing a variable whose type is "pointer to a variable of type int" to be a null pointer.

(2) Passing the address of that variable to a function.

(3) That function treats the address passed to it as a local variable.

(4) The function then writes the return value of new to the variable at the address that was passed to it.

(5) When the function returns, the caller has the return value of new--i.e., the pointer to the array of ints that was initialized in the function--in the variable whose address was passed.

Do you see the difference?
 
  • #139
Some comments on your (yungman) code for main() in post #136.
C++:
int main()
{
    int size = 5;
    int* pNumber = NULL;//initiate a pointer number
    getRNum(pNumber, size);//get the pointer to array of 5 random numbers
    cout << " Back in main from getRNum.\n\n";
    for (int count = 0; count < 5; count++)// display the numbers
        cout << *(pNumber + count) << "\n\n";
    delete[] pNumber;//free the memory of 5 element array number[5]
    return 0;
}
All line numbers referred to below start at the beginning of the code body.
Line 2 - We say "initialize" not "initiate." Also, your comment isn't much more helpful than no comment at all. A comment should not restate what the code is doing.
Line 3 - You have a variable named size. Any comments should refer to size, not its value. That way, you can change the value of size, and your comments will still be correct.
Line 5 - Use size instead of hard-coding 5 in the loop's condition expression.
Line 7 - It has already been mentioned that splitting the memory allocation and deallocation between two program elements is questionable. Besides this, you should not have 5 hard-coded here. Also, if the array has 5 elements, then number[5] is the element one past the end of the array.
Line 8 - A return statement used to be necessary in main(), but one of the new C++ standards, I believe, dispensed with that requirement.
 
  • #140
Hi Everyone
I have been doing a lot of googling, trying to learn pointer to a pointer and how to solve my problem I think I found it. But I just need to read more and let it sink in first before I post back. I don't want to jump the gun again. Here is the very simple program that works already, I just need to digest first, I still have a little difficulty bending my brain to say I got it.
C++:
// Pointer to a pointer
#include <iostream>
using namespace std;
void changePtVal(int**);
int Gvar = 42;
int main()
{
    int var = 23;   
    int* ptr = &var;
    cout << " Before calling changePtVal, *ptr = var = " << *ptr << " ptr = " << ptr << "\n\n";// the content in address ptr = var =23.
    changePtVal(&ptr);//**pptr = &ptr.
    cout << " After calling changePtVal, *ptr = " << *ptr << "\n\n";
    cout << " address of var = " << &var << " ptr = " << ptr << " *ptr = " << *ptr << "\n\n";
    return 0;
}
void changePtVal(int** pptr)
{
    *pptr = &Gvar;
}

//The result is:

//Before calling changePtVal, * ptr = var = 23 ptr = 012FFE48

//After calling changePtVal, *ptr = 42

//address of var = 012FFE48 ptr = 00EEC008 * ptr = 42

In case, this is the site I am reading:https://www.geeksforgeeks.org/passing-reference-to-a-pointer-in-c/
 

Similar threads

Replies
7
Views
2K
Replies
6
Views
2K
Replies
1
Views
1K
Replies
5
Views
2K
Replies
75
Views
5K
Replies
17
Views
2K
Replies
9
Views
2K
Back
Top