Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a char* point to a char[]?

Tags:

c++

c

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?

like image 222
BKS_headphonesman Avatar asked Aug 23 '19 06:08

BKS_headphonesman


People also ask

How is a char * a string?

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 (").

What does char * [] mean in C?

char* means a pointer to a character. In C strings are an array of characters terminated by the null character.

Can a char pointer point to a string?

Instead of using arrays, we can use character pointers to store a string value.


2 Answers

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?

like image 66
jww Avatar answered Sep 29 '22 01:09

jww


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);
}
like image 25
Agnius Vasiliauskas Avatar answered Sep 28 '22 23:09

Agnius Vasiliauskas