-2

I am trying to create a function that accepts a string and converts all lowercase letters to uppercase and everything else into zeros then prints the string. Here is what I have:

void upperAndZeros(char* toUpper) {
    char *toReturn[(sizeof(toUpper) / sizeof(*toUpper)) + 1];
    int i;
    for (i = 0; toUpper[i] != '\0'; i++) {
        if (toUpper[i] >= 'a' && toUpper[i] <= 'z') {
            toReturn[i] = (char) toupper(toUpper[i]); //this is line 127 in the code
        } else {
            toReturn[i] = (char) 0;
        }
    }
    toReturn[i] = '\0';
    printf("The modified string is '%s'", toReturn);
}

But when I go to compile this I get the following error:

127:25 warning: assignment makes pointer from integer without a cast
Haris
  • 12,120
  • 6
  • 43
  • 70
Ulsting
  • 491
  • 2
  • 6
  • 17

2 Answers2

3

The error you are getting is because you are trying to char in a char * array here

toReturn[i] = (char) toupper(toUpper[i]);

You want an array of char not char *. Change this line

char *toReturn[(sizeof(toUpper) / sizeof(*toUpper)) + 1];

to

char toReturn[(sizeof(toUpper) / sizeof(*toUpper)) + 1];

Another change that you should do, which was suggested in the comment is, sizeof() won't work here, as an array decays into a pointer when passed onto a function. sizeof(toUpper) would return the size of a pointer. Read this to understand the problem.

Use strlen() here, if the string pointed by toUpper is NUL terminated.

If not then send the length separately to the function as another parameter.

Community
  • 1
  • 1
Haris
  • 12,120
  • 6
  • 43
  • 70
  • 2
    `sizeof()` is a non-sense here! You need `strlen`! – Jean-Baptiste Yunès Feb 20 '16 at 16:13
  • 2
    In fact, you need `strlen(toUpper) + 1`, as @Jean-BaptisteYunès points out. Also, the `0` needs to be `'0'`; otherwise, the output will stop at the first character that isn't lower-case alpha in the input (something [ProWi](https://stackoverflow.com/users/2328163/prowi) pointed out in a now deleted answer). – Jonathan Leffler Feb 20 '16 at 16:14
0

Lots of problems, something like this should work better:

void upperAndZeros(char* toUpper) {
    char toReturn[strlen(toUpper) + 1];
    int i;
    for (i = 0; toUpper[i] != '\0'; i++) {
        if (islower(toUpper[i])) {
            toReturn[i] = (char) toupper(toUpper[i]);
        } else {
            toReturn[i] = '0'; // beware not 0 but char '0'
        }
    }
    toReturn[i] = '\0';
    printf("The modified string is '%s'", toReturn);
}
Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69