1

I have a code like this in C:

typedef struct _a1{
  int d1;
} a1, *pa1;

I can create another pointer and use it like:

a1 *pa2 = NULL;
pa2 = (a1*)malloc(sizeof(a1));

Trying the same for "pa1" fails. How do I use pointer "pa1"?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user915783
  • 689
  • 1
  • 9
  • 27
  • For a start is there a problem with the space bar?. Number 2 you do not need to cast malloc as it is bad. – Ed Heal Jan 03 '17 at 20:37
  • @EdHeal on some compilers with the non-permissive flag you can't compile without a cast. – kabanus Jan 03 '17 at 20:49
  • 2
    See [Is it a good idea to `typedef` pointers?](https://stackoverflow.com/questions/750178/is-it-a-good-idea-to-typedef-pointers) — short answer "No", but that's what you're doing, whether you realized it or not. – Jonathan Leffler Jan 03 '17 at 20:51
  • 2
    @kabanus: Only C++ compilers (perhaps those masquerading as C compilers) object to the absence of a cast. This might be more of a problem on Windows with MS Visual Studio than on most other platforms. – Jonathan Leffler Jan 03 '17 at 20:52
  • @JonathanLeffler Thanks. I assumed a such, but this happens commonly enough for so I just skip these 'details', though your right. – kabanus Jan 03 '17 at 20:54

1 Answers1

3

In case it's not clear, pa1 is not a pointer to an a1 struct. What you're doing with the typedef is just defining two types - one a type that is pointer to your struct (p1=a1*), and one the struct itself (a1). For me this works without a problem:

#include <stdio.h>
#include <stdlib.h>

typedef struct _a1{
    int d1;
} a1, *p1;

int main() {
    p1 p2 = NULL;
    p2 = (p1)malloc(sizeof(a1));
    printf("%p\n",p2);
    return 0;
}

And I suggest reading Is it a good idea to typedef pointers? — I wholeheartedly agree.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
kabanus
  • 24,623
  • 6
  • 41
  • 74
  • 1
    It matters. Showing people C++ code for a C question confuses people learning C and using a real C compiler. Actually, it also confuses those who are learning C and using a C++ compiler. C and C++ are two very different languages. You should essentially never write C++ code in an answer to a C question on SO. – Jonathan Leffler Jan 03 '17 at 20:54
  • Thanks guys. I had never seen this format , so although I kind of guessed its usage but confirmation like above is useful. – user915783 Jan 03 '17 at 21:05