maekchi
maekchi

Reputation: 55

Why no error shown this code in C?

I don't know why this code don't show error. Let me know this why.

char str[10][5];

scanf("%s",&str[1]);
printf("%s",str[1]);

I think this must show error but this show only warning and normally execute. Please tell me why this normally execute.

Upvotes: 0

Views: 113

Answers (4)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

The value of expression

&str[1]

is equal to the value of expression

str[1]

That is the both address the same memory extent.

So you get the correct result because scanf and printf process the value according to the format specifier %s That is scanf stores characters at this memory extent appending them with terminating zero and printf outputs the characters from the same memory extent until it encounters the terminating zero. And the both expressions aboth supply the same address.

Upvotes: 2

Peter - Reinstate Monica
Peter - Reinstate Monica

Reputation: 16016

As discussed a few times before, the address of an array has the same numerical value as the address of its first element (which the array will decay to when passed to a function). That is, str[1] which is an array of char will decay to a pointer to char containing the same address as &str[1], which is the address of that array. And, believe it or not, the array starts with its first element so that both share the same address.

So both pointers point to some memory location inside str, that is, to valid addresses; they are typed just differently. C's weak type system tolerates the type differences. scanf will just assume from the format specifier %s that you passed a char pointer. Since the memory there is good (it's s[1] after all) you can scan into it.

Yes, it's UB but works on every platform available to mere mortals.

Upvotes: 5

2501
2501

Reputation: 25752

The values of str[1] and &str[1] are the same. But their types are not, the types are char* and char(*)[5] respectively.

The required type for %s is char*, if you pass an incompatible type, as you do, you get undefined behavior. Now since the value is the same, the program will work, but the code itself is not correct.

Upvotes: 4

scanf and printf are functions that got variadic arguments. It means that you can pass any quantity of any arguments in it. Any faults followed by misuse of such a functions lead to undefined behaviour and therefore such functions considered unsafe.

Upvotes: 0

Related Questions