0

I want to create 2d array using pointer and show then show it. I change rows by increment pointer (one *) and columns by index. My code:

int ** tabl=new int *[4];
for (int i=0;i<10;i++)
    tabl[i]=new int [3];
int **ptab=tabl;//save first position of array

for (int i=0;i<4;i++)
{
    for (int j=0;j<3;j++)
    {
        *tabl[j]=rand()%10 +1;
        printf("%4d",*tabl[j]);
    }
    tabl++;
}
tabl=ptab;
cout<<endl<<endl<<endl;
for (int i=0;i<4;i++)
{
    for (int j=0;j<3;j++)
    {
        printf("%4d",*tabl[j]);
    }
    tabl++;
}

Output:

   2   8   5   1  10   5   9   9   3   5   6   6

   2   1   9   1   9   5   9   5   6   5   6   6

But some of the digits in the second loop are different then the original. Why?

3
  • *tabl[j] means tabl[j][0]. You actually wanted tabl[0][j]. It would be better to use tabl[i][j] instead, and not do tabl++, and not have ptab. Commented Dec 3, 2015 at 21:54
  • I know two index method, but my teacher from studies demand using pointers. Commented Dec 3, 2015 at 21:57
  • This does use pointers. When you write tabl[i], actually tabl decays to a pointer, and the code is defined as being equivalent to *(tabl+i). Commented Dec 3, 2015 at 22:00

1 Answer 1

5

The problem is the way you refer to the element. It should be (*tabl)[j], not *tabl[j].

Also note that you go beyound allocated memory here:

int ** tabl=new int *[4];
for (int i=0;i<10;i++)
               ^
    -----------+
Sign up to request clarification or add additional context in comments.

2 Comments

I changed size from 10 to 4, because I really didn't see all values, that's why "10" left(I missed it). Of course I corrected it. I understand the brackets are there because of the priorities?
Yes, *tabl[j] means "dereference j-th element of tabl", not "j-th element of dereferenced table"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.