Let's define this struct:
struct MyStruct {
int firstInt;
int secondInt;
char * firstString;
char * secondString;
};
I'm trying to initialize a struct like this:
MyStruct s = {4, 5, {'a', 'b', 'c'}, "abc"};
But it's not working. Is there any way to do it? (the firstString is required not to have '\\0' at the end)
Since your requirement is to not have a null terminator at the end, you have to use an array for firstString
:
struct MyStruct {
int firstInt;
int secondInt;
char firstString[3];
char * secondString;
};
Then you can initialize it like this:
MyStruct s = {4, 5, {'a', 'b', 'c'}, "abc"};
You cannot initialize a char*
with {'a', 'b', 'c'}
because you have to provide storage for the characters, a char*
is only able to point at something. "abc"
happens to be a constant string literal which is stored in read only memory, so you are able to make the char*
point at that.
Also, in C++, "abc"
is a constant which cannot me modified, so you should change char * secondString;
to const char * secondString;
.
You can use a compound literal for this:
struct MyStruct {
int firstInt;
int secondInt;
char * firstString;
char * secondString;
};
struct MyStruct s = { 4, 5, (char[]){'a', 'b', 'c'}, "abc" };
This construct was introduced in C99; see section 6.5.2.5 of the N1256 draft . Some compilers (particularly Microsoft's) may not support it.
Note that in C, the type struct MyStruct
cannot be referred to as just MyStruct
; this is a difference between C and C++. Make sure you're compiling the language you think you are.
One thing to watch out for is the lifetime of the object associated with a compound literal. String literals denote array objects with static lifetime, ie, the object exists for the entire execution of the program. The array object associated with (char[]){'a', 'b', 'c'}
has static storage duration if it occurs outside the body of a function, but automatic storage duration (associated with the innermost enclosing block) if it occurs in side the body of the function. This could be a problem if you tried to pass a copy of s
outside the block in which it's defined.
A subtle point arises. Your struct has two char *
but has no storage to back these pointers up. You probably want something like this:
struct MyStruct {
int firstInt;
int secondInt;
char firstString[3];
char secondString[4];
};
#include <iostream>
using namespace std;
struct MyStruct {
int firstInt;
int secondInt;
char * firstString;
char * secondString;
};
int main()
{
char arr[] = {'a', 'b', 'c','\0'};
MyStruct s = {4, 5, arr, "abc"};
cout << s.firstString << endl;
return 0;
}
MyStruct s = {4, 5, {'a', 'b', 'c'}, "abc"};
{'a', 'b', 'c'} have no memory to store.It's a r-value.
——I think. ^-^
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.