0

I have the following code:

void function(int *c1, int *c2){

    int val1 = 1, val2 = 2;

    c1 = &val1;
    c2 = &val2;
}

void main(){
    int *c1, *c2;

    function(c1, c2);

    printf("*c1=%d, *c2=%d\n", *c1, *c2);
}

I need to assign c1 and c2 new values in a function and use them later in main. The function must be 'void'.

I have tried solving this through allocated memory but to no avail. Any help would be appreciated.

ikegami
  • 367,544
  • 15
  • 269
  • 518
p b
  • 1
  • 1
    You don't want to return pointers to local variables like `val1` and `val2` anyway. – Steve Summit Dec 21 '22 at 14:33
  • You'll want `void function(int*&c1, int*&c2) { static int val1{1}; static int val2{2}; c1 = &val1; c2 = &val2; }` – Eljay Dec 21 '22 at 14:34
  • Please only tag the language you are using. Removed one of the tags at "random". Fix if I removed the wrong one. – ikegami Dec 21 '22 at 14:36
  • Tip: `void main()` is wrong. It should be `int main( void )` – ikegami Dec 21 '22 at 14:40
  • "I need to assign c1 and c2 new values." There are two different possible interpretations. Please clarify. Depending on what you're actually trying to do, it's possible that @ikegami's answer is correct, and the alleged [duplicate question](https://stackoverflow.com/questions/13431108) is irrelevant. – Steve Summit Dec 21 '22 at 14:45
  • @SteveSummit the function is supposed to find 2 indexes, the pointers c1 and c2 are supposed to carry this information to main(). Only the function body can be changed, the parameters must remain the same. – p b Dec 21 '22 at 14:49
  • 1
    The `c++` tag was removed, so now my C++ comment is irrelevant. I'll leave it for posterity, and the lesson learned that mistagged questions and result in comments and answers that are off the mark. – Eljay Dec 21 '22 at 15:04

1 Answers1

2

You don't want to assign to c1 and c2.

c1 = &val1;  // Wrong.
c2 = &val2;

You want to assign to the objects to which c1 and c2 point.

*c1 = val1;  // Fixed.
*c2 = val2;

But there's a second problem. You don't have anywhere to store the int values! The variables in main shouldn't be pointers at all.

int *c1, *c2;

should be

int c1, c2;

and that means that

function(c1, c2);
printf("*c1=%d, *c2=%d\n", *c1, *c2);

should be

function(&c1, &c2);
printf("c1=%d, c2=%d\n", c1, c2);
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • at first I was getting a segfault but it was fixed by allocating memory for the pointers. Thank you. – p b Dec 21 '22 at 14:52
  • Not sure what you mean by "allocating memory for the pointers". If you called `malloc`, that was probably overkill. I think in the caller you want `int c1, c2` (note no `*`'s) and `function(&c1, &c2);`. – Steve Summit Dec 21 '22 at 15:02
  • You should clarify that main() needs to be changed as well. Otherwise they'll just dereference uninitialized pointers. – Lundin Dec 21 '22 at 15:09
  • @Lundin I had missed that. Added. – ikegami Dec 21 '22 at 15:19