0

Hi I wrote a program below. It's a program, that saves the letters backwards in an Array, when the user gives a string.


int main(){

    char string[100];
    char gnirts[100];

    int i, j;

    printf("String : ");
    scanf("%s", string);

    int size = sizeof(string)/sizeof(char);

    for(i=size-1, j=0; 0<=i ; i--, j++){
        gnirts[j] = string[i]; 
    }

    for(i=0; i<size; i++){
        if(gnirts[i])
            printf("%c", gnirts[i]);
    }

    return 0;
}

I gave the program String : asdf and received �i���i���i�fdsa

At the beginning I set the size of string as 100. And then with the line int size = sizeof(string)/sizeof(char); I set Array string with the size, that depends on what the User gives. But it's not working. I got a trash values before the meaningful values.

How can I delete the trash values and set a new size of the Array string and get the right result?

Thank you.

salami2
  • 3
  • 1

1 Answers1

0

sizeof(string) gives you the size of the entire array in bytes, not the number of characters in the string.

To get the length of the string, you want strlen:

int size = strlen(string);
dbush
  • 205,898
  • 23
  • 218
  • 273