In the following code I am running into an issue with mutating an array. My question is why doesn't the funOne function mutate the array that I pass in?
#include <iostream>
void funOne(char *arr, char x, char y, int z);
void print(char *array);
void print(char *array){
std::cout << array << std::endl;
}
void funOne(char *arr, char x, char y, int z){
z = sizeof(arr);
for(int i = 0; i<z; i++){
if(arr[i] == x){
x == y;
}
}
}
int main(){
char arra[] = {'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b'};
funOne(arra, 'a', 'c', 10);
print(arra);
system("pause");
return 0;
}
x == y;
Whoops...?
==
operator is for comparing things; =
operator is for assigning things. Furthermore, I guess you wanted to assign to arr[i]
, not x
:
arr[i] = y;
Take greater care.
Your final problem is that z
will be wrong, because arr
is not your array but a pointer to your array… and sizeof(char*)
is fixed. You will have to pass the array's length in to the function as another argument.
Or, y'know, use a std::vector
seeing as this is the 21st century!!
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.