String literals with NULL termination

A string literal is a C-string which, by definition, is NULL-terminated. The name comes from the C convention of having null-terminated strings. 

There is no way to have a string literal, not NULL-terminated. But if you have a string that is not null-terminated,  I can say, it is not a stricg at all, and you cannot use the C string manipulation routines on it. You can't use strlen, strcpy or strcat. Basically, any function that takes a char * but no separate length is not usable.


The standard says the string would be NULL-terminated if it can only fit. Otherwise, it would be an overflow. 


An array of character type may be initialized by a character string literal, optionally enclosed in         braces. Successive characters of the character string literal (including the terminating null          character if there is room or if the array is of unknown size) initialize the elements of the array.    


How to scan an array string without declaring its size and print each character of that string using C programming?

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

int main()
{
    char arr[] = "Stunning Palace";
    int index = 0;
    
    //printf("Arr %s and sizeof(arr) %d strlen(arr) %d\n", arr, sizeof(arr), strlen(arr));
    
    for (; index < strlen(arr); index++) {
        printf("%c\n", arr[index]);   
    }

    return 0;
}



Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
S
t
u
n
n
i
n
g
 
P
a
l
a
c
e


Here, the string is NULL-terminated, so we can luxuriously use strlen.  

I have written another interesting problem to find the given string matches exactly the string we have. Click here.



Comments