My program is supposed to out put 10 20 40, but it doesn't. What's wrong with it?

int main()
    {
        int arr[3] = { 5, 10, 15 };
        int* ptr = arr;

        *ptr = 10;          // set arr[0] to 10
        *ptr + 1 = 20;      // set arr[1] to 20
        ptr += 2;
        ptr[0] = 30;        // set arr[2] to 30

        while (ptr >= arr)
        {
            ptr--;
            cout << ' ' << *ptr;    // print values
        }
	cout << endl;
    }

When you post a question, post details about what the problem is, not just "it don't work". *ptr + 1 = 20; is not allowed. You can't have addition on the left the way you have it. Put parentheses around the terms *(ptr + 1) = 20; .

if ptr[0]=30 sets the value of last element in arr to 30, then currently the pointer is at the last element. so the statement ptr-- inside the while loop as the first statement makes you lose the last element and it is not printed.


and, for my information does *(ptr+1) do the job. coz the aray is of type int which most probably takes two bytes. so isnt it supposed to be *(ptr+2) or just *(ptr++)

iand, for my information does *(ptr+1) do the job. coz the aray is of type int which most probably takes two bytes. so isnt it supposed to be *(ptr+2) or just *(ptr++)

No, the pointer arithemetic takes care of the inrement for you once you mention the pointer type. Hence if you have a pointer to an array of integers then doing ptr++ would do the trick -- ie increment it automaticallly by 4 bytes or whatever be the size of the datatype.

and, for my information does *(ptr+1) do the job. coz the aray is of type int which most probably takes two bytes. so isnt it supposed to be *(ptr+2) or just *(ptr++)

*(ptr+2) :
No. When adding to a pointer, the 1 is translated to 1 full unit, so the 1 == sizeof(int) *(ptr++) :
Yes, this would work, but that actually changes the pointer which was not the intent.

If ptr[0]=30 sets the value of last element in arr to 30, then currently the pointer is at the last element. so the statement ptr-- inside the while loop as the first statement makes you lose the last element and it is not printed.

I don't get this explanation.It printed out 10, 20, 2. But why the 2? How must i change the addition to make it work?

I tried this:

int main()
    {
        int arr[3] = { 5, 10, 15 };
        int* ptr = arr;

        *ptr = 10;          // set arr[0] to 10
        *(ptr + 1) = 20;      // set arr[1] to 20
        ptr += 2;
         ptr[0] = 30;        // set arr[2] to 30

        while (ptr >= arr)
        {
            cout << ' ' << *ptr;    // print values
            ptr--;
        }
    cout << endl;
    }

and this printed 30 20 10 (the reverse of what i wanted).

while (ptr >= arr)
        {
            cout << ' ' << *ptr;    // print values
            ptr--;
        }

That's because you're entering the information into the array forward, and then you print it out backwards. Enter the data into the array backwards, or print out the information forwards. Either way, if you want the data to be printed out correctly, you'll need to print it out in the same order as you stored it.

Alright, I switched it so I entered the array information backward, and it's works fine.


I just don't johnpeter's line:

if ptr[0]=30 sets the value of last element in arr to 30, then currently the pointer is at the last element. so the statement ptr-- inside the while loop as the first statement makes you lose the last element and it is not printed.

Alright, I switched it so I entered the array information backward, and it's works fine.


I just don't johnpeter's line:

I think what he meant is that if you call ptr-- before you print out the element, then yes, you will lose the last element. But since you've got it after the cout , then you won't have any problems.

