I want to be able to do something like this:
typedef struct
{
char* c_str;
} string;
string s = "hello";
Is it possible to do that in any way?
I know that it is possible to do this:
typedef struct
{
char* c_str;
} string;
string s = { "hello" };
But I do not like the curly brackets when it is only one member variable.
A structure data type can be used within a program in the same way that a simple data type can be used to instantiate data objects. In particular the elements of an array can each store a complete structure object. An object capable of storing data.
A data structure is a collection of different forms and different types of data that has a set of specific operations that can be performed. It is a collection of data types. It is a way of organizing the items in terms of memory, and also the way of accessing each item through some defined logic.
Structs may be passed to and from functions just like any basic data types. Individual structs are always passed by value, even if they contain arrays. Arrays of structs are passed by pointer / address, just like any other array, even if they only contain a single value.
A structure is a key word that create user defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type.
You could use a typedef
instead of a struct
:
typedef char* string;
string s = "hello";
But then const string
would make the pointer const, and not the pointed-to data. So const string s
is equivalent to char* const s
. A solution may be to define an additional type for const strings:
typedef char* string;
typedef const char* const_string;
For the original struct, the same is true. (C++ has the same "problem", which is why it has iterator
and const_iterator
in its container types.)
An advantage of a typedef for a pointer type is that you can type
string s1, s2, s3;
instead of
char *s1, *s2, *s3;
In C, it is not possible, but you can do it in C++ if you add constructor that takes one appropriate parameter. Compiler will do the rest. You can mark the constructor as explicit if you want to avoid this implicit conversion behaviour.
In C++:
struct string {
char * m_c_str;
/* explicit */ string(char* c_str) : m_c_str(c_str) { }
};
int main(int argc, char * argv[]) {
string s = "hello";
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With