在 C 中反转数组? [英] Reversing Array in C?

查看:44
本文介绍了在 C 中反转数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图实现一个反向数组代码,但它似乎不起作用,我真的不知道为什么.For 循环似乎不起作用.我不知道为什么,因为我觉得这个逻辑很对.

Hi i trying to implement a reverse array code but it doesnt seem to work and im really not sure why. The For loop just doesnt seem to work. I dont know why because the logic seems pretty right to me.

#include <stdio.h>
#include <string.h>

void reverse(char, int);

int main()
{
    char a[100];
    gets(a);

    reverse(a, strlen(a)-1);

    printf("%s\n",a);
    getchar();
    getchar();
    getchar();
    return 0;
}

void reverse(char ar[], int n)
{
    char c;
    int i = 0;
    printf("n = %d" , n);
    for ( i = 0; i >= n ; i++){
        c = ar[i];
        ar[i] = ar[n];
        ar[n] = c;
        printf("Processed");
        n--;}

}


/*
if (begin >= n)
return;

c          = *(x+begin);
*(x+begin) = *(x+n);
*(x+n)   = c;
offs = x++;
printf("Begin = %d   ,  n = %d, offs = %p  \n", begin, n, offs);
reverse(x, ++begin, --n); */

推荐答案

void reverse(char, int);  //declaration wrong

void reverse(char[], int);
                 ^^^ 

<小时>

你的循环


Your loop

for ( i = 0; i >= n ; i++) // this fails i=0, n=some size

应该是

for ( i = 0; i <= n ; i++)

避免使用 gets() 使用 fgets() 代替.

Avoid using gets() use fgets() instead.

这篇关于在 C 中反转数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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