(Correct me if I'm wrong.)

I see, I think the bigger idea i'm missing out on is this:

what does the while (ptr >= arr)mean in context?
In this case, if ptr -- works, then why am I starting from index 2 (arr[2]) and working my way down?

I see, I think the bigger idea i'm missing out on is this:

what does the while (ptr >= arr)mean in context?

Think of it like this: ptr is pointing to the last element in the array arr . So at the moment, ptr > arr because arr refers to the first element in the array. You keep moving ptr backwards, and when it passes out of arr , it will be pointing at some "random" memory address. When this happens, ptr != arr, and the while loop is terminated.

In this case, if ptr -- works, then why am I starting from index 2 (arr[2]) and working my way down?

Because that's the easiest right now, as ptr is pointing to the last element in arr. If you wanted to, you could make ptr point to arr like this:

ptr = arr;

And then your loop could go forwards. You could test it in the while loop like ptr >= &arr[2] , or you could just scrap the while loop and use for for 3 iterations.

Okay thanks JoeProgrammer for the explanation. I understand much more.

Sorry to switch topics, but I have another question:

This is a separate function:

void findDisorder(int arr[], int n, int* &p)
      {
          for (int k = 1; k < n; k++)
          {
              if (arr[k] < arr[k-1])
              {
                   p = arr + k;
                   return;
   
              }
          }
        p = NULL;
      }       
          
  int main()
  {
        int nums[6] = { 10, 20, 20, 40, 30, 50 };
        int* ptr = new int;
   
        findDisorder(nums, 6, ptr);
              
        if (ptr == NULL)
            cout << "The array is ordered" << endl;
        else
        {
              cout << "The disorder is at address " << ptr << endl;
              cout << "It's at index " << ptr - nums << endl;
              cout << "The item's value is " << *ptr << endl;
        }
  delete ptr; 
  }

I'm just confused as to why I need to use the new operator in certain situations.

Why would I need

int* ptr = new int;

instead of just

int* ptr

? I don't know which instances when I need to use, or not, and the purpose.

I'm just confused as to why I need to use the new operator in certain situations.

Why would I need

int* ptr = new int;

instead of just

int* ptr

? I don't know which instances when I need to use, or not, and the purpose.

At first, it may seem like you don't need it. But as you recall, new allocates memory. Simply using int *ptr; will not allow you to store anything, because it's not pointing to any memory address.

But, you might say, "I'm merely passing the address of ptr to findDisorder()." Well, look carefully. Does findDisorder() allocate any memory? No. So memory has to be allocted some place, and in this case, it's allocated in main(). If you try to use a pointer when it's not pointing to anything, you'll get a GP fault. Also notice the good programming practice the author used by deleting the pointer before the program ended to prevent a memory leak.

Hope this helps

Thank you, it was very clear.
Just one point I'm not so sure though:

Does findDisorder() allocate any memory? No. So memory has to be allocted some place, and in this case, it's allocated in main().

How do I know if findDisorder() allocates any memory?

In C++ the only way you can allocate memory on the fly is with the new operator. If you don't see the keyword new anywhere in the code, then no dynamic memory is allocated. Static memory is allocated any time you declare an object or a function. The amount of static memory allocated is not changeable at run time, whereas the amount of dynamic memory is changeable at runtime. The compiler/program will deallocated the static memory automatically. However, you need to deallocate (free, release, delete, whatever term you want to call it) any dynamic memory you use since the compiler/program doesn't know how much will be allocated during any given run of the program.

How do I know if findDisorder() allocates any memory?

As previously stated, new is used for dynamic memory allocation in pointers. However, pointers do not always need memory dynamically allocated for them to be useful. For example, one could create a static object and use a pointer to point to it. In that case, no new declaration would be needed.

This is not an issue here, as pointers are not used to modify other static objects.

Okay, hold on: Someone told me that this would be the solution:

# include <iostream>
using namespace std;

void findDisorder(int arr[], int n, int** p)
    {
        for (int k = 1; k < n; k++)
        {
            if (arr[k] < arr[k-1])
            {
                 *p = arr + k;
             return;
            }
        }
    *p = NULL;
    }       
        
int main()
{
      int nums[6] = { 10, 20, 20, 40, 30, 50 };
      int* ptr; 
      findDisorder(nums, 6, ptr);
        
    if (ptr == NULL)
        cout << "The array is ordered" << endl;
    else
    {
            cout << "The disorder is at address " << ptr << endl;
            cout << "It's at index " << ptr - nums << endl;
            cout << "The item's value is " << *ptr << endl;
    }
}

What's up wtih the ** (pointer to pointer to int)??

What's up wtih the ** (pointer to pointer to int)??

OK, remember that one * means that the variable is a pointer. So guess what ** means? It's a pointer to a pointer. In the previous example, you avoided this by using int * &p , which is also **, but using the & means that after the declaration, it's only a single pointer. Hope that made sense what I just said.

The code you just posted would work, except I think there's an error here:

findDisorder(nums, 6, ptr);

Because ptr is only a single pointer, and the function is asking for a pointer to a pointer (**), then you will need to give ptr to them like this:

findDisorder(nums, 6, &ptr);

In the code you just posted, also notice later on in findDisorder(), it now refers to ptr as *ptr , because it's modifying the address that's being pointed to, but not the memory address that points to the second memory address. Using & instead of another * in the first example allowed the use of modifying what ptr pointed to without using a *.

Hope this helps

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.