Difference between result of character and integer pointer - c++

I was trying to execute the following code:
#include <iostream>
using namespace std;
int main()
{
int arr[4] = {1,2,3,4};
int *p;
p = arr;
cout << "p=" << p << endl;
char ch3[4] = {'c','d','e'};
char *ptr;
ptr = ch3;
cout << ptr << endl;
getchar();
return 0;
}
When I print the pointer p, it prints the address of the array 'arr' which is stored in it, whereas when I print the pointer ptr, it prints the array ch3 and not the address of it.
I wanted to know why is this happening.

Because operator<< is overloaded for const char* - that overload prints the char array located at that address.
To see the address itself, you'll need to cast it to void*:
cout<<static_cast<void*>(ptr)<<endl;

Related

Accessing a pointer to integer within a pointer to structure

I am having a difficult time trying to access *testscores from *stPtr.
#include <iostream>
using namespace std;
struct GradeInfo{
char name;
int *testscores;
double average;
};
int main(int argc, char *argv[]) {
GradeInfo var;
*var.testscores = 10;
cout << *var.testscores;
GradeInfo *stPtr = &var;
// This line of code breaks my test program
cout << stPtr->testscores;
return 0;
}
I would sincerely appreciate it if you could help me access the pointer to integer variable within the pointer to structure variable I have declared.
You should first allocate space for it to store actual data:
*var.testscores = new int[5];
The you can access it:
var.testscores[3] = 100;
Note the -> operator does not dereference the member. You should add an extra asterisk or use brackets:
cout << *stPtr->testscores;
cout << stPtr->testscores[3];
Should be OK by then.
Your pointer is not initialized. Either initialize it with new or, better, use smart pointers such as unique_ptr which will handle deletion of your data automatically.
You this code below. You haven't allocated memory for integer pointer.
Note: Don't forget to release the allocated memory with new.
#include <iostream>
using namespace std;
struct GradeInfo{
char name;
int *testscores;
double average;
};
int main(int argc, char *argv[]) {
GradeInfo var;
var.testscores = new int(10);
cout << *var.testscores << endl;
GradeInfo *stPtr = &var;
cout << *(stPtr->testscores) << endl;
delete(var.testscores);
return 0;
}

difference between char and const char

# include <iostream>
# include <string.h>
using namespace std;
int main()
{
int a=10;
int b=20;
char op[10];
const char p='+';
cout<<"enter the operation"<<endl;
cin>>op;
if(!strcmp(op,p)==0)
{
cout<<a+b;
}
return 0;
}
compilation result
12 17 C:\Users\DELL\Documents\cac.cpp [Error] invalid conversion from 'char' to 'const char*' [-fpermissive]
I am a beginner. Please tell me what mistake have I done.
This isn't about the difference between char and const char, but between char [] and char.
strcmp expects two character arrays.
op is an array of (10) characters. Good: that's what strcmp expects.
p is a single character. Not good: strcmp needs a char array, and p isn't any kind of array, but a single character.
You can change p from a single char '+' to a char array "+", or compare only the 0th character of op, as suggested in a comment above.
there is no version of strcmp that takes a single character as a parameter but instead it takes two string and compares them.
if you want to compare a single char variable with a string you can compare it with the first element of string or with any other element:
#include <iostream>
#include <string>
int main()
{
char op[10] = "Hi";
const char p = '+';
// if( strcmp( op, p) ) // error cannot covert parameter 2 from char to const char*
// cout << "op and p are identic" << std::endl;
// else
// std::cout << "op and b are not identic" << std::endl;
if(op[0] == p)
std::cout << "op[0] and p are identic" << std::endl;
else
std::cout << "op[0] and p are not identic" << std::endl;
const char* const pStr = "Bye"; //constant pointer to constant character string: pStr cannot change neither the address nor the value in address
const char* const pStr2 = "bye"; // the same as above
// pStr++; //error
// pStr[0]++; // error
if( !strcmp( pStr, pStr2) )
std::cout << "pStr and pStr2 are identic" << std::endl;
else
std::cout << "pStr and pStr2 are Not identic" << std::endl;
return 0;
}

Constant pointer modified in function

I tried compiling this code being absolutely sure it won't compile since I try to modify the address to a const pointer (int p[100]), but the code compiled and run perfectly. Can anyone explain to me why this worked?
#include <iostream>
using namespace std;
int bar1(int *p){ cout << p << " "; p++; cout << p << "\n"; return 0; }
int bar2(int p[100]){ cout << p << " "; p++; cout << p; return 0; }
int arr1[100];
int arr2[100];
int main(){
bar1(arr1);
bar2(arr2);
}
I compiled this in Visual Studio 2013 the output was:
3f320 3f324
3f4B0 3f4B4
I try to modify the address to a const pointer (int p[100])
That's not a const pointer. As a function parameter, it's equivalent to int * p.
A const pointer looks like int * const p, and your code will give the expected compile error if you use that.

