Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C structure as a data type

Tags:

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.

like image 971
Erik W Avatar asked Apr 25 '15 15:04

Erik W


People also ask

Can structure used as data type?

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.

Is structure a data type or data structure?

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.

Is struct a valid data type?

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.

Why we use struct data type?

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.


2 Answers

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;
like image 199
tmlen Avatar answered Oct 13 '22 05:10

tmlen


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;

}
like image 30
Krab Avatar answered Oct 13 '22 07:10

Krab