pointers

C

Chathu

Hello everyone!
Can anyone explain the meaning of these two code fragments.
1). int **p;
p=(int**)malloc(sizeof(int *));

2). void (*p)(void);
 
M

Michael Mair

Chathu said:
Hello everyone!
Can anyone explain the meaning of these two code fragments.
1). int **p;

declare p as pointer to pointer to int.
p=(int**)malloc(sizeof(int *));

clearer and less error prone:
p = malloc(sizeof *p);

try to dynamically allocate storage of the size of the type p points to
(pointer to int) and assign the return value to p.
This value has to be checked against NULL as malloc() may have failed.
When you no longer need p or the storage it points to, you have to
free(p);

Please read comp.lang.c FAQ for more information.
http://www.eskimo.com/~scs/C-faq/top.html
2). void (*p)(void);

Declare p as a function pointer, pointing to functions with empty
parameter list and no return value.


-Michael
 
I

infobahn

Chathu said:
Hello everyone!
Can anyone explain the meaning of these two code fragments.
1). int **p;
p=(int**)malloc(sizeof(int *));

More simply:

int **p;
p = malloc(sizeof *p);

p is a pointer to a pointer to int.
The malloc allocates sufficient space to store a pointer to int, and
points p at this space, OR the malloc returns a NULL pointer to show
that it couldn't meet the request for storage.
2). void (*p)(void);

p is a pointer to a function that takes no parameters and returns no
value.

#include <stdio.h>

void foo(void)
{
puts("Hello, world.");
}

void bar(void)
{
puts("Goodbye, world.");
}

int main(void)
{
void (*p)(void);
p = foo;
(*p)();
p = bar;
(*p)();
return 0;
}
 
C

CBFalconer

Chathu said:
Can anyone explain the meaning of these two code fragments.
1). int **p;
p=(int**)malloc(sizeof(int *));

Miswritten. There should be no cast. p is a pointer to a pointer
to int. It should be written as:

p = malloc(sizeof *p);

which will automatically adapt to the declaration of p, and catch
the error of failing to #include said:
2). void (*p)(void);

p is declared as a pointer to a function of no arguments returning
nothing.

Get yourself a copy of cdecl.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,159
Messages
2,570,879
Members
47,416
Latest member
LionelQ387

Latest Threads

Top