Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
80 views
in Technique[技术] by (71.8m points)

c - How can I change the value of a char using a pointer?

So I am quite new to using pointers and wanted to know how I could do the following but for a string value.

int number(int, int *);
int main()
{
    int a = 15;
    int b =0;
    
    number(a,&b);
    
    fprintf(stdout,"Number b is %d
",b);
    return 0;
}


int number(int a, int *b) {
    
    *b = a;
     
}
question from:https://stackoverflow.com/questions/65830426/how-can-i-change-the-value-of-a-char-using-a-pointer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It seems you mean something like the following

#include <stdio.h>

char * assign( char **s1, char *s2 )
{
    return *s1 = s2;
}

int main(void) 
{
    char *s1 = "Hello World!";
    char *s2;
    
    puts( assign( &s2, s1 ) );
    
    return 0;
}

The program output is

Hello World!

That is to assign a value to the pointer s2 (that has the type char *) within the function you need to pass it to the function by reference as you are doing in your program with an object of the type int. Otherwise the function will deal with a copy of its argument and changes the copy will not influence on the argument.

Passing an object by reference in C means passing an object indirectly through a pointer to it.

If you have character arrays that store strings then to copy a string to a character array you can use the standard string function strcpy declared in the header <string.h>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...