简体   繁体   中英

Reassigning strings involving pointers in C

This is a homework problem, and I believe it is a syntax problem. I have a program with a method that uses arrays of chars to represent strings. I'm trying to copy parts of the arrays into a temporary variable. I pass in these variables:

int numbers[], char arr1[][20], char arr2[][20], int l, int r

and initialize/copy into the temporary variables:

char *temp1;
char *temp2;

temp1 = arr1[l];
temp2 = arr2[l];

This code compiles and I believe it works. The problem occurs when I try to assign the temporary variables to places in the array. I've tried both:

arr1[l] = temp1;
arr2[l] = temp2;

and

arr1[l] = &temp1;
arr2[l] = &temp2;

all of these result in the following error:

error: incompatible types in assignment

So obviously I'm not writing these statements correctly. Both are of type char(I don't know if that has anything to do with the problem). I don't know how I can fix this though. Could anyone please help?

arr1[l]

arr1[l] is an array (a char[20] , specifically). Arrays are not modifiable lvalues, hence they are not assignable.

You need to copy the contents of the array pointed to by temp to arr1[l] . But, if you're trying to swap rows or something like that, you need to allocate some intermediate storage because

char *temp = arr2[l];

doesn't copy the contents, so a

memcpy(arr2[l], source, some_size);

would change the contents of what temp points to, the old contents of arr2[l] would be lost.

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