0

Passing pointers as parameters C

Hey guys I got a quick question! So let’s suppose in my main method I create an array. I want to pass this array to a function that will call another function that takes the array as a function. The thing is I want to modify the original array so I know I’m going to have to pass a pointer to the pointer that points to the first block of memory to both of them. I get how to pass and manipulate it in the first function but I’m not sure what the syntax would be to pass it from that first function that revived it as a pointer to the next one.

17th Jun 2018, 2:38 PM
Haon1919
Haon1919 - avatar
6 Antworten
+ 1
Here is the example. #include <iostream> using namespace std; void printAgain (int *arr, int n) { int *a = arr; cout<<"printAgain"<<endl; for(int i = 0; i< n ; i++) { cout << *a; a++; } cout<<endl; } void print(int *arr, int n) { int *a = arr; for(int i = 0; i< n ; i++) { cout << *a; a++; } cout<<endl; printAgain(arr,n); } int main() { int a[] = {1,2,34}; print(a,3); return 0; }
17th Jun 2018, 3:36 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
+ 1
You mean like this? https://code.sololearn.com/c16PSkF55W00/?ref=app Just repeat like you do it for the first function call.
17th Jun 2018, 3:39 PM
Matthias
Matthias - avatar
+ 1
Noah Shirey I just stored the starting address of original arr. it will not create any copy of original array. original array will be same always. just to keep track on starting address I used temp poiner for manipulation.
17th Jun 2018, 5:56 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
+ 1
Noah Shirey I'm just passing the original pointer further. arr == p in foo1 == p in foo2
17th Jun 2018, 8:51 PM
Matthias
Matthias - avatar
0
SagaTheGreat hey thanks for the response! So im going to be manipulating the array that is passed in so does passing the pointer im as you did allow the original array to be traversed or does it creat a copy of the array because for some reason I thought you had to pass a pointer to a pointer to manipulate the address.
17th Jun 2018, 5:53 PM
Haon1919
Haon1919 - avatar
0
Matthias ya! So all you have to do is pass the pointer to the first part of the array or are yot still passing a pointer to the furst pointer in the array?
17th Jun 2018, 5:55 PM
Haon1919
Haon1919 - avatar