TransWikia.com

pointers cant read the correct elements in array

Stack Overflow Asked by Jabou on November 29, 2020

I have a pointers in C, and I can’t figure out how it works.
Below is the code:

// ptr points to an array of 2 ints
int (*ptr)[2];
int torf[2][2] = {12, 14, 16};
ptr = torf;

int (*ptr_2)[2];
int torf_2[2][2] = { {12}, {14, 16}};
ptr_2 = torf_2;
  
printf("%d %dn", **ptr, **(ptr + 2));
printf("%d %dn", **ptr_2, **(ptr_2 + 2));

The answer I want should be:

12 16
12 14

But actually I got on my PC:

12 6422000
12 12

Any ideas?

2 Answers

If you add these lines to the end of your program:

printf("%p: %p %pn", ptr, ptr+1, ptr+2);
printf("%p: %p %pn", *ptr, *ptr+1, *ptr+2);
printf("%p: %p %pn", **ptr, **ptr+1, **ptr+2);

You will note that in the first case, the numbers increase by 8, which could either be the size of a pointer or two ints. Same goes for the second, but the third increases by the size of an int; so that is good.

So, to disambiguate 2 ints or 1 address, lets do a s/2/3/g. Now, we see the first case the increment is now 12 ( = 3 * 4 ). Your second case ( *ptr + i ) increments by 4, so is the address of successive ints Your third case is the integer values themselves.

Where did it get confusing? Quick checklist:

  1. When you are trying to workout pointer / indexing problems, use unique values as much as possible.

  2. Pay attention when the compiler warns you. Eventually you will know to ignore "format '%p' expects argument ... ", but it takes time to build the confidence.

  3. There is a handy program, cdecl, which converts C type expressions into something english like.

  4. In virtually all C implementations, int x[2][2], y[4]; have the same layout; that is, C multi-dimensional arrays are just an overlay of a single dimension array, with the arithmetic cleverly hidden. For this reason, definitions like int (*p)[2]; are rare and rarely useful. If you must go down this road, it is likely better to do something like:

    typedef int pair[2]; pair torf[2] = { { 0, 1 }, { 2, 3 }}; pair *ptr = torf;

if nothing else, somebody has a chance to understand it...

Answered by mevets on November 29, 2020

try this:

// ptr points to an array of 2 ints
int(*ptr)[2];
int torf[2][2] = { 12, 14, 16 };
ptr = torf;

int(*ptr_2)[2];
int torf_2[2][2] = { {12}, {14, 16} };
ptr_2 = torf_2;

printf("%d %dn", **ptr, **(ptr + 1));
printf("%d %dn", **ptr_2, **(ptr_2+1));

when you use pointers it is like the indexes of the array it begin from 0;

good work

Answered by ori ofek on November 29, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP