为什么这段代码不起作用? (指针) [英] why this code does not work? (pointers)
问题描述
#include<stdio.h>
#include<string.h>
void allocate(int *arr,int size,int value){
arr = (int *) malloc(size*sizeof(int));
int i =0;
while(i<size)
{
*(arr+i) = value;
i++;
}
}
int main()
{
int *vector = NULL;
allocate(vector,5,45);
printf("%d",*vector);
}
推荐答案
因为C按值传递所有变量,而不是通过引用传递。
这意味着当您将值传递给方法时,您在方法内所做的更改不会影响调用它的函数中的变量:
Because C passes all variables by value, not by reference.
What that means is that when you pass a value to a method, changes you make inside the method do not affect the variable in the function that called it:
void doit(int i)
{
i++;
}
...
i = 3;
doit(i);
printf("%d", i);
...
将打印3,而不是4。
这是明智的:否则我可以这样做:
Will print "3", not "4".
This is sensible: otherwise I could do this:
doit(3);
printf("%d", 3);
然后事情会变得非常混乱。
所以当你传递指向你的分配函数的指针时,它会将变量中的值(NULL)传递给函数,而不是对保存null的位置的引用。
有两种方法可以解决这个问题:
1)更改分配以接受指向a的指针-pointer-to-an-integet,向量的dpass地址:
And then things would get very confusing.
So when you pass a a pointer to your allocate function, it passes the value in the variable (NULL) to the function, and not a reference to the location that hold the null.
There are two ways to solve this:
1) change allocate to accept a pointer-to-a-pointer-to-an-integet, an dpass teh address of vector:
void allocate(int **arr,int size,int value){
*arr = (int *) malloc(size*sizeof(int));
...
int *vector = NULL;
allocate(&vector,5,45);
...
2)获取分配以返回值:
2) Get allocate to return the value instead:
int* allocate(int size,int value){
int *arr = (int *) malloc(size*sizeof(int));
int i =0;
while(i<size)
{
*(arr+i) = value;
i++;
}
return arr;
}
int main()
{
int *vector = NULL;
vector = allocate(5,45);
我?我将返回第二个版本中的值。
Me? I'd return the value as in the second version.
您的代码正在修改allocate函数中的局部变量,该函数不会返回给main。您需要传递指针的地址,如下所示:
Your code is modifiying the local variable in the allocate function, which is not returned to main. You need to pass the address of the pointer as below:
void allocate(int **arr, int size, int value)
{
*arr = (int *)malloc(size * sizeof(int));
int i = 0;
while(i < size)
{
*(*arr + i) = value;
i++;
}
}
int main()
{
int *vector = NULL;
allocate(&vector, 5, 45);
printf("%d",*vector);
}
虽然更好(更具可读性)的版本是分配函数将指针返回到main,例如:
Although a better (and more readable) version would be for the allocate function to return the pointer to main, like:
int* allocate(int size, int value)
{
int* arr = (int *)malloc(size * sizeof(int));
int i = 0;
while(i < size)
{
*(arr + i) = value;
i++;
}
return arr; // thanks to Jochen for reminding me about this
}
int main()
{
int *vector = allocate(5, 45);
printf("%d",*vector);
}
这篇关于为什么这段代码不起作用? (指针)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!