Passing scalar and array data in C++ with pointers -


i have programmed many years in fortran , trying learn c++ , transfer old programs c++. need able create array in function , pass main program variable using pointer opposed having transferred value traditional in c++. including example in question variables *var1, *varr , *array created , data passed main program , program works fine. however, if turn *array *array[1] or larger dimension array multiple values program not work. can action completed in c++ or forced incorporate function main program data available in main program? appreciated!

first example(this 1 works)

#include<iostream> using namespace std; void test(int *var1,int *varr, int *array);  int main() {     int var,var2,array1;     test(&var,&var2,&array1);     cout << var << "\n";     cout << var2 << "\n";     cout << array1 << "\n";     return 0; }  void test(int *var1, int *varr, int *array) {     *var1=20;     *varr=30;     *array=15; } 

second example (this 1 not work)

#include<iostream> using namespace std; void test(int *var1,int *varr, int *array[1]);  int main() {     int var,var2,array1[1];     test(&var,&var2,&array1[1]);     cout << var << "\n";     cout << var2 << "\n";     cout << array1 << "\n";     return 0; }  void test(int *var1, int *varr, int *array[1]) {     *var1=20;     *varr=30;     *array[1]=15; } 

int var,var2,array1[1];

about array1, declaration equivalent :

int array1[1];

which means, array of 1 integer. can access each integer syntax :

array1[x]; // int

therefore, when write

&array[1];

you retrieving address of int - int*, in many ways incompatible type of last parameter of function test.

what intend can completed sligthly modifying function declaration:

test(&var1, &var, &array1);  void test(int *var1, int *varr, int (*arrayptr)[1]) // arrayptr pointer array of 1 integer {   (*arrayptr)[0] = 15; // assign 15 first integer of array pointed arrayptr. } 

remember in c/c++, indexing starts 0 - if want reach first integer of array, need write array[0] , not array[1].

this pretty awkward way of doing however, in c++ - might want use vector has more straightforward approach.

#include <vector> #include <iostream  int main() {   std::vector<int> myvector(1); // vector class encapsulates dynamic array. here, create vector 1 pre-allocated element.    test(myvector);   std::cout << myvector[0] << std::endl; }  void test(std::vector<int> &referencetomyvector) {   referencetomyvector[0] = 15; } 

Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -