1. Computing

C Tutorial - About Pointers

By

6 of 10

Example 2- Using Pointers with a Struct

What do I need Pointers For?

C doesn't have pass by reference so any function which needs to return more than one value either has to pass in (and return) a struct which is ugly (and inefficient- copying structs!) or use pointers. This example doesn't do that, instead it returns a pointer to a struct. The question is, where does the struct get created and where does it get freed? I've chosen to create it in the function and free it afterwards. Had I created it outside, I'd have had to pass its address in.


// ex2.c
//
#include <stdio.h>
#include <stdlib.h>

struct mystruct {
    int a;
};

typedef struct mystruct * pmystruct;

pmystruct getpstruct() {
    pmystruct temp=(pmystruct)malloc(sizeof(pmystruct*)) ;
    return temp;
}

int main(int argc, char* argv[])
{
    pmystruct pb= getpstruct() ;
    pb->a = 8;
    ++pb->a;
    printf ("The value of b->a is %i ",pb->a) ;
    free(pb) ;
    return 0;
}

Download Example 2 Source Code

In example 2 mystruct is a simple struct containing an int a. In C, when you declare a struct or pass it as a parameter, you have to use the word struct so I've used typedef to simplify it. The type pmystruct is a pointer to mystruct. The function getpstruct() creates an instance of a mystruct and returns a pointer to it.

In the main() function, the variable pb is assigned an instance of a mystruct and it sets the value to 8 and then increments it before outputting the value. With a pointer to a struct the -> notation is used to access the members of the struct instead of the. notation. The function free() is the opposite of malloc() and frees up the allocated memory.

On the next page : More on Example 2

  1. About.com
  2. Computing
  3. C / C++ / C#

©2014 About.com. All rights reserved.