benhi
benhi

Reputation: 582

How to change the value of char pointer?

this is my main:

int main(void)
{
    char w1[] = "Paris";
    ChangeTheWord(w1);
    printf("The new word is: %s",w1);
    return0;
}

and i need to change the value of w1[] in this function:

ChangeTheWord(char *Str)
{

     ...

}

Upvotes: 2

Views: 27737

Answers (5)

SomeTonyGuy
SomeTonyGuy

Reputation: 101

you can actually change the value of each index with the pointer notation in a loop. Something like...

int length = strlen(str);              // should give length of the array

for (i = 0; i < length; i++)
    *(str + i) = something;

or you should be able to just hardcode the index

   *(str + 0) = 'x';
   *(str + 1) = 'y';

or use array notation

str[0] = 'x';
str[1] = 'y';

Upvotes: 1

A.s. Bhullar
A.s. Bhullar

Reputation: 2788

int main()
{
    char w1[]="Paris";
    changeWord(w1);      // this means address of w1[0] i.e &w[0]
    printf("The new word is %s",w1);
    return 0;

}
void changeWord(char *str) 
{
    str[0]='D';         //here str have same address as w1 so whatever you did with str will be refected in main(). 
    str[1]='e';
    str[2]='l';
    str[3]='h';
    str[4]='i';
}

Read this answer too

Upvotes: 4

glglgl
glglgl

Reputation: 91049

All answers so far are correct, but IMO incomplete.

When dealing with strings in C, it is important to avoid buffer overflows.

Your program crashes (or at least shows undefined behaviour) if ChangeTheWord() tries to change the word to a too long one.

Better do this:

#include <stdio.h>
#include <stddef.h>

void ChangeTheWord(char *str, size_t maxlen)
{
    strncpy(str, "A too long word", maxlen-1);
    str[maxlen] = '\0';
}

int main(void)
{
    char w1[] = "Paris";
    ChangeTheWord(w1, sizeof w1);
    printf("The new word is: %s",w1);
    return 0;
}

With this solution, the function is told which size of memory it is allowed to access.

Be aware that strncpy() doesn't work as one would suspect at the first glance: if the string is too long, no NUL-byte is written. So you have to take care by yourself.

Upvotes: 10

rakib_
rakib_

Reputation: 142655

This is how you can do it.

ChangeTheWord(char *Str)
{
        // changes the first character with 'x'
        *str = 'x';

}

Upvotes: 2

HadeS
HadeS

Reputation: 2038

You can simply access each index and replace with desired value.. Made one change for example...

void ChangeTheWord(char *w1)
{
     w1[0] = 'w';
     //....... Other code as required
}

Now when you try to print the string in main() Output will be Waris.

Upvotes: 2

Related Questions