kontingent-freieste
kontingent-freieste

Reputation: 11

Simple printf(%s) Code not running as expected

I was reading from a file and writing it into an char* but the chars were not beeing saved after the array[96]. So I decided to run a simple check with this code:

int main(void){
    char array[5];
    memset(array, 0, sizeof(array));
    array[1] = 'A';
    array[2] = '\0';
    printf("\n---%s---\n", array);
    return 0;
}

I would expect ---A--- to be printed into the console, but the A is missing. Am I missing something?

Upvotes: 0

Views: 67

Answers (1)

Seinlin
Seinlin

Reputation: 79

The array index should start from 0. As Jonathan answered in the above comment, no need to set the terminator array[1] = '\0'; since the array already got memset to 0. So the final code snippet will look like.

#include <stdio.h>
#include <string.h>

int main(void){
    char array[5];
    memset(array, 0, sizeof(array));
    array[0] = 'A';
    printf("\n---%s---\n", array);
    return 0;
}

Upvotes: 3

Related Questions