0

If I set an array variable a[]="abc" , and then set another array variable b[]={'d','e','f'} ,my last output code is printf("%s",b) ,it's output value is "defabc",why? My output is array b but the output value will output array b first and then output array a second. The whole code is on bellow.

#include<stdio.h>
void main(){
  char a[]="abc";
  char b[]={'d','e','f'};
  printf("%s",b);
}

The output is "defabc". And the string length of array b is 7 why?

4
  • i dont see "defabc" as output. Commented Jan 4, 2017 at 6:45
  • 1
    You don't have a null terminator in b so function reads past buffer and it happens that next on stack is a Commented Jan 4, 2017 at 6:45
  • 1
    @AdityaK That's the joy of undefined behaviour when programmer does something wrong. ;) Commented Jan 4, 2017 at 6:57
  • 1
    You'd need char b[]={'d','e','f', '\0'}; Commented Jan 4, 2017 at 6:58

3 Answers 3

4

In C all strings should be null (i.e. \0) terminated, so your second variable should look like the following:

char b[] = {'d', 'e', 'f', '\0'};

You might be curious why "defabc" is printed with your code. The answer is, all local variables are stored in a stack-based memory layout. So your memory layout looks like this:

|'d' | <-- b
|'e' |
|'f' |
|'a' | <-- a
|'b' |
|'c' |
|'\0'|

Also note that printf("%s", ...) reads until it reach a \0, so printf("%s", a) works as expected but printf("%s", b) prints "defabc".

Sign up to request clarification or add additional context in comments.

4 Comments

I would not mention stack data structure but memory organisation. Data structure is not relevant here
@OlegBogdanov You're right "data structure" is for different purposes!
It means that a="abc" its really value is "abc\0" right?
@Pulsar Yes. "abc" is stored in memory as 4 bytes 'a' 'b' 'c' '\0'.
0

You need a null terminator at the end of both strings. your second string does not have it as its defined as an array of characters.

Comments

0

Correct ways to declare a string

char b[] = { 'd', 'e', 'f', '\0' };    // null terminator required

or

char b[] = "def";    // null terminator added automatically

So, this code will print def as output

#include <stdio.h>

int main() {
    char a[] = "abc";
    char b[] = { 'd', 'e', 'f', '\0' };
    printf("%s", b);
    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.