5

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); */
7
  • 4
    You may want to start by making your prototype match your actual function. Commented Oct 11, 2013 at 3:22
  • 1
    maybe it should be i<=n ?! Commented Oct 11, 2013 at 3:24
  • Below theres a commented out code that works when i pass 3 parameters through but I wish to limit it to just passing 2 parameters, the string and its length Commented Oct 11, 2013 at 3:24
  • @JoC Out of curiosity only, why even pass the length. Are you envisioning calling this on only a partial string? Or is invoking strlen() from reverse() just not in the wheelhouse of this assignment? Commented Oct 11, 2013 at 3:26
  • Side note. there are more direct ways of doing this, in case you're interested in alternatives. Commented Oct 11, 2013 at 3:45

5 Answers 5

5
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

should be

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

Avoid using gets() use fgets() instead.

Sign up to request clarification or add additional context in comments.

3 Comments

do changes to this array inside the reverse function actually take effect afterwards? because, not the pointer is sent as parameter.
@hasanovh Arrays are simply named addresses in C. Said-address is passed as a pointer value to the function. They are the exception to the pass-by-value idiom of C, but not really. Their "value" is their address. Most engineers call this address synonymousness "pointer decay", though I find the tagline generally irritating, as the word "decay" appears exactly once in the entire C99 standard, and its appearance has absolutely nothing to do with passing arrays to functions.
@hasanovh AS WhozCraig said Arrays are simply named addressed in C. Said-address is passed as a pointer value to the function adding this example to WhozCriag explanation. ideone.com/B9e5hG
1

for loop condition should be 'i < n'. and prototype declaration should match.

Comments

0

for loop condition should be 'i < n'. and prototype declaration should match.

and "int n" is the size of array. So "i<=n" would make the same array reversed from end to mid, and again from mid to top. So result is same as array. make "n" as half of the array size.

1 Comment

He doesn't need to divide n in half because he decrements it in the loop, though it's easy to miss that.
0

I think better use macro for this task. In code below it is a macro SWAP.


Content a file main.c

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

// swap values with respect a type it
#ifndef SWAP
    #define SWAP(type, a, b) \
    { \
        type temp = a; \
        a = b; \
        b = temp; \
    }
#endif


/*
    Print an array integer items
 */
void
printIntArray(int array[], size_t length) {
    char ending_charapter[] = ", ";
    putchar('[');
    for (size_t i = 0; i < length; ++i) {
        printf("%d", array[i]);
        if (i < length - 1) {
            printf("%s", ending_charapter);
        }
    }
    puts("]");
}


/*
    Print an array float items
 */
void
printFloatArray(float array[], size_t length) {
    char ending_charapter[] = ", ";
    putchar('[');
    for (size_t i = 0; i < length; ++i) {
        printf("%f", array[i]);
        if (i < length - 1) {
            printf("%s", ending_charapter);
        }
    }
    puts("]");
}


/*
    Reverse an integer array in place
 */
static int
reverseIntArray(int *array, const size_t length) {
    for (int i = 0; i < length / 2; ++i) {
        SWAP(int, array[i], array[length - i - 1]);
    }
    return 0;
}


/*
    Reverse an float array in place
 */
static int
reverseFloatArray(float *array, const size_t length) {
    for (int i = 0; i < length / 2; ++i) {
        SWAP(float, array[i], array[length - i - 1]);
    }
    return 0;
}


/*
    Reverse an string
 */
static int
reverseString(char string[]) {
    size_t str_len = strlen(string);
    for (int i = 0; i < str_len / 2; ++i) {
        SWAP(char, string[i], string[str_len - i - 1]);
    }
    return 0;
}


int
main (const int argc, const char *argv[])
{
    puts("An example reverse for a int array");
    int arrInt[4] = {1, -2, 3, -4};
    printIntArray(arrInt, 4);
    reverseIntArray(arrInt, 4);
    printIntArray(arrInt, 4);

    puts("An example reverse for a float array");
    float arrFloat[4] = {0.1, -2.12, 1.3, -4.2};
    printFloatArray(arrFloat, 4);
    reverseFloatArray(arrFloat, 4);
    printFloatArray(arrFloat, 4);

    puts("An example reverse for a string");
    char str[] = "Simple text";
    puts(str);
    reverseString(str);
    puts(str);

    return 0;
}

Compilation as:

gcc std=c11 -I /usr/include/ -o main main.c

Result:

An example reverse for a int array
[1, -2, 3, -4]
[-4, 3, -2, 1]
An example reverse for a float array
[0.100000, -2.120000, 1.300000, -4.200000]
[-4.200000, 1.300000, -2.120000, 0.100000]
An example reverse for a string
Simple text
txet elpmiS

Notes:

  1. Just working
  2. Workint with any built-in type
  3. Poorly tested and used only the GCC compiler
  4. Based on

    4.1 Define a preprocessor macro swap(t, x, y)

    4.2 Reversing an array In place

    4.3 The answers on this question


Testing environment

$ lsb_release -a
No LSB modules are available.
Distributor ID: Debian
Description:    Debian GNU/Linux 8.6 (jessie)
Release:    8.6
Codename:   jessie
$ uname -a
Linux localhost 3.16.0-4-amd64 #1 SMP Debian 3.16.36-1+deb8u2 (2016-10-19) x86_64 GNU/Linux
$ gcc --version
gcc (Debian 4.9.2-10) 4.9.2
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Comments

-1

Not gonna lie, it seems as though you're handling too much in the "reverse function". I personally like to break down my code as much as possible, so that it's easier to find mistakes.

To start, you may want to put the swapping process (for loop) in its own function called "swap". You can do this with char pointers 'a' and 'b' as parameters.

1 Comment

Breaking code into smaller units is a good practice, but that doesn't really answering the question. Plus, this is kind of implied in stackoverflow.com/a/42063309/4234794 by use of a macro.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.