在向量上插入新值(C 语言)
Inserting new values on vector (in C language)
我正在尝试创建一个详细说明数组的函数。我不确定如何在函数上输入向量或数组,然后返回修改后的 vector/array(我正在尝试使用指针)。
这可能吗,还是我用错了指针?
int newValue(int *p){
// modify the vector
return p;
}
int main(){
int a[6]={4,6,7,3,1,8};
int *p;
p = a;
p = newValue (p);
(这是作业:
给定一个包含 VET_SIZE 个整数元素的数组:
编写一个函数以在特定索引中插入一个新值
数组,并向前移动以下元素而不
删除除最后一个元素的值之外的现有值)
I'm not sure how to input a vector or an array on a function and then reurning the modified vector (I'm trying to use pointers)
你需要做的就是传递数组本身,然后你可以直接在函数newValue
中修改它。像这样:
void newValue(int *p, size_t n){
// modify the 2nd item
p[1] = 10;
}
然后在main
中调用它:
newValue(a);
一些注意事项:
- 您的
newValue
不需要 return 任何东西(void
就可以),因为您可以直接更改数组。
void newValue(int *p, size_t n)
与 void newValue(int p[], size_t n)
相同 - 因为数组 decays
指向指针。
- 通常传递一个关于输入数组大小的附加参数
n
是很好的,因此在您的函数中您可以检查以确保您没有 out-of-bound 访问权限。
我正在尝试创建一个详细说明数组的函数。我不确定如何在函数上输入向量或数组,然后返回修改后的 vector/array(我正在尝试使用指针)。
这可能吗,还是我用错了指针?
int newValue(int *p){
// modify the vector
return p;
}
int main(){
int a[6]={4,6,7,3,1,8};
int *p;
p = a;
p = newValue (p);
(这是作业: 给定一个包含 VET_SIZE 个整数元素的数组: 编写一个函数以在特定索引中插入一个新值 数组,并向前移动以下元素而不 删除除最后一个元素的值之外的现有值)
I'm not sure how to input a vector or an array on a function and then reurning the modified vector (I'm trying to use pointers)
你需要做的就是传递数组本身,然后你可以直接在函数newValue
中修改它。像这样:
void newValue(int *p, size_t n){
// modify the 2nd item
p[1] = 10;
}
然后在main
中调用它:
newValue(a);
一些注意事项:
- 您的
newValue
不需要 return 任何东西(void
就可以),因为您可以直接更改数组。 void newValue(int *p, size_t n)
与void newValue(int p[], size_t n)
相同 - 因为数组decays
指向指针。- 通常传递一个关于输入数组大小的附加参数
n
是很好的,因此在您的函数中您可以检查以确保您没有 out-of-bound 访问权限。