I'm relatively new too C++ programming. While I was working on a code about arguments passing with an array of character pointers. I encountered a problem where the value of my pointers are changed after certain operations. Below is my code.
#include <iostream>
using namespace std;
void input(char* argv[], int &i)
{
char buff[10][20]; //buffer string array
while (cin.peek() != '\n') {
cin >> buff[i++];
}
for (int j = 0; j < i; j++) {
argv[j] = buff[j];
}
argv[i] = NULL; // putting a NULL at the end
}
int main(int argc, char* argv[])
{
char *arg[10];
int i = 0;
input(arg, i); //input the arguments
for (int j = 0; j < i; j++) {
cout << arg[j] << endl; //output the arguments entered
}
return 0;
}
The sub-function void input(char* argv[], int &i)
is supposed to let me input my arguments as many as 9 times or when an enter key is pressed. While i
indicates the total number of arguments.
The arguments are then stored as an array of character pointers and then pass it back to the main function's char *arg[10]
to hold.
However, I found that after
cout << arg[j] << endl;
The values of arg
are lost, and random values are being printed.