yroc yroc - 2 months ago 14
C Question

C Program to Get Characters into Array and Reverse Order

I'm trying to create a C program that accepts a line of characters from the console, stores them in an array, reverses the order in the array, and displays the reversed string. I'm not allowed to use any library functions other than

getchar()
and
printf()
. My attempt is below. When I run the program and enter some text and press Enter, nothing happens. Can someone point out the fault?

#include <stdio.h>
#define MAX_SIZE 100

main()
{
char c; // the current character
char my_strg[MAX_SIZE]; // character array
int i; // the current index of the character array

// Initialize my_strg to null zeros
for (i = 0; i < MAX_SIZE; i++)
{
my_strg[i] = '\0';
}

/* Place the characters of the input line into the array */
i = 0;
printf("\nEnter some text followed by Enter: ");
while ( ((c = getchar()) != '\n') && (i < MAX_SIZE) )
{
my_strg[i] = c;
i++;
}

/* Detect the end of the string */
int end_of_string = 0;
i = 0;
while (my_strg[i] != '\0')
{
end_of_string++;
}

/* Reverse the string */
int temp;
int start = 0;
int end = (end_of_string - 1);
while (start < end)
{
temp = my_strg[start];
my_strg[start] = my_strg[end];
my_strg[end] = temp;
start++;
end--;
}

printf("%s\n", my_strg);

}

Answer

It seems like in this while loop:

while (my_strg[i] != '\0')
{
    end_of_string++;
}

you should increment i, otherwise if my_strg[0] is not equal to '\0', that's an infinite loop. I'd suggest putting a breakpoint and look what your code is doing.