Pulsar
Pulsar

Reputation: 29

An array output

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?

Upvotes: 0

Views: 44

Answers (3)

frogatto
frogatto

Reputation: 29285

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".

Upvotes: 4

Shreevardhan
Shreevardhan

Reputation: 12641

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;
}

Upvotes: 0

Sayu Sekhar
Sayu Sekhar

Reputation: 169

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.

Upvotes: 0

Related Questions