Why is this simple program in C crashing (VS VS pointer)

I have two files:

In file 1.c I have the following array:

char p[] = "abcdefg";

In the 0.c file, I have the following code:

#include <stdio.h>

extern char *p; /* declared as 'char p[] = "abcdefg";' in 1.c file */

int main()
{
    printf("%c\n", p[3]);   /* crash */
    return 0;
}

And this is the command line:

gcc  -Wall -Wextra     0.c  1.c

I know what extern char *pit was supposed to be: extern char p[];but I just need to explain why it does not work in this particular case . Although it works here:

int main()
{
    char a[] = "abcdefg";
    char *p = a;

    printf("%c\n", p[3]);   /* d */
    return 0;
}
+4
source share
3 answers

Your two examples are not comparable.

In your second example, you have

char a[] = "abcdefg";
char *p = a;

So ais an array, and pis a pointer. Drawing it in photos, it looks like

      +---+---+---+---+---+---+---+---+
   a: | a | b | c | d | e | f | g | \0|
      +---+---+---+---+---+---+---+---+
        ^
        |
   +----|----+
p: |    *    |
   +---------+

And all is well; no problem with this code.

1.c p:

   +---+---+---+---+---+---+---+---+
p: | a | b | c | d | e | f | g | \0|
   +---+---+---+---+---+---+---+---+

"p", ( ), , 0.c, , p . ( <extern "), p - . , location p, - , , - . , , "abcdefg", . , 0x61 0x62 0x63 0x64 ( , "abcdefg") . , .

, printf 0.c

printf("%p\n", p);

p . (, , p , , , , , .)

0x67666564636261

8 "abcdefg\0", . ( , , () 64- , (b) .) ,

printf("%c\n", p[3]);

0x67666564636264 (.. 0x67666564636261 + 3) . , , location 0x67666564636264 , , .

.

, ,

char *p = a;

, , , " , "? ? - ( ?) " C": ,

char *p = &a[0];

, , , , , .

: " , ?", , . ,

void print_char_pointer(char *p)
{
    printf("%s\n", p);
}

void print_char_array(char a[])
{
    printf("%s\n", a);
}

, ,

char a[] = "abcdefg";
char *p = a;

,

print_char_pointer(a);

print_char_array(p);

, , . ? , , print_char_pointer(a)? , , print_char_array(p)?

, , , , , , .

print_char_pointer(a);

, , ,

print_char_pointer(&a[0]);

, , , .

, , , ? , " C".

void print_char_array(char a[])

,

void print_char_array(char *a)

? , , , - , , . , .

(, , "" C ", , , . . , : (1) , , get . (2) , , , , , , , . (3) , "", [], , p[i], , , , *(p + i). , , , - tenet (1), - , . , , , .)

+13

. " char", - .

, , . . ?.

, , , .

+4

:

, , .

( " , " ", " ).

- , , . , . - , " " ( , ). , undefined ( UB).

+4

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


All Articles