0

if we use

char a[10];
for(int i=0;i<9;i++)
{
    a[i]=GetChar();
    printf("%c",a[i]);
}

While assigning every char to a char array, should we always leave the last byte in char array for '\0' or if we use all the characters in the array will an additional byte be added to array for '\0' in the stack memory?

0

If you declare a as a 10 byte char array, the system allocates 10 bytes. Full stop. "It" has no idea what how you intend to use it. The compiler is very literal that way. If you intend to build a char array and use it as a string, you need to allocate the space for the terminating null-byte and terminate it. Otherwise it is a memory leak and you will get unpredictable results. If it will simply be a char array, not used as a string, then no allocation for the null byte is required. (NB something as simple as a printf with a "%s" format "uses it as a string"). If you want to "see" unpredictable results in action, try this program:

#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>

int main(void)
{
    string atoz = "abcdefghijklmnopqrstuvwxyz";
    char a[10];
    for (int i = 0; i < 10; i++)
    {
        a[i] = atoz[i];
    }
    printf("%s<-\n",a);
}

Then switch the two declaration lines like this:

char a[10];
string atoz = "abcdefghijklmnopqrstuvwxyz";

and compile/run it again. It will give a different result (at least it did when I tried it!)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .