-2

Is there a difference of declaring int *p; or int **p; I know **p is used for a pointer to a pointer but *p can also be assigned to a pointer so my question is there a difference between them?

void main()
{

    int numDays;
    double sum = 0;
    double avg;
    cout << "Enter the number of days of sales";
    cin >> numDays;
    double *Sales = new double[numDays];
    double *p = Sales;
    for (int i = 0; i < numDays; i++)
    {
        cout << "enter how much you sold for day " << i << endl;
        cin >> *p;
        sum = sum + *p;
        p++;


    }


    avg = sum / (numDays);
    cout << "the sum is" << sum << endl;
    cout << "the avg is" << avg << endl;

    delete[]Sales;

why don't we use pointertopointers for a dynamic array such as this in this spot

double *Sales = new double[numDays];
        double *p = Sales;

or can you?

  • 1
    Yes. A regular `int *` points to a bunch of ints in memory. An `int **` points to a pointer to a bunch of ints in memory... – Millie Smith Apr 18 '16 at 00:57
  • 2
    Possible duplicate of [Why use double pointer? or Why use pointers to pointers?](http://stackoverflow.com/questions/5580761/why-use-double-pointer-or-why-use-pointers-to-pointers) – jtbandes Apr 18 '16 at 00:57
  • @MillieSmith Actually an `int **` points to *some number* of pointers, where each points to some number of `ints`. – Daniel Jour Apr 18 '16 at 00:59
  • @MillieSmith - an `int**` pointes to a bunch of (as in 1 or more) `int*`s in memory. Those `int*`s may or may not point to `int`s. For example, they may all be NULL, in which case they don't point anywhere. – Pete Becker Apr 18 '16 at 01:02
  • @DanielJour technicalities. – Millie Smith Apr 18 '16 at 03:53
  • @PeteBecker Actually, an `int **` may not point to an `int *` in memory. It may be NULL. – Millie Smith Apr 18 '16 at 04:01
  • @MillieSmith - and `int*` may not point to an `int` in memory. It may be NULL. But that wasn't your point, nor mine. – Pete Becker Apr 18 '16 at 12:23
  • @PeteBecker that was pretty much half of your comment, actually. My point is you're being pedantic. Time to delete these comments and move on. – Millie Smith Apr 18 '16 at 15:45

3 Answers3

0

They are different types. One level of indirection above an int, vs two levels.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
0

I know **p is used for a pointer to a pointer

Correct.

but *p can also be assigned to a pointer

But not to a pointer to a pointer.

so my question is there a difference between them?

Yes.

user207421
  • 305,947
  • 44
  • 307
  • 483
0
int * ptr

pointer->value

int ** ptr

pointer->pointer->value

Stephen
  • 1,498
  • 17
  • 26