简体   繁体   中英

Changing array's elements with function and pointer

I'm trying to change an array's values using a function that has parameters of pointer

#include <stdio.h>

void store(int *arr1, int place) {
int i;
for(i = 0; i < sizeof(*arr1); i++) {
    printf("Value %d: ", i+1);
    printf("\n");
    scanf("%d", &*arr1[place]);
    place++;
}

for(i = 0; i < sizeof(*arr1); i++) {
    printf("Element %d: %d", i, *arr1[place]);
    printf("\n");
    place++;
}



}

int main()
{
int arr[5];

store(&arr, 0);

return 0;
}

but it turns me this:

error: invalid type argument of unary '*' (have 'int')

This should work properly, let me try to explain why I made those changes.

#include <stdio.h>
#define MAX_LENGTH 5 //preprocessor directive

void store(int arr1[]) {
int i;
for(i = 0; i < MAX_LENGTH; i++) {
    printf("Value %d: ", i+1);
    printf("\n");
    scanf("%d", &arr1[i]); 
}
for(i = 0; i < MAX_LENGTH; i++) {
    printf("Element %d: %d", i, arr1[i]); //maybe also i+1?
    printf("\n");
}
}

int main()
{
int arr[MAX_LENGTH];

store(arr); //only one parameter needed

return 0;
}

An array itself is a pointer, pointing to a memory location, array[0] is the first element, array[1] is the memory location of the first one plus the size of the datatype in this case an integer. So if you want to pass it to a function as a pointer you don't need to specify that it's a pointer, neither do you have to tell the function that it's a pointer.

The sizeof() function counts the bits inside of the array, meaning that you have to divide it by the datatype (it's better to do it that way, than using a fixed number, because the size of an integer eg can vary depending on the machine).

int i = sizeof(arr1) / sizeof(arr1[0]) //brackets indicate single integer

As you didn't initialize any values yet, you won't get a 5 out of that, that's why I made the decision to set a value using #define at the top, this is a preprocessor directive allowing you to set a value you can access in both of your functions.

I also chose to delete the place variable, it seemed unnecessary, because you might as well use i, if you want to use it, you have to set an initial value for it, otherwise it will just use any value that is stored at its memory location, which leads to errors.

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