Feb 29, 2012 at 4:19pm UTC
It prints
test1
test1
for me.
Post your entire code, what you've posted above shouldn't actually compile since test isn't declared before main. You should also look into using strings instead of char*.
Feb 29, 2012 at 4:30pm UTC
In the code
1 2 3 4
string=test(1);
printf("%s\n" ,string);
string2=test(2);
printf("%s\n" ,string);
you
two times print the same variable
string . In the second statement
printf("%s\n",string);
you shall change string to
string2
Also it is better to define your function test as
1 2 3 4 5 6 7 8 9 10 11 12
const char * test( int i )
{
const char * string;
if ( i==1 )
string = "test1" ;
else
string="test2" ;
return string;
}
because you assign to pointers addresses of string literals which are not allowed to change.
Last edited on Feb 29, 2012 at 4:33pm UTC
Feb 29, 2012 at 5:04pm UTC
@vlad.
He means to use print string twice, changing the second one to string2 will give the result he does not want. He wants to print
test1
test1
i.e. string twice. Somehow his function is assigning the value of string 2 to string though which is why he's getting
test1
test2
which is what he does NOT want.
Last edited on Feb 29, 2012 at 5:04pm UTC
Feb 29, 2012 at 7:35pm UTC
I think it had something to do with a filepointer in my function.
I made a workaround so i solved it. :)
Thanks for the help.
Last edited on Feb 29, 2012 at 7:35pm UTC