Can anyone explain to me why this simple program won't print anything?

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

char * mkUpperCase(char *);

int main(void)
{
    char name[] = "information";
    printf("%s\n", mkUpperCase(name));
    return 0;
}

char * mkUpperCase(char *s)
{
    while(*s != '\0')
    {
        *s = toupper(*s);
        s++;
    }
    return s;
}

Recommended Answers

All 4 Replies

Because you return s from mkUpperCase which by the time the function has finished running points to the termintor of the string.

If you print name as well as the return from mkUppercase you can see the function actually did it's job.

mkUpperCase should store and return the input pointer.

Thanks. I understand it now. Meaning all I have been returning is the address of the NULL terminator, isn't it?
I have modified the function mkUpperCase as below and it does the job as I expect it to, but I'd like to know if it's safe.

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

char * mkUpperCase(char *);

int main(void)
{
    char name[] = "information";
    printf("%s\n", mkUpperCase(name));
    return 0;
}

char * mkUpperCase(char *s)
{
    char *n = s;
    while(*s != '\0')
    {
        *s = toupper(*s);
        s++;
    }
    return n;
}

use array index and no need to return nothing, just print name afterwards :)
by the way you are not modifying char* and returning from a function, you are modifying the data that pointer points to and returning pointer to that data

It partly depends on what you mean by "safe". You function is heavily reliant on being passed a well formed C string and will cause problems if it is not. However most C string handling functions suffer from this particular issue. You could insist the buffer size is passed along with the pointer to the buffer and ensure that the function does not write outside the bounds of the supplied buffer.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.