dimanche 15 décembre 2019

Value of pointer empty/null inside if statement where value is checked to be non-null beforehand [closed]

In this code:

void change_dir(char* split[], int sz)
{
    if (split[1] != NULL)
    {
        int length = (int) strlen(split[1]);
        char *finder = strchr(split[1], '\\');
        int index = (int) (finder - split[1]) + 1;

        if (index == length && split[2] != NULL)
        {
            char *directory = split[1];

            for (int i = 2; i < sz; i++)
            {
                char* next = split[i];
                strcat(directory, " ");
                strcat(directory, next);
            }

            if (chdir(directory) == -1)
            {
                printf("-shell: %s: %s: No such file or directory \n", split[0], directory);
            }
        }
        else
        {
            if (chdir(split[1]) == -1)
            {
                printf("-shell: %s: %s: No such file or directory \n", split[0], split[1]);
            }
        }
    }
}

I find that the value for split[i] (even when confirming that split[2] has a value that's not "" before entering the if statement) has the value "" as opposed to the value it stored prior to entering the if statement. Why is this? As it means the program breaks at the second strcat().

Aucun commentaire:

Enregistrer un commentaire