tags:

views:

81

answers:

4

I am using structs in my project in this way:

typedef struct
{
    int str1_val1;
    int str1_val2;
} struct1;

and

typedef struct
{
    int str2_val1;
    int str2_val2;
    struct1* str2_val3;
} struct2;

Is it possible that I hack this definition in a way, that I would use only types with my code, like

struct2* a;
a = (struct2*) malloc(sizeof(struct2));

without using keyword struct?

A: 

Yes, you can use the typedef'ed symbol without needing the struct keyword. The compiler simply uses that name as an alias for the structure you defined earlier.

One note on your example, malloc returns a pointer to memory. Hence your statement should read

a = (struct2 *)malloc(sizeof(struct2));
sizzzzlerz
I just fixed code and this is not the point.
ralu
No, it should read `a = malloc(sizeof *a);`.
R..
@ralu: So what is the point? This looks like the answer to the question you asked; what did you mean to ask?
David Thornley
+1  A: 

Yes, as follows:

struct _struct1
{
...
};
typedef struct _struct1 struct1;

struct _struct2
{
...
};
typedef struct _struct2 struct2;

...

struct2 *a;
a = (struct2*)malloc(sizeof(struct2));
slashmais
I got compile error at first line of next file
ralu
Perhaps it is a problem in the other file, then. Because this code looks correct.
Jonathan Sterling
I knew I got it, problem was in other h file declared just before this one same "wrong way"
ralu
That cast on the malloc is incorrect.
Steve S
Fixed - thanks @Steve S (Typo's the bain of my life).
slashmais
Get rid of the underscores in the struct tags. They're unnecessary and if misused can lead to errors.
R..
A: 

Just to share, I've seen this approach, and though I personally don't like it (I like everything named and tagged =P and I don't like using variable names in malloc), someone may.

typedef struct {
    ...
} *some_t;

int main() {
    some_t var = (some_t) malloc(sizeof(*var));
}
Santiago Lezica
<xxxx>_t names are reserved for the implemenation
pm100
A: 

as a footnote. If you code in C++ then you don't need to do the typedef; a struct is a type automatically.

pm100