Home > database >  In c, when I use %s to print out the contents of a char array it prints blank, but when I loop over
In c, when I use %s to print out the contents of a char array it prints blank, but when I loop over

Time:06-28

Just implementing a simple sorting algorithm to sort a string. I tried printing out the buff char array with printf("%s\n") but it came out blank. The contents of the array are there, though, and I checked with printing out each character of it. What am I missing here?

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char const *argv[])
{   
    if (argc != 2)
    {
        printf("usage: ./sortstring string");
        exit(1);
    }

    int size = 1; // 1 to account for '\0'
    for (int i = 0; argv[1][i] != '\0'; i  )
    {
        size  = 1;
    }
    char buff[size];
    strcpy(buff, argv[1]);

    char temp;
    for (int i = 0; i < size; i  )
    {
        for (int j = i   1; j < size; j  )
        {
            if (tolower(buff[i]) > tolower(buff[j]))
            {
                temp = buff[i];
                buff[i] = buff[j];
                buff[j] = temp;
            }
        }
    }

    // printf("%s\n", buff);
    for (int i = 0; i < size; i  )
    {
        printf("%c", buff[i]);
    }

    return 0;
}

CodePudding user response:

Change "%c" to "%d" in printf and see the result.

    for (int i = 0; i < size; i  )
    {
        printf("%d", buff[i]);
    }

strcpy copies terminating null byte with the source string.
You sorted terminating null byte with other characters.

CodePudding user response:

The problem is that you're initializing size with 1. I know you did that because you need one more char to \0, but after that, either you need to loop through size - 1 or you can decrease the value of size before your for loops.

Another thing you can is: initialize size with 0, and use size 1 while creating your array.

CodePudding user response:

Instead of attempting to manually count characters in "argc[1]", you could just use the "strlen" function. So, instead of

int size = 1; // 1 to account for '\0'
for (int i = 0; argv[1][i] != '\0'; i  )
{
    size  = 1;
}

You could use

int size = strlen(argv[1]);

Regards.

CodePudding user response:

Your sorting function is probably sorting the null character to position 0.

  • Related