This question already has answers here:
Why does Sizeof operator on a std::string yield unexpected result? [duplicate]
(3 answers)
Why is sizeof(std::string) only eight bytes?
(2 answers)
What is the proper size of std::string in C++? [duplicate]
(2 answers)
Closed 1 year ago.
I've been handed legacy code that I need to insert a new feature into... For the feature I am populating the message struct that was provided to me and then pack it into a vector. However I am running into issues where the data isn't making it all the way over in one piece. I know that my struct is causing the issue since when I so a sizeof(struct) I get an incorrect size.
struct fault
{
std::string n, d;
bool rec;
int sev;
std::vector diagData;
}
void MsgPack::pack(std::string n, std::string d, bool r, int s)
{
fault Msg;
fault.n = n;
fault.d = d;
fault.rec = r;
fault.sev = s;
std::size_t size = sizeof(fault); //ALWAYS returns 48 no matter how large strings are.
unsigned char* data;
memcpy(data, (const unsigned char*)&fault,size);
std::vector<char> p;
for(int i=0;i<size; i++)
{
p.push_back(data[i]);
}
sendMsg(p);
}
So I know there are several problems with this code, from the push_back, to the always returning 48... My questions are as follows:
I know that I can define the struct to contain chars that are predefined in size; however, the API call that I'm trying to make takes a string as an argument. I want to allow for the user to write anything that need/want and not box them in. Is there a way to keep the strings in the struct?
Is there a better way to do the push_back? I know that it iterating over 48 8byte chunks will either put too much or too little into the vector.
Just general coding practices and advice... Its been about 5yrs since I coded last so I am very rusty. I usually don't touch code so please go gentle on me :).
Related
This question already has answers here:
c++ sizeof( string )
(9 answers)
Closed 1 year ago.
When I run this code, result is always 24 regardless of what string is. Why?
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s = "asdccccc";
cout << sizeof(s);
return 0;
}
A string is an object. By using sizeof you are getting the size of the members of that object. One of those members is probably a pointer to the actual string contents, but the size of a pointer is constant no matter what it points to.
Consider this simple example
class string
{
const char* _ptr;
....
....
public:
}
When you write sizeof(string), you will get the size of the class, not the size of string literal _ptr points to.
This question already has answers here:
Array with size 0 [duplicate]
(4 answers)
What is the purpose of allocating a specific amount of memory for arrays in C++?
(5 answers)
Closed 5 years ago.
Im reading up for a exam in C++ and just fideling around in order to get a better sense of the language. My understanding is that arrays in c++ are defined with a fixed length either before run time or dynamically. Knowing this I don't understand why C++ accepts this. I wouldn't think that it would be possible to add element to an array of length 0;
int * TestArray = new int[0];
TestArray[0]=10;
TestArray[1]=20;
TestArray[2]=30;
Writing to array elements outside of the valid size is Undefined Behaviour. It's a bug and your program is ill formed. But the compiler is not required to issue a diagnostic (although most will with the right warning options).
It's your responsibility to follow the rules.
You may not access any elements in a zero sized array. It results in undefined runtime behavior.
However, zero sized arrays are allowed for various reasons.
First, it allows you to make functions less complicated by skipping size checks:
void f(size_t n)
{
int * ptr = new int[n];
//...
delete[] ptr;
}
instead of:
void f(size_t n)
{
if (n>0)
{
int * ptr = new int[n];
//...
delete[] ptr;
}
}
Second, the intent was to make it easy for compiler writers to implement new using malloc, and this is the defined behavior for malloc.
The GCC c compiler docs give this reason:
"Zero-length arrays are allowed in GNU C. They are very useful as the last element of a structure that is really a header for a variable-length object: "
struct line {
int length;
char contents[0];
};
struct line *thisline = (struct line *)
malloc (sizeof (struct line) + this_length);
thisline->length = this_length;
[without it], you would have to give contents a length of 1, which means either you waste space or complicate the argument to malloc.
My professor told me that because c++ and c can access and write outside of array bounds,it is one of the main reasons they are used to create operating systems. For example you can even do something like
arr[-1]=5;
I believe it is worth mentioning.However this can lead to undefined behavior.
This question already has answers here:
C++ : Creating an array with a size entered by the user
(3 answers)
Closed 3 years ago.
I am trying to get a user input and set it as the PUZZLESIZE which is used by int peg and row but am getting the expression must have a constant value.
How would I go about getting a user input and setting it as a global const that struct Board will recognize?
int a;
const int PIECE = a;
const int PUZZLESIZE = ((PUZZLESIZE *(PUZZLESIZE+1)) /2);
typedef struct Board {
int *row[PUZZLESIZE];
int peg[PIECE];
int lastmove;
struct Board *prevBoard;
int prow;
int pcol;
} Board;
int main()
{
scanf("%d",a);
}
Thanks for any help in advanced
Re-setting the value of a const variable at runtime is not possible.
You just defined PIECE as a const (constant variable):
const int PIECE = a;
So, you cannot change the value of PIECE after starting the program.
You have to rethink a little about how your program will work. In addition since you are using C++ you may consider the use of the language features and libraries so that you can follow best practices as recommended by #Joren.
You have 2 options:
Option 1 : Make PuzzleSize your largest supported puzzle.
If you do this all you need to do is validate the user input against this size.
In addition you don't have to fiddle with memory allocation.
Simple solution
Potentially can have large segments of unused memory
Option 2: Make row a double pointer and use new to allocate your rows.
typedef struct Board
{
int **row; // int *row[PUZZLESIZE];
....
}
once the user sets the input you can validate the input and do this
int main()
{
scanf("%d",a);
row = new int*[a]; }
Don't forget to take a look at your C++ book and read up on const, multidimensional arrays ,and new.
Good Luck!
This question already has answers here:
sizeof an array passed as function argument [duplicate]
(3 answers)
Why do C and C++ compilers allow array lengths in function signatures when they're never enforced?
(10 answers)
Closed 8 years ago.
int size(int arr1[])
{
int size1=sizeof(arr1)/sizeof(int);
cout<<size1<<endl;
return size1;
}
void main()
{
int b[]={1,2,3,4,5};
int size2 = size(b);
cout<<size2<<endl;
for (int i=0;i<size2;i++)
{
cout<<b[i];
}
}
I have put the b[] function into size() and check the size then return value.
however, it just return 1 as the answer.
Can anyone please help me to solve this.
A beginner of C++
sizeof(arr1) in the function returns the size of a pointer, not of the whole array.
That´s just how the language is.
You´ve to determine the array size without sizeof:
Either pass a second parameter with the number, or fill the array in a way
you can find the end because a certain value is there (and nowhere else)
This question already has answers here:
When a function has a specific-size array parameter, why is it replaced with a pointer?
(3 answers)
sizeof(array) / sizeof(int) [duplicate]
(2 answers)
Closed 9 years ago.
I have written a function size which takes integer array as an argument.
int length(int a[])
{
return sizeof(a)/sizeof(int);
}
int main()
{
int a[] = {1,3,5,6,9,4,2,1,0,0};
int len = sizeof(a)/sizeof(int);
cout << len; // This correctly prints 10 .
len = size(a);
cout << len; // But this print 2 .why ??
return 0;
}
Can someone explain me this behaviour?
Thanks.
The reason you get 2 is because sizeof(int *) is twice as large as sizeof(int), and arrays decay into pointers when passed into a function.
There are various ways to work around this. In C++, you could use a std::vector<int> a = { ... }; instead, which would solve the problem (by calling the a.size() to get the size, as sizeof(a) wouldn't work).
Because sizeof(a) is returning the size of the pointer which will be either 4 bytes or 8 bytes depending upon whether your app is 32-bit or 64-bit. So you would need to maintain the length of your array using a separate variable.
Or, better still, I would recommend using one of the standard collection classes, like std::vector for example since this will maintain the length automatically.