-1

I'm writing a program that can modify rows and cols from a function of a function. I don't understand how to do pointer of a pointer.

void changeNum(int*setRows, int *setCol)
{
  changeNum2(*setRows,*setCol);
}
void changeNum2(int*setRows, int *setCol)
{
  *setRows=5;
  *setCol=5;
}
int main() {
  int*row=10;
  int* col=10;
  changeNum(&row,&col);
  printf("%d %d",row,col);
  return 0;
}
andyong5
  • 149
  • 9
  • 2
    Any textbook/online course/tutor should be able to help you out. – John3136 Dec 14 '17 at 01:48
  • The question title alone indicates that your are approaching becoming a three-star-programmer (http://wiki.c2.com/?ThreeStarProgrammer). Please reconsider. – Yunnosch Dec 14 '17 at 06:32

2 Answers2

1

First

  int*row=10;
  int* col=10;

This is wrong. Assigning hardcoded address. You don't want this

  int row=10;
  int col=10;

How to get the address of the row and col?

&row and &col.

How to pass it to function?

Call it, changeNum(&row,&col);

void changeNum(int*setRows, int *setCol)
{
     ...       
}

How to pass pointer to pointer?

void changeNum(int*setRows, int *setCol)
{
    chnageNum2(&setRows, &setCol);
}

ChangeNum2 how it would change value?

void chnageNum2(int **setRows, int **setCol){
    **setRows = 110;
    **setCol = 110;
}

Can we do the same change using changeNum() only?

Yes we can do that.

void changeNum(int*setRows, int *setCol)
{
     *setRows = 110;
     *setCol = 110;        
}

Definitely check this. Grab a book. It will help a lot.

The complete code will be

void changeNum(int*setRows, int *setCol)
{
  changeNum2(&setRows,&setCol);
}
void changeNum2(int**setRows, int **setCol)
{
  **setRows=5;
  **setCol=5;
}
int main(void) {
  int row=10;
  int col=10;
  changeNum(&row,&col);
  printf("%d %d",row,col);
  return 0;
}
user2736738
  • 30,591
  • 5
  • 42
  • 56
0
#include <stdio.h>

void changeNum(int*, int*);
void changeNum2(int*, int*);

void changeNum(int* setRows, int *setCol) {
    changeNum2(setRows,setCol);
}

void changeNum2(int* setRows, int *setCol) {
    *setRows=5;
    *setCol=5;
}

int main() {
    int row=10;
    int col=10;
    changeNum(&row, &col);
    printf("%d %d\n", row, col);
    return 0;
}

It takes sometime to grasp that every C function parameter is passed by value. So you can safely pass setRows pointer to the second function simply by its value.

Also, it's necessary to declare previously the function changeNum2, I've included the declaration without parameter names to clarify it's possible.

I strongly recommend reading this book: https://en.wikipedia.org/wiki/The_C_Programming_Language, specially chapter 5 (Pointers and arrays).

You can find a PDF copy easily. It's where I finally learned this concept.

Niloct
  • 9,491
  • 3
  • 44
  • 57