mardi 27 janvier 2015

Why doesn't this program reverse a string?

I am learning C. I wrote the following program to try and reverse a user-input string. However, it doesn't work. I'd like to know why.


Here is the code with comments:



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

int main(int argc, char** argv) {
char* normal; // initialize the original string
printf("Give me a word.\n"); // ask for user input
scanf("%s", &*normal); // retrieve input, set variable
int n = strlen(normal); // retrieve length of string
char reversed[10] = {0}; // declare reversed string

// for loop starting from n length, decrementing by one
for(int i = n; i >= 0; i--) {
/* for i in the original string, the reversed string
equals n minus i, to reverse the string one by one */
normal[i] = reverse[n - i];
}

// print the newly reversed string
printf("%s\n", reversed);

return 0;
}

Aucun commentaire:

Enregistrer un commentaire