1

I've written the following code and I don't understand how does it work.

#include "stdio.h"

typedef struct {
    char s[100];
} MyStruct;

void teste(MyStruct *mS) {
    scanf("%s", mS->s);
    printf("%s\n", mS->s);

    scanf("%s", &(mS->s));
    printf("%s\n", mS->s);

    printf("%p\n", mS->s);
    printf("%p\n", &(mS->s));
}

int main(void) {
    MyStruct a;
    teste(&a);
    return(0);
}

When compiling, I get the (expected) warning that:

gut.c: In function ‘teste’:
gut.c:11:8: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[100]’ [-Wformat=]
    scanf("%s", &(mS->s));

However, when I run the code, mS->s and &(mS->s) behave as they're equal!

aaa
aaa
bbb
bbb
0x7ffc0fab39c0
0x7ffc0fab39c0

And both the pointer and it's dereferenced version are actually equal! How does this happen? Is this undefined behavior? I'm using GCC 5.3.1, with the only flag being -Wall.

Thanks a lot in advance!

phckopper
  • 32
  • 5

0 Answers0