Converting an integer to Char Pointer using C - c++

I am trying to convert an integer to a char pointer as shown below. The data results are different. I am not sure what is going wrong. Please help me in correcting the code.
int main(){
char *key1 = "/introduction";
std::ostringstream str1;
str1<< 10;
std::string data=str1.str();
std::cout <<"The data value="<<data<<std::endl; // The data value= 10
char *intro= new char[data.length()+1];
strcpy(intro, data.c_str());
std::cout <<"The data value="<<*intro <<std::endl; // The data value=1
return 0;
}
I am not sure why two data value are printed different i.e, 10 and 1.

In C++, when trying to print all the contents of a char * with cout, you should pass the pointer, i.e. cout << intro << endl.
What you've done here is dereferenced the char *, so cout << *intro << endl is equivalent to cout << intro[0] << endl, which is equivalent to printing the first character, 1.

Related

Pointer printing first char of string

#include <iostream>
using namespace std;
char* input(char **S);
int main()
{
char **S = new char *;
char *K = input(S);
//cout << K << endl;
cout << *K << endl;
}
char* input(char **S)
{
cout << "Enter string: ";
cin >> *S;
cout << S << endl; // Prints address of S
cout << *S << endl; //Prints content of address stored in S
return *S;
}
I am failing to understand why when I print out *K, I just get the first character of the input string but if I print out the commented line(just K alone) I get the whole string. Any help with explaining what I am not able to see or understand is appreciated.
Let's understand how arrays work:
// Let's say I have one character array
char arr[] = {'a', 'b', 'c', 'd'};
In here, the name of the array i.e. arr acts as the pointer to the first element of the array. However, do note that it is NOT the pointer to the first element to avoid confusion, it just have an implicit conversion to pointer of element type. More details can be found here: https://stackoverflow.com/a/1641963/10821123
Now since array is contiguous, the rest of the elements can be determined.
// so ideally, the below two statements would print the same thing
cout << &arr << endl;
cout << (void*) &arr[0] << endl;
// the above line just takes out the address of the first pointer
Now coming to your question, I'll convert my example to a string one:
char *K = "abc";
cout << *K << endl; // a
cout << K << endl; // abc
Note that the above assignment of char *K = "abc"; will give you a warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
The pointer only holds the address of the first element of the array, so when you dereference the pointer, it prints the first element, i.e. *K is interpreted as K[0]
Now there's an overload of operator <<, so what it does is if it sees a character pointer i.e. char*, it prints the complete null-terminated string, that's why in your case too, it is printing the whole string.

Strange symbols printing in C++ instead of array content [duplicate]

I am working on below code:
#include<iostream>
#include<stdio.h>
using namespace std;
main() {
unsigned char a;
a=1;
printf("%d", a);
cout<<a;
}
It is printing 1 and some garbage.
Why cout is behaving so?
cout << a is printing a value which appears to be garbage to you. It is not garbage actually. It is just a non-printable ASCII character which is getting printed anyway. Note that ASCII character corresponding to 1 is non-printable. You can check whether a is printable or not using, std::isprint as:
std::cout << std::isprint(a) << std::endl;
It will print 0 (read: false) indicating the character is non-printable
--
Anyway, if you want your cout to print 1 also, then cast a to this:
cout << static_cast<unsigned>(a) << std::endl;
I had a similar issue here that I've long forgotten about. The resolution to this problem with iostream's cout can be done like this:
#include<iostream>
#include<stdio.h>
main() {
unsigned char a;
a=1;
printf("%d", a);
std::cout<< +a << std::endl;
return 0;
}
instead of casting it back to another type if you want cout to print the unsigned char value as opposed to the ascii character. You need to promote it.
If you noticed all I did was add a + before the unsigned char. This is unary addition that will promote the unsigned char to give you the actual number representation.
User Baum mit Augen is responsible for reminding me of this solution.
You need to typecast a as integer as cout<< (int)(a);. With this you will observe 1 on the output. With cout << a;, the print will be SOH (Start of Heading) corresponding to ascii value of 1 which can't be printed and hence, some special character is observed.
EDIT:
To be more accurate, the cout statement should be cout << static_cast<unsigned>(a) as Nawaz has mentioned.
The C compiler has its own way of defining the type of the printed output, because you can specify the type of the output.
Ex:
uint8_t c = 100;
printf("%d",c);
so you can also print c as an int by %d, or char %c, string %s or a hex value %x.
Where C++ has its own way too, the cout prints the 8-bit values as a char by default. So, you have to use specifiers with the output argument.
You can either use:
a + before the name of the output argument
uint8_t data_byte = 100;
cout << "val: " << +data_byte << endl;
use a function cast unsigned(var); like,
uint8_t data_byte = 100;
cout << "val: " << unsigned(data_byte) << endl;
printf("%u",a);
its so simple try it

The sizeof several casts

