If I have this code:
How do I make b[2] point to a[0], so that if I change the value of a[0], the value of b[2] gets changed accordingly.Code:#include <iostream> using namespace std; int main(int argc, char *argv[]) { char a[1]; char b[4]; a[0] = 3; b[0] = 1; b[1] = 2; *b[2] = a[0]; b[3] = 4; a[0] = 5; cout << b[2] << endl; return (0); }
You'd need a pointer to be able to point.
the b[2] is always evaluated to be the value contained inside the b index of 2 not as a pointer and since b is a character array it cannot be used as a pointer.
the b is considered to be a special type of pointers but it always points to the beginning of the array and cannot point to next element.
so i dont think that's possible to do what you want.
"Recursion is just a line of code"
-Karim Hosny-
My flickr
Alright, so instead I need to make an array of 4 pointers. And I want to be able to set the value of the memory group for each pointer. So I do this:
I know that *b[0] works as I want it to, by assigning the allocated memory pointed to by *b[0] the value 1. And *b[2] = &a[0] should assign the address of a[0] to the pointer *b[2]. But I get the error "cannot convert from 'char *' to 'char'". So what do I need to change here?Code:#include <iostream> using namespace std; int main(int argc, char *argv[]) { char a[1]; char *b[4]; a[0] = 3; *b[0] = 1; *b[1] = 2; *b[2] = &a[0]; *b[3] = 4; a[0] = 5; cout << a[0] << endl; cout << b[0] << endl; cout << b[1] << endl; cout << b[2] << endl; cout << b[3] << endl; return (0); }
try it without the *
so it would be b[2]=&a[0]
as the *with a pointers is used to access the value that the pointer points at, but without * let you reassign an address to the pointer variable.
"Recursion is just a line of code"
-Karim Hosny-
My flickr
Right, that compiles, but I get a warning for *b[0] = 1; saying "uninitialized local variable 'b' used". So how do I initialize it?
You kinda need to decide what you want b to be. Is it going to be an array of pointers, or an array of chars? It can't be both simultaneously.
Well, obviously I want it to be an array of pointers that point to variables of type char like with *b[0] = 1;
Edit:
Nevermind, I neglected the fact that *b[0] = 1 means that at the address that b[0] points to, the value is set to 1. So it makes sense now that b[0] has to be initialized to point to an address first, and that's why I'm getting the error.
Thank you for all the help, I think I've got it now.![]()
Last edited by ThemePark; 01-25-2010 at 12:51 AM.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks