Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I change the size of Array?(and how can I throw the trash values of Array?)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Thank you.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading