Saturday, May 9, 2009

Parse string by reference in C?

I want to know how to parse a string by reference to a function.


For example


void func( char* thefunc);





char * test ="thestr";


func( test )


{


//modify test by reference


}





so how to modify the string test without having to put a return in the function "func"??

Parse string by reference in C?
Like this:





#include %26lt;stdio.h%26gt;





void swapnum(int *i, int *j) {


int temp = i;


i = j;


j = temp;


}





int main(void) {


int a = 10;


int b = 20;





/* Pass by reference */


swapnum(%26amp;a, %26amp;b);


printf("A is %d and B is %d\n", a, b);


return 0;


}
Reply:When you use a string 'by reference' it means you don't pass a copy of the string to the function, instead you pass an address where the string is, and the function accesses it wherever it is.





In this case you passing a pointer to the first character of the string. The function can read the string character by character (test, test+1, test+2, etc.), until it reaches a zero, then it knows that's the end.





Since the function accesses the string where it is, instead of a copy of the string, it doesn't have to return anything. When it's done, the string is changed, but still in the same place (test).
Reply:See http://c-faq.com/aryptr/aryptrequiv.html . C strings are just character arrays. In C, you can --never-- pass arrays by value. They will always be by reference. You don't have to return anything. If you modify the string in your function, it will be modified permanently.





Just a caveat. Even though in your function the C string has pointer semantics, do not originally create the string by directly pointing to a literal. You need to either allocate memory for an array (either by directly creating it on the stack or pointing a dynamically allocated array), and then pass that to the function.
Reply:Here is an example code you want in func.


func( test )


{


//modify test by reference


*(test+0)='a';


*(test+1)='b';


*(test+2)='c';


}


this will change the acutal string.test.


so in the after calling func(test) from main, print the string. You will have the requried change (i.e) it will print abcstr instead of thestr.





You can write any code instead of replacing the first 3 charecters with 'a','b','c'.





--------------------------------------...

hamper

No comments:

Post a Comment