Skip to content

Instantly share code, notes, and snippets.

@foysalit
Created November 6, 2013 23:55
Show Gist options
  • Save foysalit/7346438 to your computer and use it in GitHub Desktop.
Save foysalit/7346438 to your computer and use it in GitHub Desktop.
c struct and pointer

[(ref:)] (http://c.learncodethehardway.org/book/ex16.html)

//struct
struct Person{
  char *name;
  int age;
}

//function that returns a pointer to a struct
//takes in the properties of the struct as arguments
//returns a pointer to the newly created struct
//that's why the return type of th
struct Person *create_person(char *name, int age){
  struct Person *who = malloc(sizeof(struct Person));

  who->name = name; 
  who->age = age;

  return who;
}

//in main we can user this function like below
int main(){
  struct Person *foysal = create_person("foysal ahamed", 22);
  
  //now to access the properties of foysal we can just do 
  //foysal->name and foysal->age

  return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment