Thread: Returning a pointer to a struct

  1. #1
    Hamster without a wheel iain's Avatar
    Join Date
    Aug 2001
    Posts
    1,385

    Returning a pointer to a struct

    I have an array of structs, each struct contains one char[16] and one int, i need a a function to return a pointer to the char[16] whena specfic event occurs.

    I ahve two problems:
    What type does the returning function need to be?
    Is the following return statement correct:

    return **structName[element].char[16]

    (where char is the array name)

    tia
    Monday - what a way to spend a seventh of your life

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Code:
    #include <stdio.h>
    
    struct type
    {
       char c[16];
       int  i;
    } array[] =
    {
       {"a",0},{"b",1},{"c",2},{"d",3},{"e",4},{"f",5},{"g",6},
    };
    
    char *foo(struct type *obj, size_t size, int event)
    {
       while ( size-- )
       {
          if ( obj->i == event )
          {
             return obj->c;
          }
          ++obj;
       }
       return 0;
    }
    
    int main()
    {
       char *result = foo(array, sizeof array / sizeof *array, 4);
       if ( result )
       {
          puts(result);
       }
       return 0;
    }
    [edit]
    Code:
    char *foo(int event)
    {
       static struct type
       {
          char c[16];
          int  i;
       } array[] =
       {
          {"a",0},{"b",1},{"c",2},{"d",3},{"e",4},{"f",5},{"g",6},
       };
       size_t i;
       for (i = 0; i < sizeof array / sizeof *array; ++i)
       {
          if ( array[i].i == event )
          {
             return array[i].c;
          }
       }
       return 0;
    }
    Last edited by Dave_Sinkula; 03-23-2005 at 04:48 PM.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help with linked list sorting function
    By Jaggid1x in forum C Programming
    Replies: 6
    Last Post: 06-02-2009, 02:14 AM
  2. Link List math
    By t014y in forum C Programming
    Replies: 17
    Last Post: 02-20-2009, 06:55 PM
  3. struct pointer
    By t014y in forum C Programming
    Replies: 5
    Last Post: 01-26-2009, 03:50 PM
  4. Replies: 1
    Last Post: 12-03-2008, 03:10 AM
  5. towers of hanoi problem
    By aik_21 in forum C Programming
    Replies: 1
    Last Post: 10-02-2004, 01:34 PM