-2
#include <stdio.h>

int main()
{
    char as[4];
        *as='0';
    *(as+1)='1';
   *(as+2)='2';
   *(as+3)='3';
    printf("%s",as);
    return 0;
}

The output i got is : 0123.

In the above program i declared an array of size 4 -> char as[4]; and in that i stored 4 chars 0,1,2,3.

Normally if we declare a char array, '\0' will be stored at last (i.e. as[3]='\0'); but i stored '3' in it. how it did not generate error?.

  • 3
    C compilers do not check used indices of an array. Your program has undefined behavior. – Vlad from Moscow Oct 08 '21 at 05:58
  • The `printf` function *will* go out of bounds of your array in search of the terminator for the string. You're just lucky (or unlucky in some peoples views) that nothing bad happens. – Some programmer dude Oct 08 '21 at 06:01
  • 3
    On another note, why use pointer arithmetic instead of plain array indexing? As in `as[0] = '0';` etc.? They are *exactly* equal. – Some programmer dude Oct 08 '21 at 06:01
  • *strings* are not really part of the language. We humans call *strings* to char arrays which include a `'\0'` terminator (or to pointers to such). Using a char array without a zero-terminator with functions that expect a zero terminated array (a string) invokes **UB** (Undefined Behaviour). – pmg Oct 08 '21 at 06:04
  • 2
    in C it is up to you to follow the rules of the language – M.M Oct 08 '21 at 06:14
  • 2
    See https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior/4105123#4105123 – Chris Dodd Oct 08 '21 at 06:29
  • 1
    BTW: "string without null terminator" is a misnomer, *like "cake without sugar"*. The null terminator is exactly what makes a char array a string!! – pmg Oct 08 '21 at 06:32
  • char array without null terminator is not a C string :). Use of such a char array as a parameter of any function requiring C string involves **U**ndefined **B**ehavoiur – 0___________ Oct 08 '21 at 07:04
  • @pmg Technically you can have a char string without NUL terminator (it would not be a C string, but still a valid string) and store the length in a separate variable. But nobody does it because then you could not use *any* of the libc functions (nor any C function that expects a valid C string). After all, who wants a cake without sugar? Nobody, but you can still cook it. Plus: non-NUL terminated strings are useful when you have `\0` bytes inside the string itself, although rare. – Luca Polito Oct 08 '21 at 08:16
  • You were lucky to have no error – Ptit Xav Oct 08 '21 at 10:32

1 Answers1

0

There is absolutely nothing stopping you from using an array of char as an array of char. There could be any number of reasons to want this.

However, C strings are null-terminated by definition. Using the %s specifier in printf tells it to expect a null-terminated string, so your program will (probably) not work correctly unless you give it such a string.

Chris
  • 26,361
  • 5
  • 21
  • 42