简体   繁体   中英

fgets() weird behavior with realloc()

int main(void)
{
    int howMany,i,j;
    char* temp = NULL;
    char** friends = NULL;
    printf("Please enter the number of the friends you have\n");
    scanf(" %d",&howMany);
    howMany++;
    friends = (char**) malloc(sizeof(char*)*howMany);
    for (i = 0; i < howMany; i++)
    {
        temp = (char*) malloc(20*sizeof(char));
        fgets(temp,20,stdin);
        temp[strspn(temp, "\n")] = '\0';
        *(friends + i) = (char*)realloc(temp,sizeof(char) * (strlen(temp)+1));
    }

    for (i = 0; i < howMany; i++)
    {
        for ( j = 0; j < strlen(*(friends+i)); j++)
        {
            printf("%c",friends[i][j]);
        }
        printf("\n");
    }
    for (i = 0; i < howMany; i++)
    {
        free(*(friends + i));
    }

    free(friends);
    getchar();  
    return 0;
}

The purpose of my code is to get the amount of friends i have, their names and finally printing it to the screen, any ideas why my code isn't working?

Input: 2 daniel david

Output:

(\\n)

Expected output: daniel david

The main problem is here:

temp[strspn(temp, "\n")] = '\0';

You used the wrong function. You want strcspn , not strspn . Change it to:

temp[strcspn(temp, "\n")] = '\0';

Also, as others pointed out, you should not change the value of howMany , since you need its original value in your loops.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM