C++: array for loop printing addresses instead of values - c++

this was an example given to us in class. Could someone explain to me why this prints 29 addresses instead of 29 "0" (zeroes) ?
int num[29]; is an array which has set aside 29 addresses for 29 integers -i get that part, but in the for loop you arent u printing the values IN those addreses rather than the addresses themselves?
also, whats the difference between (num+i) and (num[]+i)?
I'm a little confused..
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int num[29];
for (int i=0;i<29;i++)
cout << (num+i) << endl;
return 0;
}

The reason for printing addresses is that
(num+i)
Is the address of the ith element of the array, not the ith element itself. If you want to get the ith element, you can write
*(num + i)
Or, even better:
num[i]
As for your second question - the syntax (num + i) means "the address i objects past the start of num, and the syntax (num[] + i) is not legal C or C++.
Hope this helps!

A declaration such as:
int num[29];
defines a contiguous array of 29 integers.
To access elements of the array use num[i] where i is the index (starting at 0 for the 1st element).
The expression num on its own gives a pointer (memory address and type) of the first element of the array.
The expression ptr + i (where ptr is a pointer and i is an integer) evaluates to a pointer that is i positions (in units of the type of pointer) after ptr.
So num + i gives a pointer to the element with index i.
The expression &a gives a pointer to some object a.
The expression *ptr gives the object that some pointer ptr is pointing at.
So the expressions a and *(&a) are equivalent.
So num[5] is the same as *(num+5)
and num+5 is the same as &num[5]
and num is the same as &num[0]
When you print a pointer with cout it will show its address.
When you print an object it will print the value of the object.
So
cout << num + 5;
will print the address of the 5th (zero-indexed) element of num
and
cout << num[5];
will print the value of the 5th (zero-indexed) element of num

Related

Inserting a Integer Array into a Pointer Array?

Can someone tell me how this compiles. How can you assign an integer array element to a pointer array element? The weird this is that the output suggests that nums[i] is an integer rather than a pointer, however nums was defined as a pointer.
#include <iostream>
int main() {
int n;
int *nums = NULL;
nums = new int[n]; // Assign pointer nums to a address in heap allocated for a integer array of n-elements.
n=5;
int Array[n] = {5,4,3,6,8};
for(int i=0; i<n; i++)
{
nums [i] = Array[i];
std::cout << nums[i] << " , " << &nums[i] << std::endl;
}
delete []nums;
return 0;}
I get the following output:
5 , 0x786cd0
4 , 0x786cd4
3 , 0x786cd8
6 , 0x786cdc
8 , 0x786ce0
Thanks for any help
How can you assign an integer array element to a pointer array element?
nums is a pointer to a dynamic array of int elements, in this case to the 1st int in the array. Dereferencing nums[i] yields an int& reference to the ith element in the array.
Array is a fixed array of int elements. When a fixed array is accessed by its name, it decays into a pointer to the 1st element. So, dereferencing Array[i] also yields an int& reference to the ith element in the array.
Thus, nums[i] = Array[i]; is simply assigning an int to an int. Nothing weird about that.
the output suggests that nums[i] is an integer rather than a pointer
That is correct, it is.
however nums was defined as a pointer
That is also correct. It is a pointer to an int, in this case the 1st int in the dynamic array.
Also, on a side note, your code has undefined behavior because n is uninitialized when used to allocate nums, and int Array[n] is non-standard behavior since n is not a compile-time constant.

Filling an array using a pointer

Trying to fill an array using a pointer so each index of array contains its' index. The output I am currently getting is this +DD;D;DD. Could someone explain where I am going wrong on this? Thanks.
#include <iostream>
using namespace std;
int main()
{
int NUMBER_ELEMENTS;
cout << "Enter number of elements: ";
cin >> NUMBER_ELEMENTS;
short array1[NUMBER_ELEMENTS];
short *arrPtr;
arrPtr = array1;
short i = 0;
while(i < NUMBER_ELEMENTS)
{
*arrPtr = i;
arrPtr = arrPtr + 1;
cout << "+" + array1[i];
i++;
}
}
Problem 1: The length of an automatic array can not be given at runtime. It must be known at compile time. In order to create an array with dynamic length, you can use std::vector instead.
explain how this is a variable length array?
You can input different values in different executions of the program. Therefore the length varies. Even the value staying the same is by itself not sufficient. The expression used the array length must be a compile time constant expression.
Problem 2: "+" + array1[i] doesn't do what you probably think it does.
The string literal is an array of characters. array1[i] is an integer. When you add an integer to an array using the plus-operator, the array decays to a pointer to first element of the array, and the the pointer is incremented by number given as the operand.
Therefore "+" + 0 increments the pointer by zero places, so the string printed in the first iteration is "+". "+" + 1 increments the pointer by one places. After the + character, there is only the null terminator, so the printed string is empty. After that iteration, the later iterations overflow the array, and the behaviour of the program is undefined.

