Thread: Printing back arrays

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    46

    Printing back arrays

    I'm trying to print back an arrays of char's but all I'm getting is garbage? Anyone know a better way to do this?

    #include <stdio.h>

    int main ( ) {

    int SIZE = 80;

    char string[SIZE];

    printf("Input a sentance: ");
    scanf("%s", &string);

    for(int i=1;80>=i;i++){
    putchar(string[--SIZE]);
    }

    return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    The array is initialised with garbage characters, and scanf will not necessary write to the whole array.

    You should call strlen to determine the number of valid characters in the array.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Sep 2001
    Posts
    46
    Thanks you.

  4. #4
    Registered User
    Join Date
    Aug 2001
    Posts
    247
    Hi this should fix it............
    Code:
    #include <stdio.h>
    #include <string.h>
    #define SIZE  80  
    
    int main ( ) { 
    
    char string[SIZE];
    int len; 
    
    printf("Input a sentance: "); 
    /*scanf will read to first space character so use*/
    gets(string);
    /*  loop initialized to string length minus null char*/
    /*  then decrement until = to first element = 0  */ 
    len = strlen(string) - 1;
    for(i = len; i >= 0; i--)    /* post decrement*/
           putchar(string[i]);     /* not SIZE but i  */
    }
    hoping to be certified (programming in c)
    here's the news - I'm officially certified.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C# Printing Problem
    By silverlight001 in forum C# Programming
    Replies: 0
    Last Post: 03-23-2009, 01:13 AM
  2. seperating initialising and printing of arrays into functions
    By Tom Bombadil in forum C Programming
    Replies: 1
    Last Post: 03-11-2009, 11:47 AM
  3. Function to read in two arrays
    By ssmokincamaro in forum C Programming
    Replies: 7
    Last Post: 11-12-2008, 07:59 AM
  4. handling file rb+ (write back into self)
    By IsmAvatar2 in forum C Programming
    Replies: 5
    Last Post: 01-23-2007, 09:47 PM
  5. Crazy memory problem with arrays
    By fusikon in forum C++ Programming
    Replies: 9
    Last Post: 01-15-2003, 09:24 PM