宏SWAP(T,X,Y)的交换类型t两个参数 [英] Macro SWAP(t,x,y) exchanging two arguments of type t

查看:401
本文介绍了宏SWAP(T,X,Y)的交换类型t两个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我基本上是试图使一个SWAP(T,X,Y)宏交换类型t两个参数。我想,当这两种说法的形式是想解决问题会

v [我++]和W [F(X)],即SWAP(INT,V [我++],W [F(X)])。

下code基本上是崩溃......

 的#define SWAP(T,X,Y){T * P = X; T * Q =ÿ; ŧZ = * P; * p = * Q; * Q = Z;}INT F(INT X){
    回报(0-X);
}诠释主要(无效){INT v [] = {1,2,3};
INT I = 0;INT W [] = {4,5,6};
INT X = -1;INT * P = V;
INT * Q = W;SWAP(INT *,V [我++],W [F(X)]);返回0;
}

任何想法可能会错呢?


解决方案

  SWAP(INT *,V [我++],W [F(X)]);

v [我++] INT 元素,但你将其分配到一个指针对象:

  T * P = X;

所以当你提领 P T Z = * P; 你得到一个段错误。如果你想有一个指针元素使用&放大器; 运营商

此外 v [我++] 有副作用(它会修改我++ ),你永远不应该通过前$ p有一个宏调用的副作用$ pssions。

So I am basically trying to make a SWAP(t,x,y) macro that exchanges two arguments of type t. I am trying to think of going around the problem when these two arguments are of the form

v[i++] and w[f(x)] , i.e. SWAP(int, v[i++], w[f(x)]).

The code below is basically crashing ...

#define SWAP(T,x,y) {T *p = x; T *q = y; T z = *p; *p = *q; *q = z;}

int f (int x){
    return (0-x);
}

int main(void) {

int v[] = {1,2,3};
int i = 0;

int w[] = {4,5,6};
int x = -1;

int *p = v;
int *q = w;

SWAP(int*, v[i++],w[f(x)]);

return 0;
}

Any ideas what may go wrong?

解决方案

SWAP(int*, v[i++],w[f(x)]);

v[i++] is an int element but you are assigning it to a pointer object in:

T *p = x;

so when are you are dereferencing p in T z = *p; you get a segfault. If you want a pointer to the element use the & operator.

Moreover v[i++] has a side-effect (it modifies i++) and you should never pass expressions that have side-effects in a macro call.

这篇关于宏SWAP(T,X,Y)的交换类型t两个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