I'm confused as to what a line of code does in this program:
int *temp = new int [cap];
int num = 0;
for(int i = name; i < number; i++)
{
*(temp + count) = *(foo + i);
num++;
}
name
, number
, and foo
are global variables (foo
being a pointer),
and cap
is an argument.
Specifically, I don't understand this line:
*(temp + count) = *(foo + i);
Why are there pointers to the parentheses, and what will this do?
int* means a pointer to a variable whose datatype is integer. sizeof(int*) returns the number of bytes used to store a pointer.
An integer pointer (like addressOfDigit ) can only store the address of variables of integer type. int variable1; int variable2; char variable3; int *addressOfVariables; * – A pointer variable is a special variable in the sense that it is used to store an address of another variable.
No, pointers are not integers. A pointer is an address.It is merely a positive number and not an integer.
1.2 Declaring Pointers Pointers must be declared before they can be used, just like a normal variable. The syntax of declaring a pointer is to place a * in front of the name. A pointer is associated with a type (such as int and double) too.
*(temp + count) = *(foo + i);
The +
operators are performing pointer arithmetic. Adding an integer to a pointer value yields a new pointer incremented a specified number of objects past the original pointer. For example, if p
is a pointer to arr[0]
, then p+2
points to arr[2]
.
The *
operator deferences the resulting pointer, giving you the object that it points to.
In fact, the array indexing operator []
is defined in terms of pointer arithmetic, so that A[i]
means *(A+i)
(ignoring operator overloading). So the above line of code:
*(temp + count) = *(foo + i);
could also be written (more clearly IMHO) as:
temp[count] = foo[i];
You might want to read the comp.lang.c FAQ, particularly sections 4 (Pointers) and 6 (Arrays and Pointers). Most of the information is also applicable to C++.
However, C++ provides higher-level library interfaces that can be more robust than the low-level C equivalents. It's seldom a good idea in C++ to write code that deals directly with arrays and pointers to array elements, unless it's very low-level code and performance is critical and/or you're dealing with data structures from C code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With