Is it possible to make the char* point to the char array?
Yes. Instead of:
int main(){
char *c="Hello";
toup(c);
}
Use:
int main(){
char c[] = "Hello";
toup(c);
}
char *c = "Hello";
makes the string const and usually puts the string in a const data section. char c[] = "Hello";
provides the mutable string you want.
Also see Why is conversion from string constant to 'char*' valid in C but invalid in C++.
Also see Blaze's comment:
for (int x;x<strlen(c);x++)
x is uninitialized. Did you mean int x = 0
?
Two other caveats...
void toup(char* c) {
char array[sizeof(c)];
for (int x;x<strlen(c);x++){
array[x]=toupper(c[x]);
}
}
First, toup
is modifying a local array. It is not visible outside the function.
Second, sizeof(c)
yields either 4 or 8 since it is taking the size of the pointer. That means the declaration is either char array[4];
on 32-bit machines, or char array[8];
on 64-bit machines.
array[x]=toupper(c[x]);
should segfault when the length of string c
is larger then the pointer.
You should probably do something like:
void toup(char* c) {
for (size_t x=0;x<strlen(c);x++){
c[x]=toupper(c[x]);
}
}
A similar question is at How to iterate over a string in C? Also see What is array decaying?