1

I want to change the value of character array, when I am using like this

char *str;
fun(str);

void fun(char *str) {
    str = (char *) ("changed");
}

It is not doing anything and having str as null

whereas in this manner

char *str;
fun(&str);

void fun(char **str) {
    *str = (char **) ("changed");
}

It is coming fine. But I have a restriction to have the function definition as void fun(char *str), how to change the value using this usecase

1
  • *str = (char **) ("changed"); is wrong, don't cast a char * with (char **), the first snippet is also wrong, you are changing the value of a local variable. how to change the value using this usecase: Using strcpy: void fun(char *str) { strcpy(str, "changed); } . str must point to allocated space (an array or via malloc) with space enough to store "changed" Commented Oct 2, 2020 at 16:29

2 Answers 2

2

I want to change the value of character array

With fun(char *str), str is a pointer. To change the value of the character array, do not change the pointer str. Change the contents of the memory str points to.

void fun(char *str) {
    // str = (char *) ("changed");
    str[0] = 'c';
    str[1] = 'h';
    str[2] = 'a';
    str[3] = 'n';
    str[4] = 'g';
    str[5] = 'e';
    str[6] = 'd';
    str[7] = '\0';
    // or simply 
    strcpy(str, "changed");
}

Be sure when calling that the pointer references available space

char buffer[100] = "Before";
printf("<%s>\n", buffer);
fun(buffer);
printf("<%s>\n", buffer);
Sign up to request clarification or add additional context in comments.

Comments

0

The usual use case is that you have an array that you pass to the function. Under most circumstances, an expression of array type will be converted (or "decay") to an expression of pointer type, and the value of the pointer will be the address of the first element of the array. Example:

#define SOME_SIZE 20   // Size of the longest string you intend to store; 20 is just an example

void fun( char *str )
{
  strncpy( str, "changed", SOME_SIZE );
  str[SOME_SIZE] = 0; // make sure string is terminated if SOME_SIZE <= strlen("changed")        
}

int main( void )
{
  char buf[SOME_SIZE+1] = "foo"; // +1 for 0 terminator
  printf( "buf before fun - %s\n", str );
  fun( buf );
  printf( "buf after fun - %s\n", str );
  return EXIT_SUCCESS;
}

You're not changing the value of str itself, you're changing the contents of the buffer that str points to.

1 Comment

Concerning strings like "changed", I find length as 7 and size as 8 clear. Using SOME_SIZE as the maximum length of a string in buf[] not so clear. Perhasp SOME_LENGTH?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.