c - How can I pass an array of structures to a function by reference? -


this question has answer here:

#include <stdio.h>  void changevalues(struct item *item[]);  struct item { int number; };  int main(void) {     struct item items[10];     (int = 0; < 10; i++)     {         items[i].number = i;//initialize         printf("before:: %d\n", items[i].number);     }      changevalues(items);      (int = 0; < 10; i++)     {         items[i].number = i;         printf("after:: %d\n", items[i].number);     }      return 0; }  void changevalues(struct item *item[]) {     (int = 0; < 10; i++)     item[i] -> number += 5; } 

i trying pass array of structures function. need change values of structures members within function reference , not value. odd reason when print results after function called values remain same prior function call.

in c can't pass reference (like c++). can pass value, or pass pointer.

in case, appears want pass array of struct function changevalues. that's in main. however, prototype , implementation of changevalues try pass array of pointer struct item.

one possible fix change array of pointer struct item array of struct.

void changevalues(struct item item[]) {     (int = 0; < 10; i++)     {         item[i].number += 5;     } } 

edit: had 2 other mistakes in code:

1) definition of struct item need before changevalues prototype:

struct item {     int number; };  void changevalues(struct item item[]); 

2) in main() reset value in changevalues - invalidated done in function:

for (int = 0; < 10; i++) {     items[i].number = i;   // <-- remove line resetting value again here     printf("after:: %d\n", items[i].number); } 

struct item {     int number; };  void changevalues(struct item item[]);   int main(void) {     struct item items[10];     (int = 0; < 10; i++)     {         items[i].number = i;//initialize         printf("before:: %d\n", items[i].number);     }      changevalues(items);      (int = 0; < 10; i++)     {         // items[i].number = i;   // <-- remove line resetting value again here         printf("after:: %d\n", items[i].number);     }      return 0; }  void changevalues(struct item items[]) {     (int = 0; < 10; i++)     {         items[i].number += 5;     } } 

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -