cstringnull-terminated

When does a char* ends with null in c?


I have confusion on char* null-termination so i have decided to make a study of cases i can find. Do these string literals end with a null?

  1. char str1[512]="This is a random string"
  2. char *str2 = strtok(buffer,"\n,") I have found its answer. This ends with null.
  3. fgets(stdin, str3, 512)
  4. scanf("%s",str4)
  5. The code snippet:
    char str[5];    
    for(int i=0; i<5; i++) scanf("%c",&str[i]);
    

Note 1: I have an assumption that all standard functions in c library that returns a char*, null terminates the string.
Note 2: How do I check if a string is null terminated or not? (I tried this approach but it prints random stuffs imo.)

Edit: Just showing me a way to determine whether a string literal is null-terminated will be enough. I will go through each case and update here for future readers.


Solution

  • Such an example is by no means exhaustive, but it brings some clarity. The answer is actually simple. Any array of characters ending in '\0' is called a string. The programmer independently decides what he needs .

    #include<stdio.h>
    
    int main(void)
    {
        char w[]="mamamia";
        int i;
        for(i=0;i<sizeof(w);i++)
        {
            if(w[i]=='\0')
                printf("w[%d]==null\n",i);
            else
                printf("w[%d]== %c \n",i,w[i]);
        }
        return 0;
    }