spectrum-zx
spectrum-zx

Reputation: 13

Modify struct from function?

I want to modify file in the items struct from parse_commandline().

I can without problems modify items->file from main() by using strncpy, but not from parse_commandline(). I need to modify parse_commandline() so it can recieve information about items from main(), by i don't know how?

typedef struct {
    int pack_01;
    int pack_02;
    char file[100];
} items;

static items character_y = { 1, 1 }

parse_commandline(int argc, char *argv[])
{

/* PARSE COMMANDLINE ARGUMENTS */

}

int main(int argc, char* argv[])
{
    items *ptr_items = &character_y;

    parse_commandline(argc,argv);

    return 0;
}

Upvotes: 1

Views: 4299

Answers (2)

JaredPar
JaredPar

Reputation: 754763

The way to do this is pass a pointer to items to the parse_commandline function and let the function update the structure based on the arguments.

parse_commandline(int argc, char *argv[], items* pItems) {
  pItem->pack_01 = 42;
  ...
};

int main(int argc, char* argv[]) {
  items items;
  parse_commandline(argc, argv, &items);
  ...
}

Upvotes: 1

Carl Norum
Carl Norum

Reputation: 224944

Passing a structure to a function in C is no different from passing any other variable. In your case, you should do it by reference so that you can modify the caller's structure:

void parse_commandline(int argc, char *argv[], items *theItems)

Upvotes: 0

Related Questions