C++. Error: void is not a pointer-to-object type

I have a C++ program:
struct arguments
{
int a, b, c;
arguments(): a(3), b(6), c(9) {}
};
class test_class{
public:
void *member_func(void *args){
arguments vars = (arguments *) (*args); //error: void is not a
//pointer-to-object type
std::cout << "\n" << vars.a << "\t" << vars.b << "\t" << vars.c << "\n";
}
};
On compile it throws an error:
error: ‘void*’ is not a pointer-to-object type
Can someone explain what I am doing wrong to produce this error?
You are dereferencing the void * before casting it to a concrete type. You need to do it the other way around:
arguments vars = *(arguments *) (args);
This order is important, because the compiler doesn't know how to apply * to args (which is a void * and can't be dereferenced). Your (arguments *) tells it what to do, but it's too late, because the dereference has already occurred.
Bare bones example to reproduce the above error:
#include <iostream>
using namespace std;
int main() {
int myint = 9; //good
void *pointer_to_void; //good
pointer_to_void = &myint; //good
cout << *pointer_to_void; //error: 'void*' is not a pointer-to-object type
}
The above code is wrong because it is trying to dereference a pointer to a void. That's not allowed.
Now run the next code below, If you understand why the following code runs and the above code does not, you will be better equipped to understand what is going on under the hood.
#include <iostream>
using namespace std;
int main() {
int myint = 9;
void *pointer_to_void;
int *pointer_to_int;
pointer_to_void = &myint;
pointer_to_int = (int *) pointer_to_void;
cout << *pointer_to_int; //prints '9'
return 0;
}
You have the * in the wrong place. So you're trying dereference the void*.
Try this instead:
arguments vars = *(arguments *) (args);
std::cout << "\n" << vars.a << "\t" << vars.b << "\t" << vars.c << "\n";
Alternatively, you can do this: (which also avoids the copy-constructor - as mentioned in the comments)
arguments *vars = (arguments *) (args);
std::cout << "\n" << vars->a << "\t" << vars->b << "\t" << vars->c << "\n";
The problem as bdonlan said is "dereferencing void* before casting".
I think this example would help:
#include <iostream>
using namespace std;
int main()
{
void *sad;
int s = 23;
float d = 5.8;
sad = &s;
cout << *(int*) sad;//outputs 23//wrong: cout << *sad ;//wrong: cout << (int*) *sad;
sad = &d;
cout << *(float *) sad;//outputs 5.8//wrong: cout << *sad ;//wrong: cout << (float*) *sad;
return 0;
}
*args means "the object(value) args points to". Therefore, it can not be casted as pointer to object(argument). That's why it is giving error
The problem above there is that you are trying to deference a void pointer which is not allowed in C or C++.
However, this still works:
#include <iostream>
using namespace std;
int main()
{
int b=10;
void *a=&b;
int *ptr=(int*)a;
cout<<*ptr;;
}
We can deference int* pointers after casting void pointers to int* pointers.

how to store the content of variable into const char*?

i have a pointer or variable which stores the address like 0xb72b218 now i have to store this value in to const char*. how i can store it. Thanks in advance.
I tried following:
suppose i have a pointer variable "ptr" which contains 0xb72b218 value
ostringstream oss;
oss << ptr;
string buf = oss.str();
const char* value = buf.c_str();
but it is more complicated any one know easy way.
Well... if you really want the address of something in a string, this will do:
#include <stdio.h>
#include <iostream>
int main(){
char buf[30];
void* ptr = /*your pointer here*/;
snprintf(buf,sizeof(buf),"%p",ptr);
std::cout << "pointer as string: " << buf << "\n";
std::cout << "pointer as value: " << ptr << "\n";
}
Or if you don't like magic numbers and want your code to work even when 256bit pointers are nothing special anymore, try this:
#include <limits> // for numeric_limits<T>
#include <stdint.h> // for intptr_t
#include <stdio.h> // for snprintf
#include <iostream>
int main(){
int i;
int* ptr = &i; // replace with your pointer
const int N = std::numeric_limits<intptr_t>::digits;
char buf[N+1]; // +1 for '\0' terminator
snprintf(buf,N,"%p",ptr);
std::cout << "pointer as string: " << buf << "\n";
std::cout << "pointer as value: " << static_cast<void*>(ptr) << "\n";
}
Example on Ideone.
OK, presumably there must some additional parameter that tells the function what type of data is actually being passed, but you can do it like this:
extern void afunc(const char *p, int type);
int value = 1234;
afunc((const char *)&value, TYPE_INT);
Have you looked at const_cast? It is a means of adding/removing const-ness from a variable in C++. Take a look here.