Home > OS >  How can I correct this code which let a pointer to point a greatest value by using double overlapped
How can I correct this code which let a pointer to point a greatest value by using double overlapped

Time:04-20

In 6 integers array, I want to print the greatest value by using double overlapped pointers and one additional one function. There are three parameters (int array m, the counts of elements in m, double pointer pmax) in declared function. When I debug this code, it isn't worked. Maybe I think this problem related with the process of using parameters. Then What parts should I have to modify?

Here's the code.

#include<stdio.h>
void set_max_ptr(int m[], int size, int** pmax);

int main(void)
{
int m[6] = { 5,6,1,3,7,9 };
int* pmax;
set_max_ptr(m, 6, pmax);
printf("the greatest value is %d \n", *pmax);
return 0;
}

void set_max_ptr(int m[], int size, int** pmax)
{
*pmax = &m[0];
for (int i = 0; i < size; i  )
{
if (*(m i) > **pmax)
**pmax = *(m i);
}
}

compiling error

1 warning generated. zsh: segmentation fault "/Users/cactual/"pointgreatestvalue

CodePudding user response:

You need to pass the address of the pointer:

set_max_ptr(m, 6, pmax);

should be

set_max_ptr(m, 6, &pmax);

and m i is already a pointer, do not dereference, to alter the passed pointer you want:

*pmax = m   i;

instead of

**pmax = *(m i);

CodePudding user response:

compiling error

1 warning generated. zsh: segmentation fault "/Users/cactual/"pointgreatestvalue

this is a runtime error, not a compiling error

compiling, with warnings enabled results in:

untitled.c: In function ‘main’:
untitled.c:8:19: warning: passing argument 3 of ‘set_max_ptr’ from incompatible pointer type [-Wincompatible-pointer-types]
    8 | set_max_ptr(m, 6, pmax);
      |                   ^~~~
      |                   |
      |                   int *
untitled.c:2:43: note: expected ‘int **’ but argument is of type ‘int *’
    2 | void set_max_ptr(int m[], int size, int** pmax);
      |                                     ~~~~~~^~~~
untitled.c:8:1: warning: ‘pmax’ is used uninitialized in this function [-Wuninitialized]
    8 | set_max_ptr(m, 6, pmax);
      | ^~~~~~~~~~~~~~~~~~~~~~~

Please post code that cleanly compiles

  • Related