1

In this array ,the given array is of size 5,but it is not taking more than 3 elements, Why?

#include<stdio.h>
int main()
{
    char a[10],*q;
    int i;
    q=a;
    for(i=0;i<5;i++) {
        scanf("%c",a+i);//a[5]={a,b,c}
    }
    for(int i=0;i<5;i++) {
        printf("%c",*(a+i));
    }
    printf("\n%d",sizeof(a));
    printf("\n%d",sizeof(q));
}
paulsm4
  • 114,292
  • 17
  • 138
  • 190
prve17
  • 61
  • 3
  • 2
    You're probably pressing ENTER which adds a `'\n'` to `a`. Are you doing something like: `a`, ENTER, `b`, ENTER, `c`, ENTER? Try typing: `a`, `b`, `c`, `d`, `e`, ENTER. – Fiddling Bits Mar 14 '21 at 01:51
  • 1
    Your array size is 10 (not 5) - your 1st printf should show this. If you typed "ABCDEFG", your array will show "ABCDE" (exactly 5 characters). If you typed a newline after each character ... you'll get 3 characters ... and 2 newlines :) – paulsm4 Mar 14 '21 at 02:03
  • 1
    and `sizeof` result [must be printed using `%zu`](https://stackoverflow.com/q/940087/995714) or you'll get undefined behavior – phuclv Mar 14 '21 at 06:54
  • @phuclv It prints the samething. Can you please explain ,which type of undefined behaviour it will show. – prve17 Mar 15 '21 at 04:51
  • 1
    @prve17 UB means anything can happen. If you're lucky then it works. But in other cases like on some 64-bit platforms if the parameters were passed on stack then maybe only 4 bytes were popped out of the stack and ruin the whole program [What happens when I use the wrong format specifier?](https://stackoverflow.com/q/16864552/995714) – phuclv Mar 15 '21 at 05:37

0 Answers0