Question about pointers

Hi i got a function that looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main(void){
char * string;
char * string2;

                        string=test(1);
            printf("%s\n",string);
            string2=test(2);
            printf("%s\n",string);


}

char * test(int i){
    char * string;
    if(i==1)
        string="test1";
    else
        string="test2";


    return string;
}

The output is:
test1
test2
instead of: (what i want to have)
test1
test1

How can I solve this problem?
(I already tryed strcpy() but that didn't work either)

Thanks in advance,
Castelmagno
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*.
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
@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
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
Topic archived. No new replies allowed.