What is the difference between Pointer and strings? - c++

What is the difference between a pointer and array or they are same? As a array also works with poiter arithematic so it can be said that an array is nothing but pointer to its fitst element.

They both are different by the following differences:-
int array[40];
int * arrayp;
Now if you will try to see the size of both then it will be different for pointer it will same everytime whereas for array it varies with your array size
sizeof(array);\\Output 80
sizeof(arrayp);\\Output 4(on 32-bit machines)
Which means that computer treats all the offsprings of integers in an array as one which could not be possible with pointers.
Secondly, perform increment operation.
array++;\\Error
arrayp++;\\No error
If an array could have been a pointer then that pointer's pointing location could have been changes as in the second case with arrayp but it is not so.

Related

Clarification on the relation of arrays and pointers

I wanted some further understanding, and possibly clarification, on a few things that confuse me about arrays and pointers in c++. One of the main things that confuse me is how when you refer to the name of an array, it could be referring to the array, or as a pointer to the first element, as well as a few other things. in order to better display where my trouble understanding is coming from, I'll display a few lines of code, as well as the conclusion that I've made from each one.
let's say that I have
int vals[] = {1,50,3,28,32,500};
int* valptr = vals;
Because vals is a pointer to the first value of the array, then that means that valptr, should equal vals as a whole, since I'm just setting a pointer equal to a pointer, like 1=1.
cout<<vals<<endl;
cout<<&vals<<endl;
cout<<*(&vals)<<endl;
cout<<valptr<<endl;
the code above all prints out the same value, leading me to conclude two things, one that valptr and vals are equal, and can be treated in the same way, as well as the fact that, for some reason, adding & and * to vals doesn't seem to refer to anything different, meaning that using them in this way, is useless, since they all refer to the same value.
cout<<valptr[1]<<endl;//outputs 50
cout<<vals[1]<<endl;//outputs 50
cout<<*vals<<endl;//outputs 1
cout<<*valptr<<endl;//outputs 1
the code above furthers the mindset to me that valptr and vals are the same, seeing as whenever I do something to vals, and do the same thing to valptr, they both yield the same result
cout<<*(&valptr +1)-valptr<<endl;
cout<<endl;
cout<< *(&vals + 1) -vals<<endl;
Now that we have established what I know, or the misconceptions that I may have, now we move on to the two main problems that I have, which we'll go over now.
The first confusion I have is with cout<< *(&vals + 1) -vals<<endl; I know that this outputs the size of the array, and the general concept on how it works, but I'm confused on several parts.
As shown earlier, if
cout<<vals<<endl;
cout<<&vals<<endl;
cout<<*(&vals)<<endl;
all print out the same value, the why do I need the * and & in cout<< *(&vals + 1) -vals<<endl; I know that if I do vals+1 it just refers to the address of the next element on the array, meaning that *(vals+1)returns 50.
This brings me to my first question: Why does the & in *(&vals+1) refer to the next address out the array? why is it not the same output as (vals+1)in the way that *(&vals)and (vals)have the same output?
Now to my second question. We know thatcout<< *(&vals + 1) -vals<<endl; is a valid statement, successfully printing the size of the array. However, as I stated earlier, in every other instance, valptr could be substituted for vals interchangeably. However, in the instance of writingcout<<*(&valptr +1)-valptr<<endl; I get 0 returned, instead of the expected value of 6. How can something that was proven to be interchangeable before, no longer be interchangeable in this instance?
I appreciate any help that anyone reading this can give me
Arrays and pointers are two different types in C++ that have enough similarities between them to create confusion if they are not understood properly. The fact that pointers are one of the most difficult concepts for beginners to grasp doesn't help either.
So I fell a quick crash course is needed.
Crash course
Arrays, easy
int a[3] = {2, 3, 4};
This creates an array named a that contains 3 elements.
Arrays have defined the array subscript operator:
a[i]
evaluates to the i'th element of the array.
Pointers, easy
int val = 24;
int* p = &val;
p is a pointer pointing to the address of the object val.
Pointers have the indirection (dereference) operator defined:
*p
evaluates to the value of the object pointed by p.
Pointers, acting like arrays
Pointers give you the address of an object in memory. It can be a "standalone object" like in the example above, or it can be an object that is part of an array. Neither the pointer type nor the pointer value can tell you which one it is. Just the programmer. That's why
Pointers also have the array subscript operator defined:
p[i]
evaluates to the ith element to the "right" of the object pointed by p. This assumes that the object pointer by p is part of an array (except in p[0] where it doesn't need to be part of an array).
Note that p[0] is equivalent to (the exact same as) *p.
Arrays, acting like pointers
In most contexts array names decay to a pointer to the first element in the array. That is why many beginners think that arrays and pointers are the same thing. In fact they are not. They are different types.
Back to your questions
Because vals is a pointer to the first value of the array
No, it's not.
... then that means that valptr, should equal vals as a whole, since I'm just setting a pointer equal to a pointer, like 1=1.
Because the premise is false the rest of the sentence is also false.
valptr and vals are equal
No they are not.
can be treated in the same way
Most of the times yes, because of the array to pointer decay. However that is not always the case. E.g. as an expression for sizeof and operand of & (address of) operator.
Why does the & in *(&vals+1) refer to the next address out the array?
&vals this is one of the few situation when vals doesn't decay to a pointer. &vals is the address of the array and is of type int (*)[6] (pointer to array of 6 ints). That's why &vals + 1 is the address of an hypothetical another array just to the right of the array vals.
How can something that was proven to be interchangeable before, no longer be interchangeable in this instance?
Simply that's the language. In most cases the name of the array decays to a pointer to the first element of the array. Except in a few situations that I've mentioned.
More crash course
A pointer to the array is not the same thing as a pointer to the first element of the array. Taking the address of the array is one of the few instances where the array name doesn't decay to a pointer to its first element.
So &a is a pointer to the array, not a pointer to the first element of the array. Both the array and the first element of the array start at the same address so the values of the two (&a and &a[0]) are the same, but their types are different and that matters when you apply the dereference or array subscript operator to them:
Expression
Expression type
Dereference / array subscript expresison
Dereference / array subscript type
a
int[3]
*a / a[i]
int
&a
int (*) [3] (pointer to array)
*&a / &a[i]
int[3]
&a[0]
int *
*&a[0] / (&a[0])[i]
int

Is the name of a two dimensional array address of the address of its first element in C++?

When implementing a two dimensional array like this:
int a[3][3];
these hold: A=&A[0], at the same time A[0]=&A[0][0]. So, A=&(&A[0][0]), what basically says that A is the address of the address of the first element of the array, which is not quite true. What is my mistake here? Does A really decay to a pointer to a pointer?
Your mistake is that you have an incorrect understanding of the relationship between arrays and pointers. An array is not a pointer. It is an array. However, an array is implicitly convertible to a pointer to its own first element. So, while this expression does evaluate to true:
A == &A[0]
It is not correct to say that A is &A[0]. The conversion does not happen in all expressions. For example:
&A
This does not take the address of the address of the first element of A (that doesn't even make sense). It takes the actual address of A, who's type is int[3][3]. So the type of &A is int(*)[3][3], read as "pointer to array of 3 arrays of 3 ints".
The primary difference between &A and &A[0] is that if you add 1 to &A, you will get an address that is 3 * 3 * sizeof(int) bytes away, while if you add 1 to &A[0], you will get a pointer that is only 3 * sizeof(int) bytes away.
With all this in mind, you should be able to see where your mistake is. A[0] is not &A[0][0], but it is implicitly convertible to it. However, like all conversions, this results in a temporary, which you cannot take the address of. So the expression &(&A[0][0]) doesn't even make sense.
Because of reactions on my previous answer I did some research to learn more on whatever was wrong in my explanation.
Found a rather elaborate explanation of the topic here :
http://eli.thegreenplace.net/2009/10/21/are-pointers-and-arrays-equivalent-in-c
I'll try to summarize :
if you have following :
char array_place[100] = "don't panic";
char* ptr_place = "don't panic";
the way that this is represented in memory is entirely different.
whereas ptr_place is a real pointer, array_place is just a label.
char a = array_place[7];
char b = ptr_place[7];
The semantics of arrays in C dictate that the array name is the address of the first element of the array, which is not the same as saying that it is a pointer. Hence in the assignment to a, the 8th character of the array is taken by offsetting the value of array_place by 7, and moving the contents pointed to by the resulting address into the al register, and later into a.
The semantics of pointers are quite different. A pointer is just a regular variable that happens to hold the address of another variable inside. Therefore, to actually compute the offset of the 8th character of the string, the CPU will first copy the value of the pointer into a register and only then increment it. This takes another instruction [1].
This point is frequently ignored by programmers who don't actually hack on compilers. A variable in C is just a convenient, alphanumeric pseudonym of a memory location. Were we writing assembly code, we would just create a label in some memory location and then access this label instead of always hard-coding the memory value - and this is what the compiler does.
Well, actually the address is not hard-coded in an absolute way because of loading and relocation issues, but for the sake of this discussion we don't have to get into these details.
A label is something the compiler assigns at compile time. From here the great difference between arrays and pointers. This also explains why sizeof(array_place) gives the full size of the array where as the size of a pointer will give the size of a pointer.
I must say, I was not aware of these subtle differences myself, and I have been coding for quite a long time in C and C++ and with arrays too.
Nevertheless if the name of the array element is the address of the first element of the array. You can create a pointer and initialise it what that value
char* p = array_place
p will point to the memory location where the characters are.
to conclude :
There is one difference between an array name and a pointer that must be kept in mind. A pointer is a variable, so p=array_place and p++ are legal. But an array name is not a variable; constructions like array_place=p and array_place++ are illegal. That I did know ;-)

how do arrays work internally in c/c++

I was wondering how do arrays work in c. I end up with an hypothesis and I'd like to know if I am right or not.
We know arrays are a sequence of adjacent memory cases(boxes), where each box has the size of the type it stocks (i.e if INTs one box has a size = sizeof(int) and an array of 3 INTs takes in memory adjacent places of 3 sizeof(int) )
Now we also know that we can dynamically allocate memory for an array of a certain type (malloc in C, new in C++).
what makes me wonder is the fact that an array has for origin the the address of the first box of the array and the first value (the value in the later box) when calling it with the bracket [0] is array[0] == *(array+0) == *array (whether array was declared "type * array" or "type array[]" or "type array[size]") and "array" called that way whether define as a pointer or an array ("type * array" or "type array[]" or "type array[size]") is the address of the first box.
I end up thinking and I'd like a confirmation on this: arrays when even declared with the square brackets ([]) are actually in memory a sequence of n pointers each containing (having as a value not as an address) the address of a memory box Bi containing the actual value + those memory boxes (B0,...,Bn each containing the actual values). such that in the and when one declares "int array[5]" the program actually allocate 5 adjacent boxes of int pointers P0,P1,..,P4 and 5 int sized memory places scattered all over the computer memory B0,B1,...,B4 where the value of Pi is the address of Bi
Am I right or wrong!!?? Thank you!
arrays when even declared with the square brackets ([]) are actually in memory a sequence of n pointers each containing [...] the address of a memory box Bi containing the actual value + those memory boxes
Nope.
It sounds like you're puzzled how array[0] == *(array+0) == *array could be true both for an array declared as int array[10]; and int *array = ...;. A perfectly reasonable question; We're told that for a pointer ptr the expression *ptr gets the value the pointer is pointing at, so when we use the same syntax with an array where are the addresses that we're dereferencing?
Here's the secret: The array index operator ([]) does not work on arrays in C and C++. When you apply it to an array the language implicitly converts the array into a pointer to the array's first element. Thus adding to an array or dereferencing an array appears to behave the same as adding or dereferencing a pointer.
int array[10];
// These lines do exactly the same thing:
int *ptr1 = &array[0]; // explicitly get address of first element
int *ptr2 = array; // implicitly get address of first element
So arrays really are a contiguous set of elements in memory where each element really is the value, not a pointer to another location containing the value. It's just that the way arrays are defined means that they often convert to a pointer implicitly and so it seems like there are pointers when really there's just an implicit conversion.
Arrays are stored contiguously in the virtual memory. However, the physical memory addresses that they map to may or may not be contiguous.
And the array elements do not store a pointer to point to the next element. Only the value is stored.
Think of it as this:
array[n] is simply a syntactic sugar for *(array + n).
And no, there are no pointers, the array actually contains the values in a continuos memory range.
The array does not consist of any pointers. The elements of an array are stored on the heap whereas the reference to those elements is stored on the stack. If you declare an array called values of type int and it consists of 5 elements.
The variable values is a pointer to the first value values[0] stored on the heap, it is also referred to as the base address which is the address of the first element of the array. You might wonder that how would the code find the other elements of the array. values[1] can be dereferenced by *(values+1) or at a low level it is like this *(&values + n*sizeof(values[0])) where n is the index of the element you want to dereference.
So you get the other elements of an array by just adding the size of the element to the memory. This is because the elements of an array are stored side-by-side in memory or technically stated, the blocks of memory share the same border.
An array does not have any pointers, an array like data-structure that contains pointers is called a linked list.
You can learn about the internal working of arrays here

a couple of simple questions about basic pointer use in c++ and the c++ memory model

I've been studying along with the Stanford courses on iTunes U and have hit pointers in C++. I think I understand how pointers work, but I just want to check how to do some simple stuff. Let's say I want to create a dynamic array:
double *array;
At this point there's a variable called "array" in the stack and nothing in the heap. First question - what's stored in "array" at this point? A pointer to some nonsense piece of memory?
I then allocate memory using "new":
array = new double[10];
Second question - at this point, what's stored in "array"? A pointer to some contiguous piece of memory big enough to hold ten doubles? (Sorry for the simple questions, but I really want to make sure I understand)
I assign the double 2.0 to each element in the array:
for(int i=0; i<array.length(); i++) array[i]=2.0;
Third question - is this different from using the dereference operator to assign? (i.e., *array[i]=2.0). I then pass the array to some other function:
myFunc(double array[]){
for(int i=1; i<array.length(); i++){
array[i]=array[i]*array[i-1];
}
}
Fourth question - on the pass to myFunc, since array is an array of pointers to doubles, and not an array of doubles, it passes by reference without "&", right? That means the operations in my loop are affecting the actual data stored in "array". What if I wanted to pass by value, so that I wouldn't be touching the data in "array"? Would I use
myFunc(double *array[]){...}?
Last question - what if I wanted to manipulate the memory addresses for the contents of "array" for some reason? Could i use
someVar = &array[5];
to assign the the hex address of array[5] to someVar?
I've read the section on pointers in the reader and watched the Binky video a dozen times and it still doesn't make sense. Any help would be greatly appreciated.
EDIT: Thanks a lot to everyone who answered so far. If you wouldn't mind I just have one more question. In the declaration double *array;, "array" is declared as a pointer to a double, but once I use "new" to assign it, "array" ceases being a pointer to a double, and becomes an array of doubles, right?
array contains junk data - whatever was in that memory location before array existed is still there. If you try to play with it you're going to shoot yourself in the foot, which is why you need to assign it to a valid memory location, (hence the ensuing call to new[]).
Yes, array now contains a pointer (memory address) to some contiguous piece of memory big enough to hold ten doubles.
*array[i]=2.0 won't actually compile. array[i] results in a double, and you can't use the dereference operator on a double.
What you're passing is that address to the first element in the array. So you are passing the pointer by value, and the array by reference (as the pointer is a reference to the array.) To pass the array itself by value you'd have to have one parameter for each entry. You could also copy the array and send in the copy, but the copy itself would be passed by reference, too.
double* someVar = &array[5]; will return to you a pointer to the 6th element of the array. array[5] gives you the double, and taking the address of it (with &) will give you the memory address (pointer) of that double.
Yep, that's what's happening
Most definitely. More specifically, a pointer to the beginning of a contiguous piece of memory.
Not in this case; * (for dereference) is a unary operator, and yet you have passed it two arguments. You can be sure it is multiplication that is performed (or an overloaded version of it) - also, what could array[i](*array[i-1]) mean? you can't dereference something that isn't a pointer (or doesn't have the unary * operator overloaded)
You're only passing the pointer by value and not the data. If you want to pass the data by value (make it unchanged outside the function), you'd have to copy it first, and pass that (or just use a vector)
Yes, you're just getting the address of a part of contiguous memory, and you can store the address and modify the dereferenced value elsewhere, the array will be modified also.
Also, be weary that when you allocate on the heap, you have to delete the memory afterwards. In this case, you would use delete[] array;
After declaration, the array variable contains an arbitary value. You're not allowed to do anything with that value. After new, it contains a pointer to a contiguous range of memory large enough to hold 10 doubles. *array[i]=2.0 is an error (that would imply that array is an array of pointers to double). Indexing operator [] is just a syntactic sugar for *(array+i)=2.0.
Forth question: SAY WHAT?? You don't have an array of pointers to doubles anywhere in that code. In functions, void f(double *x) and void f(double x[]) are THE SAME THING: a pointer to double. If you pass to f an array, x will receive the address of the first element (which is the VALUE of an array).
You can't pass arrays by value. Alternatively, they are always passed by value (as everything else in C), but note that the VALUE of an array is the address of its first element.
Your last question: I have no idea what you're trying to achieve, but the question clearly shows that you're confused. An address is an address, there's no such thing as "hex address".

Why does binary saving of array in a file works? [C++]

C++ newbie here.
I'm trying to figure out the following line that writes a buffer into a file:
fOut.write((char *)&_data, sizeof(_data));
_data = array of integers...
I have a couple of questions:
Is &_data the address to the first element of the array?
Whatever address it is, does that mean that we only save the address of the array? then how come I still can access the array after I free it?
Shouldn't I pass sizeof(_data)*arrLength? what is the meaning of passing the size of int (in this case) and not the size of the entire array?
What does casting into char* mean when dealing with addresses?
I would really appreciate some clarifications.
Contrary to your comment, the array must be automatic or static storage duration in order for sizeof to work.
It should be just (char*)_data. The name of an array implicitly converts to a pointer to the first element.
No, write expects a pointer, and stores the content found at that location, not the location's address.
No. Since _data is an array, sizeof (_data) is the cumulative size of all elements in the array. If _data were a pointer (such as when an array is dynamically allocated on the heap), you would want numElems * sizeof(_data[0]). Multiplying the size of a pointer by the number of elements isn't helpful.
It means that the content at that address will be treated as a series of individual bytes, losing whatever numeric meaning it might have had. This is often done to perform efficient bulk copy of data, either to and from a file, or with memcpy/memmove. The data type should be POD (plain old data) or you'll get unexpected results.
If _data is a pointer to an array allocated from the heap, as your comment suggests, then the code is badly broken. In that case, you are saving just the address, and it may appear to work if you load the file back into the same instance of your program, but that's just because it's finding the data still in memory at the same address. The data wouldn't actually be in the file, and if you re-started the program before loading the file, you'd find that the data was gone. Make the changes I mentioned in both (1) and (3) in order to save the complete array regardless of whether it's allocated automatic, static, or dynamically.
What does casting into char* means
when dealing with addresses?
Imagine this simple example
int x = 12;
char * z = (char *)&x;
And assume an architecture where int is 4 bytes long. From the C++ Standard sizeof(char)==1.
On the expression char * z the char * part, you could say that is being used for pointer arithmetic
on the Second line of the example I gave, what happens is that z now points to the first (out of 4 bytes) that x has. Doing a ++z; will make z point to the Second Byte of the (in my example) 4byte int
You could say that the left part of a declaration is used for pointer arithmetic, to simplify things. a ++(char *) would move you by one byte, while a ++(int *) would move you by the corresponding number of bytes int occupies on the memory.
Yes
No, write uses this address as the first location, and reads through sizeof(_data) writing the whole array
sizeof(_data) will return the size of the entire array not the same as sizeof(int)
Means the data will be read byte by byte, this is the pointer required by write as it writes in binary format(byte by byte)
1) Yes, &_data is the address of the first element of your array.
2) No, write() writes the number bytes you have specified via sizeof(_data) starting at address &_data
3) You would pass sizeof(int)*arrLength if _data is a pointer to an array, but since it is an array sizeof() returns the correct size.
4) don't know. ;)
read this : http://www.cplusplus.com/reference/iostream/ostream/write/
should be.
if you call "fstream.write(a,b)" then it writes b bytes starting from location a into the file (i.e. what the address is pointing at);
it should be the size in bytes or chars .
not much, similar to casting stuff to byte[] in more civilized languages.
By the way, it will only work on simple arrays with simple values inside them...
i suggest you look into the >> << operators .
is &_data the address to the first element of the array?
Yes, it is. This is the usual way to pass a "reference" to an array in C and C++. If you passed the array itself as a parameter, the whole array contents would be copied, which is usually wasteful and unnecessary. Correction: You can pass either &_data, or just _data. Either way, the array does not need to be copied to the stack.
whatever address it is, does that mean that we only save the address of the array? then how come I still can access the array after I delete him from the memory?
No, the method uses the address it gets to read the array contents; just saving the memory address would be pointless, as you point out.
Shouldn't I pass sizeof(_data)*arrLength? I mean...
what is the logic of passing the size
of int (in this case) and not the size
of the entire array?
No, sizeof(_data) is the size of the array, not of one member. No need to multiply by length.
What does casting into char* means when dealing with addresses?
Casting to char* means that the array is accessed as a list of bytes; that's necessary for accessing and writing the raw values.