Why does the function sizeof not return the same size when its getting used on the struct itself?
I need to cast it because of a winsock program that im working on.
Thanks for any help, true.
#include <iostream>
#include <string>
using namespace std;
struct stringstruct
{
string s1;
string s2;
};
int main()
{
stringstruct ss = {"123","abc"};
char *NX = (char*)&ss;
cout << sizeof(NX) << endl << sizeof(*NX) << endl;
cout << sizeof(&ss) << endl << sizeof(ss) << endl;
getchar();
return 0;
}
the example above outputs
4
1
4
64
sizeof will tell you the size of the given expression's type. In both the sizeof(NX) and sizeof(&ss), the result is 4 because pointers on your machine take up 4 bytes. For sizeof(*NX), you are dereferencing a char*, which gives you a char, and a char takes up 1 byte (and always does), so you get the output 1. When you do sizeof(ss), ss is a stringstruct, so you get the size of a stringstruct, which appears to be 64 bytes.
stringstruct ss = {"123","abc"};
char *NX = (char*)&ss;
cout << sizeof(NX) << endl << sizeof(*NX) << endl;
cout << sizeof(&ss) << endl << sizeof(ss) << endl;
I'm pretty sure that any of these casts are pretty meaningless. NX will point at the beginning of your struct. Inside the struct are two objects of type string, which in turn have pointers pointing to the data they were initialized with "123" and "abc" respectively. sizeof(*NX) is just that - size of a char, and sizeof(NX) is indeed the size of a pointer. sizeof(ss) is the size of your two string members (and any padding added by the compiler) - and sizeof(&ss) is the size of a pointer to a stringstruct.
Now, I expect what you REALLY want is a way to send your data, "123" and "abc" as two separate strings over a network. None of the above will help you do that, since even if sizeof(ss) gives you the size of the data structure you want to send, the string values are not within that structure [1]. What you really need is something calls serialization - something that writes out your strings as separate elements as text/string.
Something like this would work:
struct stringstruct {
string s1;
string s2;
string to_string()
}
string stringstruct::to_string()
{
string res = s1 + " " + s2;
return res;
}
Then use to_string like this:
string temp = ss.to_string();
const char *to_send = temp.c_str();
int send_len = temp.length();
... send the string `to_send` with number of bytes `send_len`.
[1] There is an optimization where std::string is actually storing short strings within the actual class itself. But given a sufficiently long strong, it won't do that.
A pointer is of size 4(in your case seems to be 32 bit) no matter what it points. Size of the object itself on the other hand returns the real number of bytes that an object of that structure takes.

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)

cout not printing unsigned char

I am working on below code:
#include<iostream>
#include<stdio.h>
using namespace std;
main() {
unsigned char a;
a=1;
printf("%d", a);
cout<<a;
}
It is printing 1 and some garbage.
Why cout is behaving so?
cout << a is printing a value which appears to be garbage to you. It is not garbage actually. It is just a non-printable ASCII character which is getting printed anyway. Note that ASCII character corresponding to 1 is non-printable. You can check whether a is printable or not using, std::isprint as:
std::cout << std::isprint(a) << std::endl;
It will print 0 (read: false) indicating the character is non-printable
--
Anyway, if you want your cout to print 1 also, then cast a to this:
cout << static_cast<unsigned>(a) << std::endl;
I had a similar issue here that I've long forgotten about. The resolution to this problem with iostream's cout can be done like this:
#include<iostream>
#include<stdio.h>
main() {
unsigned char a;
a=1;
printf("%d", a);
std::cout<< +a << std::endl;
return 0;
}
instead of casting it back to another type if you want cout to print the unsigned char value as opposed to the ascii character. You need to promote it.
If you noticed all I did was add a + before the unsigned char. This is unary addition that will promote the unsigned char to give you the actual number representation.
User Baum mit Augen is responsible for reminding me of this solution.
You need to typecast a as integer as cout<< (int)(a);. With this you will observe 1 on the output. With cout << a;, the print will be SOH (Start of Heading) corresponding to ascii value of 1 which can't be printed and hence, some special character is observed.
EDIT:
To be more accurate, the cout statement should be cout << static_cast<unsigned>(a) as Nawaz has mentioned.
The C compiler has its own way of defining the type of the printed output, because you can specify the type of the output.
Ex:
uint8_t c = 100;
printf("%d",c);
so you can also print c as an int by %d, or char %c, string %s or a hex value %x.
Where C++ has its own way too, the cout prints the 8-bit values as a char by default. So, you have to use specifiers with the output argument.
You can either use:
a + before the name of the output argument
uint8_t data_byte = 100;
cout << "val: " << +data_byte << endl;
use a function cast unsigned(var); like,
uint8_t data_byte = 100;
cout << "val: " << unsigned(data_byte) << endl;
printf("%u",a);
its so simple try it