I was wondering if there is a way to make char*
point to the contents of a char
array so that I can modify the char*
across functions.
For example
void toup(char* c) {
char array[sizeof(c)];
for (int x;x<strlen(c);x++){
array[x]=toupper(c[x]);
}
}
int main(){
char *c="Hello";
toup(c);
}
Trying to make the array = char*
does not seem to work. Is it possible to make the char* point to the char array?
char represents a single character whereas String can have zero or more characters. So String is an array of chars. We define char in java program using single quote (') whereas we can define String in Java using double quotes (").
char* means a pointer to a character. In C strings are an array of characters terminated by the null character.
Instead of using arrays, we can use character pointers to store a string value.
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 intx = 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?
No need for temporary buffer array
- you already have stream of characters in input.
#include <stdio.h>
#include <ctype.h>
void toup(char* c) {
for (char * it = c; *it !='\0'; it++){
*it = toupper(*it);
}
}
int main(){
char c[] = "Hello";
toup(c);
printf("%s\n",c);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With