C-arrays and pointers: equivalent pointer to an array element

Edit: A similar question asked earlier did not address some aspects related to the problem.

Kernighan and Ritchie say in the ANSI C book that the following equivalents

  • a[i]
  • *(a+i)

I do not see how this could be true for elements that occupy more than one address space, for example. Structures

Explain, please? Edit: Thanks for all the answers, but I don't quite understand. It would seem that I am experiencing the same confusion as @CucumisSativus, from his answer and comments on him.

For example, sizeof (* a) is 3. I thought that it will be so if for some reason I wanted to gain access to the middle byte of the first element in a: *(a+1).

Say that the address ais 10, and the size of each element is 20. And, say, we want to get a pointer to the second element. As I see it, we could do this: p = (10 + 20). I thought it would be equivalent &a[1].

I am having real problems explaining what I don’t understand!

+3
source share
5 answers

I read more about K & R and discovered the missing pieces in the puzzle, which allowed me to rationalize what was happening. (I am right, or not, open to discussion!)

From what I am collecting, the following is simply not true:

p = (10 + 20)
  • Given that, quoting: "Pointers and integers are not interchangeable. The only exception is Zero."
  • , * (a + i) .
  • , .

K & R , :

(p + n) : " n p points to, p".

, : printf() . , " undefined", , , .

, , , , ( ) undefined , , .

n- , . .

K & R , :

  • ( )
  • ( )
  • ( )
  • / 0

.

0

, C. i p i * sizeof(*p), .. i .

, , : - p[i] *(p+i) i[p] ...

+6

+ .

. , a + 1 int, a struct, a struct.

+3

,

int * a; char * b;

Now suppose a is stored at location 10000 and b is stored at location 20,000

So, by performing the following operations

*(a+1) : It will return the value contained in address 10004 i.e. (10000+4)
*(b+1) : It will return the value contained in address 20001 i.e. (20000+1)

Cause:

Adding a pointer is different from regular arithmetic adding. If you add 1 to the integer pointer, it will move the pointer to a location the size of the integer. Thus, in this case, it advances the pointer to 10004. Since the character is only 1 byte long, it advances the pointer 1 byte.

+1
source

a + i translate into something like this in pseudo code

  *(a+i*sizeof(variableType))
0
source

All Articles