Reversing Array in C?
13,569
Solution 1
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.
Solution 2
for loop condition should be 'i < n'. and prototype declaration should match.
Author by
JoC
Updated on June 04, 2022Comments
-
JoC almost 2 years
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); */
-
hasanoviz over 10 yearsdo changes to this array inside the
reverse
function actually take effect afterwards? because, not the pointer is sent as parameter. -
WhozCraig over 10 years@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.
-
Gangadhar over 10 years@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 -
Dmitri over 10 yearsHe doesn't need to divide n in half because he decrements it in the loop, though it's easy to miss that.
-
Jason Warner almost 4 yearsBreaking 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.