-
pointers and arrays
hey i am trying to learn pointers and references.
how can i pass an array of characters by reference to a function?
Code:
void funct(char *text)
{
cout << *text << endl;
*text = 'c';
}
int main()
{
char text;
cin >> text;
funct(&text);
cout << text << endl;
return 0;
}
this works with one character but i can't figure out how to make it work with an array
-
Arrays are automatically passed by reference. If you want to pass a null-terminated character array, you can make the function parameter char* text or char text[] since the size is determined by the terminating null character. For other arrays, you have to pass the size as a separate parameter, or as part of the array parameter: int arr[5].
Of course, in C++ you should just use the C++ string class instead null-terminated character arrays, and vector (or some other container) instead of regular arrays.
-
You wouldn't need to pass an array by reference. You already pass the array by pointer. Just use cin.get(), fill a character array, and pass that to funct. What happens after that will be dependant on what you're trying to do. You'd have to use a loop to fill the array with 'c'. Or use memset().
-
that was simple lol
thanks daved