functions and structures

This is a discussion on functions and structures within the C Programming forums, part of the General Programming Boards category; I have a structure in a function declared like this: struct audio ad; and basically I need to return its ...

  1. #1
    Registered User
    Join Date
    Aug 2004
    Posts
    34

    functions and structures

    I have a structure in a function declared like this:

    struct audio ad;

    and basically I need to return its address to the calling function.

    First, should the declaration look something like this:

    static struct audio ad;

    because this is a local variable so, it will be erased from memory when control goes back to the calling function?

    Seconds, how exactly should my function prototype look like?
    ~flood

  2. #2
    Registered User
    Join Date
    Mar 2005
    Posts
    135

    ...

    Static version
    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    
    struct audio
    {
    	int v1;
    	char szline[14];
    };
    
    struct audio foo(void); // protoype
    
    int main(int argc, char **argv)
    {
    	struct audio p;
    
    	p = foo();
    
    	printf("v1: %d\n", p.v1);
    	printf("szline: %s\n", p.szline);
    }
    
    struct audio foo(void)
    {
    	static struct audio ad;
    
    	strcpy(ad.szline, "static string");
    	ad.v1 = 56;
    	return ad;
    }
    Dynamic version:
    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    
    struct audio
    {
    	int v1;
    	char szline[14];
    };
    
    struct audio* foo(void); // protoype
    
    int main(int argc, char **argv)
    {
    	struct audio *p;
    
    	p = foo();
    
    	printf("v1: %d\n", p->v1);
    	printf("szline: %s\n", p->szline);
    
    	free(p);
    }
    
    struct audio* foo(void)
    {
    	static struct audio *ad;
    
    	ad = malloc(sizeof(struct audio));
    
    	strcpy(ad->szline, "static string");
    	ad->v1 = 56;
    	return ad;
    }

  3. #3
    Registered User
    Join Date
    Aug 2004
    Posts
    34
    Thank you
    ~flood

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. COntrol structures and functions questions
    By angelicscars in forum C Programming
    Replies: 1
    Last Post: 11-21-2005, 11:50 AM
  2. passing structures to functions
    By AmazingRando in forum C++ Programming
    Replies: 5
    Last Post: 09-05-2003, 12:22 PM
  3. Array of Structures and Functions
    By Kinasz in forum C Programming
    Replies: 2
    Last Post: 05-04-2003, 08:06 AM
  4. passing array structures to functions
    By lukejack in forum C Programming
    Replies: 2
    Last Post: 04-08-2003, 03:17 PM
  5. data structures / hash functions
    By rickc77 in forum C Programming
    Replies: 5
    Last Post: 11-11-2001, 01:54 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21