Thread: pointers

1. pointers

I had a question about pointers. Now i know that for char *'s to be used as strings you must allocate them first, but if i have this code:

Code:
```char *a = (char *) malloc (10);
char *b = *a;```
then b will hold the same memory as a, right? I dont have to reallocate b, right?

2. char *b = a; would be correct

but they do contain the same address... if that's what you want.

3. char *b = *a is a syntax error. (Or at least a warning, since the right side is a character and the left side a pointer.)

If you do char *b = a, then b will point to the same memory that a points to. You will NOT get a copy of it; it will be the exact same memory (so any changes made through b will be "seen" using a).

Also, there is no valid reason to cast malloc here.

4. b will point to the same memory yeah. But you want this:
Code:
`char *b = a;`
When declaring a pointer you put the *. When you have already declared the pointer the * means the value of the memory that a shows. You want to copy the value of the pointer not the value of the memory pointed by the pointer

EDIT: To elaborate a bit. When you declare a variable you allocate memory for it. So if you do char* b you allocate memory (static allocation) for a pointer that points to a char. Pointers on a 32bit system are usually 4bytes.
Now, the pointer has a value. A number. That value represents a memory address.
Now. When you call malloc(), a piece of memory is allocated and a pointer to that memory is returned. That means that the address of the beginning (the first element) of the memory is returned. That memory address (thus pointer) is stored in the pointer a. So a has a memory address dynamically allocated.
You declare char *b. Memory allocated (static allocation) for b, usually 4bytes since it is a pointer. Now pointer b also has a value, which that value is a memory address. If you want for b to have the same memory address with a you just do b = a;, since a is a pointer. If a was an char then you would do b = &a since you don't want the value of a but the memory address a is stored.
Finally, the whole point is that you can read the value of a memory address stored in a pointer. That is done with *.
What happens then is that the system reads the value of the memory address, which memory address is stored at the pointer variable.
Consider this:
Code:
```int *p1, *p2; //2 pointers
p1 = *(&p2);```
Think what does the second instruction actually do?

Anyway, got a bit carried away :P

5. actually, i did mean to say *b = a. that was a typo. I was more or less asking whether it does exactly what you guys explained to me. i just wanted to know if you could assign a pointer to point to the same chunk of memory as another pointer.

Popular pages Recent additions