problem in char* &

hi every body
in this code
1
2
3
4
5
6
void toPointer(char a[],char* &b[])
{
for(int i = 0;i < sizeof(a) / 4;i++)
b[i] = &a[i];

}


i have error(this error is for char* &b[])
how can i fix it?
Use char* b[] is ok.
it's important for me to use char* &b[]
because i want to change b[] in main function
Use char* b[] can keep the change made in function toPointer().
void toPointer(char a[],char* &b[]) //ERROR - arrays of references not legal
my problem is that i want change b array in main function
all of you know if we use (char* b[]) char* b in main function doesn't change
so we must use &.
how can i use this & for fix this problem?
tnx a lot
ibtkm wrote:
all of you know if we use (char* b[]) char* b in main function doesn't change

Why would you think that? As long as you're passing a non const pointer OR reference to the object, there's nothing stopping you from writing into it.
You are confused about how C/C++ passes arrays between functions..
In C/C++ arrays are passed by reference NOT by copy
So as aidyszh already said you just do char* b[]

Another thing - this also isn't right (pt is a follow on of your array confusion)
for(int i = 0;i < sizeof(a) / 4;i++)
because you are not passing a copy of the a array - C/C++ actually passes a pointer -
so sizeof(a) is actually calculationg the size of a char*

And why the division by 4?


if you look in the articles section there is a article all about arrays.
I understand OP's question, at least i think i understand. but might be not quite.
1. if OP wants to change the pointer itself (not the value that the pointer points to), a char*&, or char** is a must.
2. in OP's case, it doesn't work, because no way to take a reference of an array in C++.
3. an alternative is to put your array dynamically on the heap, rather than statically on stack. then you can use char** .
4. for 3. OP need a smart pointer to handle the ownership issue, if necessary.


1
2
3
4
5
6
7
8
9
10
11
void seearr(int* a[]){
  cout<<&a<<endl;
}

int main(int argc, char* argv[]){
  int b1;
  int b2;
  int* ap[]={&b1, &b2};
  cout<<&ap<<endl;
  seearr(ap);
}

main::ap and seearr::a, have definitely different address, a is only a copy of ap.
but, there is no way to change ap if it is an static array, that's why no reference to array is allowed.
you need to use "new".
Last edited on
everid wrote:
2. in OP's case, it doesn't work, because no way to take a reference of an array in C++.


You can a reference to an array - you cannot have arrays of references

1
2
3
4
5

int (&ref_to_array) [6]; //OK - reference to an array_of_6_integers.

int &ref [6]; //ERROR - this is an attempt to create an array of 6  references_to_integers
Last edited on
i need to add: "when passing as a function argument."
Topic archived. No new replies allowed.