Unable to understand struct to char* conversion [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have defined a struct data and assigning it to a char*. However the size of strlen function always gives result as 1 and cout doesn't show anything. Here is my code:
struct data
{
int x;
int y;
};
int main()
{
data d;
d.x = 10;
d.y = 20;
char *ch = (char*)&d;
cout <<"Length:" strlen(ch) << endl;
cout << ch << endl;
}
The output is:
Length: 1
Please help me in understanding what's going on ?

The strlen function counts all bytes in the passed string until it finds the character '\0'. This character is the same as the integer 0.
So what the call to strlen is count the number of bytes until it finds a zero, and in your case the zero happens to be in the second byte of the structures binary representation, meaning that the "string length" is one.
The only thing that you can deduce from this is that you are on a little endian system. Other than that, the call is undefined behavior as the "string" isn't actually a string.

The reason it returns 1 is because you are treating the struct as a char array. Doing this you are re-interpreting the contents of the struct - the integer 10, which is probably stored in memory as 0x0A000000 - as a string. And that yields a length of 1 (only 1 non-zero value before a null-character in the array)

Even though you're trying to treat something as a string which isn't a string, if all you want to do is print out the values in the struct, you can do something like:
struct data
{
int x;
int y;
};
int main()
{
data d;
d.x = 10;
d.y = 20;
cout << "x is " << d.x << ", y is " << d.y << endl;
}
Why are you trying to treat that struct as a string?

Related

Using unsigned char array to store memory efficiently [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I was looking for an efficient way to store memory, so I realized that an unsigned char uses only one byte of memory. Thinking about it I made a small program that obtains the size of bytes of each variable.
int main() {
int myInt = 10;
long long myLongLong = 10;
unsigned char charArray1[] = { 10, 10, 10, 10 };
unsigned char charArray2[] = { 10, 10, 10, 10, 10, 10, 10, 10 };
std::cout << "Using sizeof () we get:" << std::endl;
std::cout << "myInt -> " << sizeof(myInt) << std::endl;
std::cout << "myLongLong -> " << sizeof(myLongLong) << std::endl;
std::cout << "charArray1 -> " << sizeof(charArray1) << std::endl;
std::cout << "charArray2 -> " << sizeof(charArray2) << std::endl;
return 0;
}
Output:
Using sizeof () we get:
myInt -> 4
myLongLong -> 8
charArray1 -> 4
charArray2 -> 8
Is it correct to say that I can store bytes in an unsigned char array? If correct, how can I get some matrix elements from unsigned char and assign them to a variable?
Example: If an integer occupies 4 bytes in memory, I can get 4 elements from the unsigned char array and assign it to an integer.
Is it correct to say that I can store bytes in an unsigned char array?
Yes.
If an integer occupies 4 bytes in memory, I can get 4 elements from the unsigned char array and assign it to an integer.
If and only if the array contains the bytes of the integer in the exact same format as the system uses natively, then you can do this:
static_assert(sizeof myInt == sizeof charArray1);
std::memcpy(&myInt, charArray1, sizeof myInt);
If the format isn't the same, then it is still possible to calculate the value as long as you know what the bytes represent.

Pointers c++. Difference between p and p* [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I don't understand what it is supposed to print when it says cout << x.
and also when it says if ( *x==*y) that means that the letters should be equal or the positions( well of the position is equal than the letter is too).
I don't understand what it is supposed to print when it says cout << x.
Since x is of type char*, it is treated like a null-terminated C string on printing. If you print a pointer into the middle of a string, the suffix of the string is printed:
const char *str = "ABCDEFG";
const char *ptr = str + 3;
cout << ptr; // prints DEFG
when it says if ( *x==*y) that means that the letters should be equal or the positions
* in this context means "the value pointed to by ...", i.e. the letters should be equal, not the positions.
When you say cout << x it's supposed to print out the whole char array. Let's say that char *x = "Something" . If you enter cout << x , the output will be: Something . The * sign is the dereference operator and it's used to dereference a pointer(in other words to get the value of the pointer). So if you have char *x = "Something" and char *y = "Some other thing" and if you want to compare the first characters of those char arrays,you would use if(*x == *y) . So dereferencing a char array gets the first char. cout << *x the output will be: S.

I am new to c++ why is casting working in first case but not in second cout after masking one of the characters in char* [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
why is casting working in the first case but not in second cout after masking one of the characters in char*
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int main()
{
int n = 10;
char* ch = (char*) calloc(6, sizeof(*ch));
ch = strdup("ab");
cout << strlen(ch) << endl;
int* p = (int*) ch;
cout << (char*)p << endl;// works fine it prints "ab"
*p = *p & 65280;
cout << "cast not working\t" << (char*)p << endl; // it does not work here
free(ch);
return 0;
}
Written as hex, 65280 is 0x0000FF00. So, on common systems with int being 4 bytes, you have set ch[0] to be 0. This is a null terminator, so when you try to print the string, you see an empty string.
Note: writing to *p causes undefined behaviour by writing past the end of the allocated area too; strdup("ab") allocates 3 bytes. On common systems this probably will have no ill effect as heap allocations are done in chunks of a certain size.

how to enter 2 chars in one comand in C++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
int main()
{
long long x,y,z,result;
char f,g;
cin >>x>>y>>z;
**result** =
cout << result ;
return 0;
}
How to make result = x (+ or - or / or *) y (+ or - or / or *) z !?
Reading the operators in between the numbers is simple:
long long x,y,z;
char f,g;
cin >>x>>f>>y>>g>>z;
// See what you've got
cout << x << " " << f << endl;
cout << y << " " << g << endl;
cout << z endl;
However, figuring out the result of the operation is trickier: you need to check the values you've got in f and g, and perform the operations as needed. Note that there must be no space between your numbers and the operators, otherwise the input would be processed incorrectly.
Demo.
This is probably at the core of the exercise that you are solving, so I will suggest that you write a function like this:
long long compute(long long a, long long b, char op) {
... // Check the operator, and return the result
}
With this function in hand, you can produce the result in one simple call:
long long result = compute(compute(x, y, f), z, g);
Once you write the compute function, this should give the result that you expect.
You can do cin>>astring. And separate the string by delimiter and convert them to integer.
For example:
1,2,3
will become '1','2','3'.

How to store a string into an an array? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to store this string into an an array.
space= 0
A,a =1
B, b =2
C , c = 3
.
.
Z, z= 26
string myArray[26] =
{ "A", "B", "C", "D",”E”,”F”,”G”,”H”,”I”,”J”,”K”,”L”,”M”,”N”,”O”,”P”,
”Q”,”R”,”S”,T”,”U”,”V”,W”,X”,”Y”, ”z” };
for (int i = 0; i < myArray; i++)
{
myArray[] = myArray[i]
cerr << myArray[i] << endl << endl;
}
Is that how to get each character with number?
What you've got is an array of strings, not an array of characters. A string is a container of characters, in the sense that it is capable of holding multiple characters. Your task can be solved with one or two strings, depending on your design preferences (see below).
A, a =1
B, b =2
You are placing two characters per position. However, strings cannot hold more than one character at a single index. If you need both the upper and lower case character to occupy the same spot, you need to make either two strings, or two spots.
Here is the first approach (two strings):
string upper = " ABCDEF...";
string lower = " abcdef...";
int pos = ...; // The desired position
cout << upper[pos] << endl;
cout << lower[pos] << endl;
Here is the second approach (two positions):
string pairs = " AaBbCcDdEeFf...";
int pos = ...; // The desired position
cout << pairs[2*pos] << endl; // Upper
cout << pairs[2*pos+1] << endl; // Lower