PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 5, 2022

[FIXED] How can I change the value of a char using a pointer?

 July 05, 2022     c, c-strings, function, pass-by-reference, pointers     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing