Issue
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\n",b);
return 0;
}
int number(int a, int *b) {
*b = a;
}
Solution
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>.
Answered By - Vlad from Moscow Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.