使用函数和指针更改数组的元素

时间:2019-03-17 04:14:58

标签: c pointers

我正在尝试使用具有指针参数的函数来更改数组的值

#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;
}

但是,这让我如此:

错误:一元“ *”(具有“ int”)的无效类型参数

1 个答案:

答案 0 :(得分:0)

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 e.g. 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.