-1

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?

John
  • 105
  • 1
  • 8
  • 2
    You've got an approach that works for a single character in the string. Logic would suggest using a loop to apply the same approach to every character in the string. Also, be aware that the argument and return value of `toupper()` is of type `int`, not `char`. – Peter Jan 25 '16 at 23:30
  • C does not have a string type. It is just a sequence of `char`. Iteration statements (aka loops) are explßained in every book/tutorial about programming in general and C in special. – too honest for this site Jan 26 '16 at 13:14

2 Answers2

2

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

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]);
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97