简体   繁体   中英

Passing and changing an array, with pass by reference, using pointers in C

I'm working on a project for college and I've been stuck on this part for a while and can't seem to find an answer. Basically we have to make a program that fills an array using pass by reference and without using subscripts (just to be annoying and because he thinks they're faster to execute). Here's what I've got so far:
These are the relevant parts in main:

#define SIZE 4

int *enteredCode;
enteredCode = (int*)calloc(SIZE, sizeof(int));
codeEnter(&enteredCode);

And this is in a header file:

//codeEnter function
void codeEnter(int **code){
//Declarations

system("cls");
puts("************* INPUT CODE *************"
    "\n\nPlease enter your 4 digit code:");
for (int i = 0; i < SIZE; i++){
    scanf("%d", *(code + i));
}//End of for

I can get this to work if I change it to:

#define SIZE 4

int enteredCode[SIZE];
codeEnter(enteredCode);

Header part:

void codeEnter(int *code){
//Declarations

system("cls");
puts("************* INPUT CODE *************"
    "\n\nPlease enter your 4 digit code:");
for (int i = 0; i < SIZE; i++){
    scanf_s("%d", &*(code + i));
}//End of for

}//End of codeEnter

Any help and explanation would be appreciated.

The main problem is how you dereference the array in your codeEnter function.

You are passing a pointer to an array of int and you need to obtain the address of the i-th element of the array.

So

void codeEnter(int **code) {
  int* array = *code; // <- you obtain the original array
  int* element = (array+i); // <- you obtain the address of the element
  ...
}

This composed becomes *code + i , not *(code+i) . In your snippet you basically modify the address which contains the address to the array (so you obtain a garbage address).

suggest something like this:

#define SIZE 4

int *enteredCode:
if( NULL == (enteredCode = calloc(SIZE, sizeof(int)) ) )
{ // then calloc failed
    perror( "calloc failed" );
    exit( EXIT_FAILURE );
}

// implied else, calloc successful

codeEnter(enteredCode);

---

And this is in a header file:

//codeEnter function declaration
void codeEnter(int *code);

// this in the source file:

void codeEnter(int *code)
{  
     system("cls");
     puts("************* INPUT CODE *************"
          "\n\nPlease enter your 4 digit code:");

    for (int i = 0; i < SIZE; i++)
    {
        if( 1 != scanf("%d", (code + i)) )
        { // then, scanf failed
            perror( "scanf failed" );
            free(code);
            exit( EXIT_FAILURE );
        }

        // implied else, scanf successful

    }//End for

    // rest of function here

} // end function: enterCode

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM