Need help to understand code with pointers and arrays in c

Do I need to understand what a commented line does?

#include <stdio.h> void fun(char**); int main() { char *argv[] = {"ab", "cd", "ef", "gh"}; fun(argv); return 0; } void fun(char **p) { char *t; t = (p+= sizeof(int))[-1]; //what this line does? //[-1] does what? printf("%s\n", t); } 
+4
source share
3 answers

Assuming int is 4 bytes on your computer, then replace sizeof(int) with 4:

 t = (p+= 4))[-1]; 

- just move the pointer p 4 of the element and move back 1 element, and then get the element.

In this example, the array has 4 elements, so move forward to one end and move back to the last element, which is "gh" .

A few notes:

  • a[-1] is just *(a - 1) .
  • You need to make sure that when you do pointer arithmetic, they always point to an element in an array or one by one.
  • Also, the name argv not a good idea, since we usually use it to refer to the main parameter.
+4
source

-1 just means that it goes to the previous element:

 x[-1]=*(x-1) 

whole line

 *(x+sizeof(int)-1) 

sizeof (int) is probably 4, so the line is:

 *(x+4-1)=*(x+3)=x[3]="gh" 
+1
source

initally **p contains the address of the argv[0] element, that is, "ab" .it then increases by 2 (the size of the int is given as 2 bytes) . Now he points to "ef" . Then it is decremented to -1 .so, finally, points to "cd" . So it prints the value of t as "cd" .

Note:

Since C is a machine-dependent language of sizeof (int), different values ​​may return.

The output for the above program will be cd on Windows (Turbo C) and gh on Linux (GCC).

To understand this better, compile and run the above program on Windows (with Turbo C compiler) and on Linux (GCC compiler).

0
source

Source: https://habr.com/ru/post/1502274/


All Articles