vendredi 30 mars 2018

copying a char array with and without a pointer

can someone help me here. I am experimenting on copying a string using char array (in the first case) and using a pointer(in the second case) I understand why I need a temp[i]='\0' immediately after the while loop in the first case but I dont understand why I dont need it after the while loop in second case.

               1st case:
char source[50] = "Hello World";
char temp[50];
int i = 0;

    while (source[i] != '\0')
    {
        temp[i] = source[i];
        i++;
    }
    temp[i]='\0';
    cout << temp;

                  2nd Case:

char source[50] = "Hello World";
char *temp=source;
int i = 0;

while (source[i] != '\0')
{
    temp[i] = source[i];
    i++;
 }
cout << temp;

Aucun commentaire:

Enregistrer un commentaire