Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print an array of char, but the ending is not expected

I don't understand why there are random char after abc. what is the reason? How to print out only abc? Thanks!

#include <stdio.h>

int main()
{
    char arr[3];   
    char(*ptr)[3]; // declare a pointer to an array

    arr[0] = 'a';
    arr[1] = 'b';
    arr[2] = 'c'; 

    ptr = &arr; 
    printf("%s\n", arr);
    //printf("%s\n", ptr);
    return 0;
}

enter image description here

like image 938
ulyssis2 Avatar asked Sep 03 '25 14:09

ulyssis2


2 Answers

The string need to be terminated with a \0. Make sure to allocate enough space to store the terminator as well.

#include <stdio.h>

int main()
{
    char arr[4];   
    char(*ptr)[4]; // declare a pointer to an array

    arr[0] = 'a';
    arr[1] = 'b';
    arr[2] = 'c'; 
    arr[3] = '\0'; // <-- terminator

    ptr = &arr; 
    printf("%s\n", arr);
    //printf("%s\n", ptr);
    return 0;
}

Note that using char arr[4] you will have random content in your array. If instead you would use

char arr[4] = "abc";

This will lead to

char arr[4] = {'a', 'b', 'c', 0};

See how the other places are filled with a 0 so you don't have to set it yourself.

like image 166
mschuurmans Avatar answered Sep 05 '25 02:09

mschuurmans


The reason of the random characters is that you are trying to output the array as a string using the conversion specifier %s.

But the character array arr does not contain a string (a sequence of characters terminated by the zero character '\0').

So to output it using the function printf you can do for example the following way:

printf( "%*.*s\n", 3, 3, arr );

From the C Standard (7.21.6.1 The fprintf function)

4 Each conversion specification is introduced by the character %. After the %, the following appear in sequence:

— An optional precision that gives ... the maximum number of bytes to be written for s conversions.

like image 40
Vlad from Moscow Avatar answered Sep 05 '25 03:09

Vlad from Moscow