Recently I've been learning about Strings and Pointers in C and have learned that you can do some pretty cool things in C using pointer arithmetic which reversing a String is one of these things. The following is the code that I am working with:
#include <stdio.h>
#include <string.h>
void print_reverse_string(char s[])
{
size_t length = strlen(s);
char *beginning = s;
char *end = beginning + length - 1;
while(end >= beginning)
{
printf("%c", *end);
end = end - 1;
}
}
int main()
{
printf("Please enter string to reverse: ");
char input_string[20];
fgets(input_string, 20, stdin);
/* Get rid of new line character from fgets function */
input_string[strlen(input_string) - 1] = '\0';
printf("Reversed string: ");
print_reverse_string(input_string);
return 0;
}
My concern begins with the following line of code:
char *end = beginning + length - 1;
This assumes that the ending memory location of an array will always be greater than the beginning memory location. Is this something that I should be concerned about as a C programmer or can I always be guaranteed that
&randomArray[0] < &randomArray[1] < &randomArray[2] < .... < &randomArray[lastElement]
It's just that I have been reading about different memory spaces and how certain spaces grow upwards while others grow downwards, for example, the stack growing downwards and the heap growing upwards, and thought that there might be a possibility of arrays growing downward in size.
Could this occur on a certain architecture or am I overthinking this possibility?
char *end = beginning + length - 1; leads to undefined behavior when length == 0. Example: "ending memory location of an array will always be greater" may be true expect code wants it to be false. Pointer arithmetic such as beginning + length - 1 is only valid from the beginning of an object to 1 object past its end. So beginning + 0 - 1 is UB.
Subsequent (like in an array) objects' addresses compare in increasing order - regardless of their underlying values, but the arithmetic is valid only in a narrow range.
Better to do
char *end = beginning + length;
while(end > beginning) {
end = end - 1;
printf("%c", *end);
}
Side issue: Should the first character read via fgets() is '\0', the below code attempts input_string[SIZE_MAX] = '\0'
// do not use
input_string[strlen(input_string) - 1] = '\0';
// alternatives
if (*input_string) input_string[strlen(input_string) - 1] = '\0';
// or
input_string[strcspn(input_string, "\n")] = '\0';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With