3

I am trying to print int array with %s. But it is not working. Any ideas why?

#include<stdio.h>
main() {
    int a[8];

    a[0]='a';
    a[1]='r';
    a[2]='i';
    a[3]='g';
    a[4]='a';
    a[5]='t';
    a[6]='o';
    a[7] = '\0';

    printf("%s", a);
}

It prints just a. I tried with short as well, but it also does not work.

1
  • 3
    What happens if you change int a[8] to char a[8]? Whats different about the two? How do you think that difference affects how printf() formats and emits a string to stdout? Commented Sep 4, 2013 at 17:45

4 Answers 4

3

This is because you are trying to print a int array, where each element has a size of 4 byte (4 chars, on 32bit machines at least). printf() interprets it as char array so the first element looks like:
'a' \0 \0 \0
to printf(). As printf() stops at the first \0 it finds, it only prints the 'a'.

Use a char array instead.

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

2 Comments

On some platforms 'a' as an int may be represented like 0x00 0x00 0x00 0x41. So you won't even get a! The first byte will be zero.
I think he's a beginner so I don't wanted to confuse him with endianess, but you are right.
2

Think about the way integers are represented - use a debugger if you must. Looking at the memory you will see plenty of 0 bytes, and %s stops when it reaches a 0 byte.

It prints just a.

That's why it prints just a. Afterwards it encounters a 0 byte and it stops.

2 Comments

okay thanks :). Is there any other way to print int as string. I mean just with printf, without using loops or int to char conversions? For some reasons (beyond my scope) string is in int and not in char.
@sakura If int happens to be of the same length as wchar_t, then you may have some success printing it using wprintf(). Else no, there's no other option than looping over the string.
1

Because you declared a as an integer, so those signle characters you initialized would result in an error. You must change it to a char variable. However to save time, just make the variable a pointer using the asterisk character, which then allows you to make a single string using double quotes.

Comments

0

int a[8] means array of 8 ints or 8*(4 bytes) - Say 32 bit architecture

a[0] = 'a' stores in the first int index as 'a''\0''\0''\0' a[1] = 'r' as 'r''\0''\0''\0' and so on . . .

%s represents any C-style string ie. any string followed by a '\0' character

So

 printf("%s", a);

searches for trailing '\0' character and just prints "a" assuming it is the entire string

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.