简体   繁体   中英

String prints out junk when pass to function pointer and then back in c

Hi all i am a beginner and am new to pointers and need some help here with string. after it is pass into function pointer, it prints out junk after computation in my main program. Thanks in advance.

int main() {

char str[3][10];
char firstm[10], secondm[10];
int i;

printf("Enter three string");
//get 3 strings from user

func1(&firstm, &secondm, str)
// prints junk
}

void func1(char *first, char *second, char arr[][10])
{
    ...computation here
    ...
    ...

    first = arr[0];
    last = arr[3];
    // prints out the string correctly

}

The problem is that you are assigning to the first and last pointers. Remember that in C all arguments are passed by value , which means that arguments are copied. And changing a copy will not change the original.

What you should do is copy to the strings instead:

strcpy(first, arr[0]);
strcpy(last, arr[2]);

Another thing to note is that you pass an array with three entries in as argument to your function, but use the fifth entry ( arr[4] ). This will of course not work as there is not fifth (or fourth) entry in that array.

And some nitpicking: Arrays decays naturally to pointers, so there is not need to use the address-of operator on an array to get a pointer. In fact, it can be dangerous if you think you have an array but actually have a pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM