使用指针交换int数组值 [英] Using pointers to swap int array values

查看:184
本文介绍了使用指针交换int数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该使用指针交换整数数组中。它编译没有错误或警告并运行,但不交换整数。任何建议将是有益的!

下面是测试仪:

 #进口<&stdio.h中GT;无效掉期(INT元[]);INT主(INT ARGC,CHAR *的argv [])
{
    INT进制[] = {25,50};
    的printf(数组值是:%I和%I \\ N,元[0],元[1]);
    掉期(元);
    的printf(swaping值之后为:%I和%I \\ N,元[0],元[1]);    返回0;
}

下面是交换功能:

 无效掉期(INT元[])
{
    INT TEMP = *元;
    *进制= *(进制+ 1);
    *元=温度;
}

这是运行后显示的内容:

 数组值是:25〜50
swaping值后是:25和50


解决方案

我不喜欢这种破坏,但它看起来像一个错字比什么都重要。

在您的交换功能:

  *元=温度;

应该是:

  *(叉+ 1)=温度;

编辑:有没有你不使用数组表示法的原因?我认为这是一个更清楚一点这样的事情:

  INT TEMP =元[0];
进制[0] =进制[1];
进制[1] =温度;

I am supposed to use pointers to swap ints in an array. It compiles with no errors or warnings and runs but does not swap the ints. Any suggestions would be helpful!!!

Here is the tester:

#import <stdio.h>

void swap( int ary[] );

int main(  int argc, char*argv[] )
{
    int ary[] = { 25, 50 };
    printf( "The array values are: %i and %i \n", ary[0], ary[1] );
    swap( ary );
    printf( "After swaping the values are: %i and %i \n", ary[0], ary[1] );

    return 0;
}

Here is the swap function:

void swap( int ary[] )
{
    int temp = *ary;
    *ary = *(ary + 1);
    *ary = temp;
}

This is what is displayed after running:

The array values are: 25 and 50
After swaping the values are: 25 and 50

解决方案

I hate spoiling this but it looks like a typo more than anything.

In your swap function:

*ary = temp;

should be:

*(ary + 1) = temp;

edit: Is there a reason you're not using array notation? I think it's a bit clearer for things like this:

int temp = ary[0];
ary[0] = ary[1];
ary[1] = temp;

这篇关于使用指针交换int数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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