Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printing int array as string

Tags:

c

string

printf

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.

like image 287
sakura Avatar asked Jan 27 '26 22:01

sakura


1 Answers

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.

like image 96
robin.koch Avatar answered Jan 29 '26 11:01

robin.koch