How is this particular code processed in C++14

I know there is a bug in the code, but I am interested to know exactly how C++14 processes the code to output this
3
þÿÿt
With this code
#include <iostream>
void pretty_print(int,int,int);
int main()
{
srand(time(0));
const int LIM = 100;
int a = rand()%LIM;
int b = rand()%LIM;
int c = rand()%LIM;
if(a+b+c<500)
{
pretty_print(a,b,c);
}
else throw new std::invalid_argument("FOOBAR");
return 0;
}
void pretty_print(int a, int b,int c)
{
std::string ans = "";
int count = 0;
if(a!=0)
{
count++;
ans+=(a+" ");
}
if(b!=0)
{
count++;
ans+=(b+" ");
}
if(c!=0)
{
count++;
ans+=(c+" ");
}
std::cout << count << "\n";
std::cout << ans << "\n";
}
P.S. I have deliberately tried to add an integer to a string without conversion in order to examine why the output is such. I want to know why adding an integer without conversion to a string results in such a behaviour.
I want to know why adding an integer without conversion to a string results in such a behaviour.
A string literal is an array of characters. In a value context (such as as an operand of +), an array will be converted into pointer to first element. This implicit conversion is called decaying.
Adding an integer n to a pointer (to an element of an array) will result in a pointer to nth successive sibling of the originally pointed element. For example, "abcd" + 1 will result in a pointer to the characer b. This is called pointer arithmetic.
You generate numbers up to 100, so you end up getting a pointer to up to hundredth index of the string literal. However, the length of the string literal is only 2 (the length of the array includes the null terminator in addition to the length of the string itself), so unless you happened to generate only zeroes and ones, those pointers will be outside the bounds of the string literal.
When a character pointer is passed to the compound assignment operator of std::string, that pointer will be treated as a null terminated pointer to a character string and the pointed object will be accessed.
The behaviour of accessing an array out of bounds is undefined.
In C++ a string literal like e.g. " " is really an array of constant characters. As such it will decay to a pointer to its first element.
What you're doing with a+" " is pointer arithmetic: You add the value of a to the pointer pointing to the first character of " ". In other words, a + " " is equal to &" "[a]. (It helps knowing that for any pointer or array p and index i the expression *(p + i) is exactly equal to p[i].)
Unless the values of your variables is 0 (or 1, which is the index of the terminator), then the values as indexes will be way out of bounds of the array holding " ", leading to undefined behavior.

Having difficulty working with pointers

I having some issue when it comes to initializing pointers.
void findMM (int *PMM, int *theG)
{
// code I haven't written yet. It will essentially take two variables from //theG and store it in MM
}
int main()
{
int size;
int MM [2] = {1000, 0};
int *theG = NULL;
cout << "\nPlease insert size of array:" << endl;
cin >> size;
theG = new int [size];
findMM(&MM, &theG); //Get error with &MM
delete [] theG;
return 0;
}
The complier says that argument of type int (*)[2] is incompatible with parameter of type int ** So obviously that I have issue with the code in particular my (reference?) of array MM. Or perhaps there is other obvious faults that I am missing?
Edit attempt 2
void findMM (int *PMM, int *theG)
{
PMM [1] = 5;
theG [0] = 7;
}
int main()
{
int size;
int MM [2] = {1000, 0};
int *theG = NULL;
cout << "\nPlease insert size of array:" << endl;
cin >> size;
theG = new int [size];
findMM(MM, theG);
cout << MM [1] << endl << theG[0];
delete [] theG;
return 0;
}
The output would be 5 and 7 correct?
Since MM is an array, &MM is a pointer to an array (that's the type int (*)[2] that you see in the error). Instead, you seem to want to pass a pointer to the first element of the array. There are two ways to do that. Firstly, you can explicitly get the first element and then take the address of it: &MM[0]. Secondly, you can rely on array-to-pointer conversion to do it for you and just pass MM. Array-to-pointer conversion converts an array to a pointer to its first element.
I know this question has already been answered but I believe I can contribute to the asker's understanding.
Let's start with the basics:
void main()
{
int a = 2; // a is an int
cout << a << endl; // print 2
int *b; // b is a pointer-to-int
b = &a; // store the address of a in b
cout << *b << endl;// print the value that b points to, which is 2
int my_array = new int[3]; // allocate an array with 3 integers
my_array[0] = 50; // store 50 in the first element of the array
my_array[1] = 51; // store 51 in the second element of the array
my_array[2] = 52; // store 52 in the third element of the array
cout << c[0] << endl; // print 50
some_function(my_array, 3); // explained below
}
Now let's see how to pass arrays into functions. Assume we want to have a function called some_function that receives an array.
void some_function(int *some_array, int size_of_the_array)
{
// use the array however you like here
}
The function some_function receives a pointer to an int (also known as "pointer-to-int"). The name of an array is always the address of its first element, so if a function expects a pointer to an int and you give it the name of an array of ints, you are actually giving it the address of the first element in the array (this is just C++ syntax rules). So the function now has the address of the first element in the array, it can do stuff like *some_array to access the first element in the array, but what if it wants to access the other elements? It adds 1 to the pointer it already has and then applies the * operator to it: *(some_array + 1). Let's say an int is 4 bytes, if you add 1 to a pointer-to-int, the result of this addition is a new pointer that points to a location in memory 4 bytes ahead, so *(some_array + 93) is the value in the 94th element of the array some_array (array elements are stored sequentially in memory). A shorthand notation for this is some_array[93]. So if you have int *some_array = new int[100];, then some_array is a pointer and some_array[93] is the same as *(some_array + 93), which is the 94th element in the array.
The address itself though is not enough, you also need to know the number of entries in the array so that you don't try to access an element past the end of the array. In this example, assume that some_function simply prints the contents of the array, so if you don't provide 3 as the second argument to the function then it will have no way of knowing when to stop adding 1 to the pointer it received in the first argument. Beware, however, that by passing an array to a function this way, you are not passing the function a copy of the array, you are simply telling it where to find its contents in memory.

Pointers of two dimensional array

There is such code:
int (*ptr_)[1] = new int[1][1];
ptr_[0][0] = 100;
std::cout << "to: " << &ptr_ << ' ' << ptr_ << ' ' << *ptr_ << ' ' << &(*ptr_) << ' ' << **ptr_ << std::endl;
Result is:
to: 0xbfda6db4 0x9ee9028 0x9ee9028 0x9ee9028 100
Why values of ptr_ and *ptr_ are the same? Value of ptr_ equals to 0x9ee9028, so value of memory cell 0x9ee9028 is *ptr_ which is 0x9ee9028, however **ptr_ gives result 100. Is it logical?
ptr_ is a pointer to an array of length one. Variables of array type in C and C++ simply degrade to pointers when printed (among other things). So when you print ptr_ you get the address of the array. When you print *ptr_ you get the array itself, which then degrades right back into that same pointer again.
But in C++ please use smart pointers and standard containers.
int main() {
int test[2][3] = { {1,2,3}, {4, 5, 6} };
int (*pnt)[3] = test; //*pnt has type int[3]
//printArray writes array to stdout
printArray(3, *pnt); //returns 1 2 3
printArray(3, *(pnt+1)); //returns 4 5 6
return 0;
}
mutl-dimentional arrays are really arrays for arrays, for example test[2][3] is an array with two elements that are of type int[3] which in turn have 3 integer elements.
In your case you have a pointer to a pointer to a variable.
In other words your array looks like this:
array = {{100}}
ptr_ points to array
&ptr_ is the address of outer array
ptr_ is the address of first element (which is to another array)
*ptr_ same as above
&(*ptr_) gets first element of outer array which is the innter array, then returns the address of the innter array
**ptr_ gets first element of outer array (which is the inner array) then dereferences the innter array which is an actuall value