Strings : Why is this program not printing the first element?

Aadit Kapoor

Aadit Kapoor

@aadit-kapoor-EBxnXT Oct 27, 2024
Why is this program not printing the first element?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char names[][5] = {
        "aadit",
        "jobs",
        "mark",
    };



    printf("%s\n",names[0]);
    getch();
}

when I printf(%s",names[0]) it shows aaditjobs.

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • [Prototype]

    [Prototype]

    @prototype-G9Gn5k Mar 18, 2014

    The first name you specified actually requires 6 byte of space. So what's effectively happening is, at the run time, aadit took 5 byte with \0 not coming into picture because it's beyond the memory being held by the array. This made the program to think the string has not yet finished and making it jump to the next memory location pointing to jobs\0. This time, since jobs is only 4 bytes it finds the 5th byte as terminating char thus finishing the print.

    If you make jobs as jobss, it'll move forward to print mark as well.
  • Aadit Kapoor

    Aadit Kapoor

    @aadit-kapoor-EBxnXT Mar 18, 2014

    Thank you!