Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Copying valid strings to 2d array in C

I am checking if a function returns true, it prints out valid strings according some other function I got. At the moment, it’s printing it out correctly but it is also printing empty lines which seem to correspond to the invalid strings.

How can I make these empty lines go away?

Here is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int main()
{
    int i, count = 0;
    char input[10];
    char validStr[10][60] = {""};
    for (i = 0; i < 60; ++i){
        if(fgets(input,10, stdin) == NULL){
            break;
        }
        input[strcspn(input,"\n")] = '\0';
        if(checkIfValid(input)){
            memcpy(validStr[i],input,sizeof(input));
            count++;
        }
    }
    printf("%d\n",count);
    for (int j = 0 ; j < count; ++j){
        printf("%s\n",validStr[j]); 
    }
}

The count indicates it is printing only the valid strings but as you can tell by the pic it prints white lines.

enter image description here

Note: For various reasons the program needs to follow the current order so the output is printed after the first for loop.

Thanks in advance!

>Solution :

Instead of this:

    if(checkIfValid(input)){
        memcpy(validStr[i],input,sizeof(input));
        count++;
    }

This:

    if(checkIfValid(input)){
        memcpy(validStr[count],input,sizeof(input));
        count++;
    }

As others have pointed out in the comments, you want to safely secure that string copy. May I suggest:

    if(checkIfValid(input)){
        char* dst = validStr[count];
        size_t MAXLEN = 10;
        strncpy(dst, input, MAXLEN);
        dest[MAXLEN-1] = '\0';
        count++;
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading