I'm missing something simple here (run-time execution precedence?) - c++

Execution of this simple code:
int foo(int* a){
cout <<"a="<<a;
*a=1;
cout <<", *a="<<*a<<endl;
return 0;}
int main () {
int* ptr;
ptr=new int[2];
ptr[0]=0;
ptr[1]=0;
cout<< foo(ptr) <<" "<< ptr <<" *ptr="<< *ptr <<endl;
cout<< foo(ptr) <<" "<< ptr <<" *ptr="<< *ptr <<endl;
return 0;}
Leads to (linux):
a=0x939f008, *a=1
0 0x939f008 *ptr=0
a=0x939f008, *a=1
0 0x939f008 *ptr=1
Please explain why *ptr=0 in the second line, but not in the fourth; could it be, that "things" are "fetched" to cout from right to left? Than - how does it really work (step-by-step at runtime)?

The order of evaluation of arguments to a function is Unspecified as per the C++ Standard.
It may be:
Left to Right or
Right to Left or
Any other order
One of my previous answer here, explains this in depth and detail.

Related

Entering value to dynamically allocated memory at runtime

Following is the code I wrote for reading a value at run time to dynamically allocated memory:
void main()
{
clrscr();
int *p = new int[5];
int *a = new int();
cin >> *a; // **line 5**
cout << *a << "\n"; // **line 6**
cout << &p; // line 7
cout << *p; // line 8
cout << "\nEnter 5 no for array\n";
for (int i = 0; i <= 4; i++)
{
cout << &p[i] << " :- ";
cin >> p[i]; // LINE 12
}
for (i = 0; i <= 4; i++)
cout << "\n" << p[i]; // LINE 16
delete[] p;
delete a;
getch();
}
I would like to know that while entering data for user in integer, we have to use *a with cin and cout for entering data in line 5 & 6 but in case of array we just gave the pointer variable name in line 12 & 16. Can anyone please tell me why we are having this difference?
Moreover can anyone also please tell me the difference between output of line 7 & 8.
You don't "have to"; you could have written cin >> a[0].
For built-in types and pointers and such, a[b] is *(a+b) is *(b+a) is b[a] and you can interchange them all.
It's only convention that leads to a choice. Like generally if you'd allocated more than one int you'd use "array notation" (a[i]) and if you'd allocated only one int you'd use a straight-up dereference (*(a+0), or *a).
But the language doesn't really care how many elements you allocated because either way you just have a pointer to "one or more" consecutive elements.
tl;dr this is just how the syntax was designed.
As for your second question, &p and *p give different results because they mean different things, and I'll leave discerning that difference as an exercise to the reader.

Pointer increment answer not understood

I have been trying for such code
#include <iostream>
using namespace std;
int main()
{
int t=1;
cout<<t<<" ";
int *b = new int(t);
cout<<*b++<<" ";
cout <<*b<<" ";
cout<<t<<" ";
return 0;
}
It is giving me output as 1 1 0 1. I cant understand 0 in the output. Please explain me why this is happening ?
The precedence of the ++ operator is higher than that of the * operator in this case. You are thus incrementing the pointer b itself rather than the memory being pointed to (which is presumably your intention).
To get the behaviour you want:
cout<<(*b)++<<" ";
After the line
cout << *b++ << " ";
b points to memory beyond what was allocated.
The line after that,
cout << *b << " ";
dereferences memory beyond valid limits. Hence, it is cause for undefined behavior.

C++ program only lists last value entered into an array

I am trying to output the values present in the array, that are accepted during runtime, onto the console. But when I run this program I get the 5 values in the array as the last value only.
For example: if i give 0 1 2 3 4 as the five values for this program then the output is shown as 4 4 4 4 4.
#include "stdafx.h"
#include<iostream>
using namespace std;
int main()
{
int arrsize = 5;
int *ptr = new int[arrsize];
*ptr = 7;
cout << *ptr << endl;
cout << "enter 5 values:";
for (int i = 0; i < arrsize; i++)
{
cin >> *ptr;
cin.get();
}
cout << "the values in the array are:\n ";
for (int i = 0; i < arrsize; i++)
{
cout << *ptr << " ";
}
delete[] ptr;
cin.get();
return 0;
}
Both of your loops:
for (int i = 0; i < arrsize; i++)
...
loop over a variable i that is never used inside the loop. You are always using *ptr which refers always to the first element of the dynamically allocated array. You should use ptr[i] instead.
A part from that, dynamic allocation is an advanced topic. I'd recommend sticking with simpler and more commonly used things first:
std::cout << "Enter values:";
std::vector<int> array(std::istream_iterator<int>(std::cin), {});
std::cout << "\nThe values in the array are:\n";
std::copy(begin(array), end(array), std::ostream_iterator<int>(std::cout, " "));
Live demo
Following issues I think you could tackle:
The first include can be omitted I think. Your code works without that.
You use cin.get(), not sure why you need that. I think you can remove that. Even the one at the very end. You could put a cout << endl for the last newline. I am using Linux.
And use ptr like an array with index: ptr[i] in the loops as mentioned in the other answer. ptr[i] is equivalent to *(ptr+i). You have to offset it, otherwise you're overwriting the same value (that is why you get that result), because ptr points to the first element of the array.
P.S.: It seems that if you're using Windows (or other systems) you need the cin.get() to avoid the console to close down or so. So maybe you'd need to check it. See comments below.

Pointers & converting a char array to an int

I am doing some exercises to figure out how to access values in an array after they are changed with pointers. Can someone point out why the first output does not show the desired output? I am trying to get both cout to print 1234, one by using the new pointer and one by using the position in the array
int main()
{
char myArray[50]={0};
short* sizeOfAlloc=(short*)(myArray+5);
*sizeOfAlloc=1234;
cout << (short*)(myArray+5) <<endl;
cout << *sizeOfAlloc <<endl;
system("pause");
}
cout << (short*)(myArray+5) <<endl;
Prints the pointer. Not the value pointed by it.
cout << *((short*)(myArray+5)) <<endl;
^^ ^^
Will print the value pointed to by (short*)(myArray+5)

Strcmp does not behave as expected, Returns 0 when comparing two unequal strings

I am having understanding a weird behavior of strcmp function, which will be illustrated by the following code:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char *p = "no";
cout << p << endl; //Output: no
cout << &p << endl; //Output: 0x28ac64
cout << strlen(p) << endl; //Output: 2
cout << strcmp(p, "no") << endl; //Output: 0
cin >> p; //Input: bo
cout << p << endl; //Output: bo
cout << &p << endl; //Output: 0x28ac64
cout << strlen(p) << endl; //Output: 2
cout << strcmp(p, "no") << endl; //Output: 0
return 0;
}
What I fail to understand is why the output of line 15 is 0. 0 means the two strings are equal, which is clearly not the case. What am I missing here?
P.S. I do apologize for the escape characters in the headers, but I could not get iostream to display if I removed it. Though I am posting this, I will figure out how to get it right for next time. :)
The problem is that p points to a string literal, therefore your attempt to modify the string literal with cin >> p; leads directly to undefined behavior.
What's most likely happening is that the compiler is treating the string literal as constant (since you're not supposed to modify it) and therefore, (at compile time) determining what the result from strcmp should be, and producing that. The fact that you're modifying it at run-time is ignored, because you're not supposed to do that anyway.
Unfortunately for compatibility many compilers support this:
char *p = "no";
Which should fail to compile and correct one is:
const char *p = "no";
If you fix that (and you should get at least warning), you would see what is the issue with following compile errors.
p is pointing to the first element of an array of const char. Attempting to modify these values (as you do in cin >> p) invokes undefined behaviour.