How does program C generate this output?

void main()
{
    char str[2][7] = {"1234567", "abcdefg"};
    char** p = str;
    printf("%d\n", *(p+1));
    printf("%c\n", *(p+1));
}

Output:

1631008309
5

Edit: Thank you. I see that "5" is only 0x35, except str [0] [4] I should have been. Why can't I exit [0] [4] instead of this weird 1631008309 ??

OMG, I'm stupid enough to ask this question! Thanks to everyone guys.

+3
source share
5 answers

You specify char ** at the beginning of the memory allocated to your 2-dimensional array.

1 , , sizeof a char *, , -, 4 . int (% d), a765, , . char, 5.

[ , , , "a765" - ASCII , (0x61373635).]

+10

:

char** p = str;

. str - 2 7 . , :

&str[0]

" 7 ". " char", p. :

char *p = str[0];

char *p = str[1];

char (*p)[7] = str;
+5

% d - ASCII . % d , , TO ASCII . ​​

+5

, C , main() int, void.

:

#include <stdio.h>
int main()
{
    char str[2][7] = {"1234567", "abcdefg"};
    char** p = str;
    printf("%d\n", *(p+1));
    printf("%c\n", *(p+1));
    return(0);
}

gcc -o x -Wall x.c :

x.c: In functionmain’:
x.c:5: warning: initialization from incompatible pointer type
x.c:6: warning: format ‘%dexpects typeint’, but argument 2 has typechar *’
x.c:7: warning: format ‘%cexpects typeint’, but argument 2 has typechar *’

( -Wall, .)

, printf(). . , p. , p str.

: , "1234567", NUL '\0'; , , 7, 8, . , !

:

#include <stdio.h>
int main()
{
    char str[2][7] = {"1234567", "abcdefg"};
    char** p = str;
    printf("%d\n", *(p+1));
    printf("%c\n", *(p+1));
    printf("%p %p %p -- %p %p %p\n", str, &str[0], &str[0][0], p, p+1, *(p+1));
    printf("%.4s\n", (p+1));
    return(0);
}

( Mac):

1631008309
5
0xbffffa5e 0xbffffa5e 0xbffffa5e -- 0xbffffa5e 0xbffffa62 0x61373635
567a

, str, & str [0] & str [0] [0] p+1 . , .

, fun, gcc -m64 -o x64 x.c, :

1701077858
b
0x7fff5fbff9e0 0x7fff5fbff9e0 0x7fff5fbff9e0 -- 0x7fff5fbff9e0 0x7fff5fbff9e8 0x676665646362
bcde
+3

, .

* (p + 1) , , va_arg.

printf char, printf.

, :

void main()
{
  char str[2][7] = {"1234567", "abcdefg"};
  char** p = str;
  printf("%d\n", *(p+1));
  printf("%c\n", *(p+1));
  int n = *(p+1);
  char c = *(p+1);
  printf("0x%08X\n", n);
  printf("0x%08X\n", c);
}

:

1631008309
5
0x61373635
0x00000035

This describes security like stdarg: stdarg

+1
source

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


All Articles