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

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.

Jump to Post

All 4 Replies

Re: Modifying a char * and returning it from a function 80 80

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.

Re: Modifying a char * and returning it from a function 80 80

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;
}
Re: Modifying a char * and returning it from a function 80 80

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

Re: Modifying a char * and returning it from a function 80 80

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 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.