I have tried the following: *string = toupper(*string);
This only made the first char of the string pointer to by the pointer upper case. I want all the chars pointer to by *pointer to be in uppercase. Anyway I can do this?
I have tried the following: *string = toupper(*string);
This only made the first char of the string pointer to by the pointer upper case. I want all the chars pointer to by *pointer to be in uppercase. Anyway I can do this?
You can do this as it is shown below
char s[] = "hello world";
for ( char *p = s; *p; ++p ) *p = toupper( ( unsigned char )*p );
Take into account that you may not change string literals. String literals are immutable. If you write for example in the above code
char *s = "hello world";
instead of
char s[] = "hello world";
then the program behaviour will be undefined.
You need to iterate through every character like this
for (size_t i = 0 ; string[i] != '\0' ; ++i)
string[i] = toupper((unsigned char) string[i]);
The behaviour you are observing is because *
dereferences the pointer, and since you are dereferencing the pointer without incrementing it, you are just setting the first element of the sequence of characters.
The *
operator works on a pointer in the following way: *(pointer + offset)
is equivalent to pointer[offset]
. So *string = toupper(*string)
is equivalent to
string[0] = toupper(string[0]);