将指针传递给函数? [英] Passing Pointers to Functions?
问题描述
#include 无效交换(int *a,int *b){int *k = a;a = b;b = k;}int main() {整数阿尔法= 5;整数β = 34;交换(阿尔法,贝塔);std::cout <<阿尔法<
第一个问题:我如何将值传递给具有指针作为传递参数的函数.
第二个问题:如何交换.它交换指针.但是当它出来时,alpha 和 beta 的值不应该仍然保持不变.
第三个问题:为什么当我传递指针时该函数不起作用,而当我传递常规变量时该函数起作用.
第四个问题:在函数void swap(int *a, int* b)
中是int *a
和int *b
引用?
这将是最好的例子,说明为什么我们不应该在全局级别包含命名空间 std...
swap (alpha,beta);
会调用 std::swap
而不是你自己的 swap
.
第三个问题:为什么当我传递指针时该函数不起作用,而当我传递常规变量时该函数起作用
因为您的 swap
没有正确编写.应该是:
void swap (int *a, int *b) {//最好你还应该检查指针是否不为 NULL.内部温度;温度 = *a;*a = *b;*b = 温度;}
<块引用>
第四个问题:在函数void swap(int *a, int* b)
中是int *a
和int *b
引用?
引用的语法是:
void swap ( int& a, int& b );
所以不,他们不是.它们是指针.
#include <iostream>
void swap (int *a, int *b) {
int *k = a;
a = b;
b = k;
}
int main() {
int alpha = 5;
int beta = 34;
swap (alpha,beta);
std::cout << alpha << std::endl;
std::cout << beta << std::endl;
int *ab = new int();
*ab = 34;
int *cd = new int();
*cd =64;
swap(ab,cd);
std::cout << *ab << std::endl;
std::cout << *cd << std::endl;
}
First Question: How am I able to pass values to a function which has pointers as passing parameters.
Second Question: How is it able to swap. It swaps the pointers. But when it comes out shouldn't the values of alpha and beta still remain same.
Third Question: Why doesn't the function work when I pass pointers but works when I pass regular variables.
Fourth Question: In the function void swap(int *a, int* b)
are int *a
and int *b
references?
And that would serve the best examples for why we should not include namespace std at global level…
swap (alpha,beta);
would call std::swap
rather than your own swap
.
Third Question: Why doesn't the function work when I pass pointers but works when I pass regular variables
Because your swap
isn't properly written. It should be:
void swap (int *a, int *b) {
// Preferably you should also check if pointers are not NULL.
int temp;
temp = *a;
*a = *b;
*b = temp;
}
Fourth Question: In the function
void swap(int *a, int* b)
areint *a
andint *b
references?
The syntax of reference is:
void swap ( int& a, int& b );
So no, they aren't. They are pointers.
这篇关于将指针传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!