Chester
Chester

Reputation: 23

Understanding Pointers and Relationships to Structs

This is part of a study guide at the moment and while I realize its not very difficult, I can't understand what its asking for.

Write a Function: struct *grump(int i, int j) which returns a pointer to a "struct grump" holding the values i, j in its fields a,b

So Im given

struct grump
{
    int a;
    int b;
};

I'm just confused as to what its asking for

Upvotes: 2

Views: 107

Answers (3)

iabdalkader
iabdalkader

Reputation: 17312

It's asking you to allocate a struct grump that will hold the values i and j, something like:

struct grump* func(int i, int j)
{
    struct grump *g = malloc(sizeof(*g));
    if (g != NULL) {
       g->a = i;
       g->b = j;
    }
    return g;
}

Note: we check if g != NULL to make sure malloc() succeeded before using grump if not the function will return NULL. Of course at some point you will need to free() that memory, I'm sure your study guide will mention it soon.

Upvotes: 3

DigitalRoss
DigitalRoss

Reputation: 146073

There are no built-in things called constructors in C but that's essentially what you are writing. It might be a good idea to take it to the next level and use typedef to create some slightly more object-like structs.

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int a, b;
} g;

g *grump(int i, int j) {
  g *t = malloc(sizeof(g));
  t->a = i;
  t->b = j;
  return t;
}

int main(int ac, char **av) {
  g *a;

  a = grump(123, 456);
  printf("%d %d\n", a->a, a->b);
  return 0;
}

Upvotes: 1

Omkant
Omkant

Reputation: 9204

You have to write a function Which will set the values you passed into function into the struct grump but it depends where is your struct object.

You can access the struct object if that is global or you are allocating using malloc()

I have shown demo using malloc()

You can do like this :

struct grump* foo(int i, int j)
{
struct grump *ptg;
ptg=malloc(sizeof(struct grump));
if(ptg)
{
ptg->a=i;
ptg->b=j;
}
return ptg;
}

int main()
{
struct grump *pg;
pg=foo(5,10);
// Do whatever you want 
free(pg); // Don't forget to free , It's best practice to free malloced object
return 0;
}

Upvotes: 1

Related Questions