简体   繁体   English

用函数和指针改变数组的元素

[英]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')错误:一元“*”的无效类型参数(有“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.数组本身是一个指针,指向一个内存位置,array[0] 是第一个元素,array[1] 是第一个元素的内存位置加上数据类型的大小,在这种情况下是一个整数。 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). sizeof() 函数计算数组内部的位数,这意味着您必须将其除以数据类型(最好这样做,而不是使用固定数字,因为整数的大小(例如)可能会因机器)。

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.由于您还没有初始化任何值,因此您不会从中得到 5,这就是为什么我决定使用顶部的 #define 设置一个值,这是一个预处理器指令,允许您设置一个值可以访问您的两个功能。

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.我也选择删除place变量,好像没有必要,因为你还不如用i,如果你想用它,你必须给它设置一个初始值,否则它只会使用它存储的任何值内存位置,这会导致错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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