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?
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);
}
Your toup
function has problems:
char array[sizeof(c)]
here sizeof(c)
is the size of a pointer, not the string. int x
is not initialized in the for loop. x < strlen(c)
is very very very inefficient. You are calculating the length every iteration and strlen
is an expensive function. And in the main function, char *c="Hello";
is not valid C++. You meant char c[] = "Hello"
Here's is one way to do this:
#include <iostream>
#include <algorithm>
#include <cctype>
int main() {
char str[] = "Hello World";
std::for_each(std::begin(str), std::end(str),
[](char& c) { c = std::toupper((unsigned char)c); });
std::cout << str << '\n';
}
To get a pointer to a char array:
char *ptr = array;
To then use values from it (ie printf)
printf(“%c\n”,*(ptr + i));
make sure to dereference ptr by using *
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.