#include <iostream> #include <string> using namespace std; void setNumber(string array[3], int t) { array[0] = "255"; t = 255; } int main() { int t = 1; string array[3] = { "1","2","3" }; setNumber(array, t); cout << array[0] << endl; //обратить внимание на эти строчки кода cout << t; // } //консоль array[0] = 255 //t = 1 <- ??? 

Why in this code does the array element store the value through the setNumber function while the variable t of the int type is not?

  • To avoid such troubles, define parameters as constant, for example; void setNumber(const string array[3], int t) - Andrey Sv

1 answer 1

Because the function signature is actually setNumber(string * array, int t) . C-style arrays in C / C ++ cannot be passed to a function by value, and the type of such an argument will always be a pointer. Pass all by reference, then the changes will be visible in main

 void setNumber(string (& array)[3], int & t)