Home > Mobile >  C fill char array with n values leads to problem
C fill char array with n values leads to problem

Time:11-30

I want to give the program an integer value from 1 to 26 (doesn't need to be hardcoded) that creates a char Array that is filled with the letters from A to letter n. This is the code:

int main(int argc, char *argv[])

{
    int n = atoi(argv[1]);
    char comb[n];

    for (int i = 0; i < n; i  )
        comb[i] = 65   i;
    
    printf("%s", comb);
}

The problem is, that if i hand over values from 8 - 15 and 24 - 26, the output shows something like this: ABCDEFGH�������

However, if i hardcode n to be one of the problematic values from above, the output is just right.

Can somebody explain to me, why the program puts out the extra �. Thanks

CodePudding user response:

  1. The standard way to convert a string to a numeric type in C is to use the strto* family of functions. In your case, you would want something like:

    int count = strtol(argv[1], // String
                       NULL, // Optional output pointer to where the scan stopped 
                       10) // Radix
    

    I'd also check that argc > 2, i.e. that argv[1] was actually passed by the user.

  2. %s expects a pointer to a null terminated string. In other words, printf has no way of knowing where the string argument stops until it sees the '\0', so what you're seeing is some other part of your process memory being printed out as text. To fix: allocate n 1 for comb, and memset(comb, n 1, 0); before the loop, or set comb[n] = '\0' right after the loop.

  • Related