Thread: String as parameter not working properly

  1. #1
    Registered User
    Join Date
    Oct 2012
    Posts
    12

    String as parameter not working properly

    Hello guys, I want to alter a string inside a function, but it is not working.

    Here is the function:

    Code:
    #include <stdio.h>
    
    void test (char *ch){
           ch[0] = 0;
           ch[1] = 1;
           ch[2] = '\0';
    }
    
    int main(){
           int i;
           char ch[20];
    
           test(ch);
    
           for(i=0;i<20 && ch[i] != '\0';i++){
                        printf("%c", ch[i]);
           }
    
            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,661
    > ch[0] = 0;
    > ch[1] = 1;
    Since 0 is the same as '\0', I'd say it works perfectly and doesn't print anything at all.

    Perhaps you expected to see "01" printed, in which case you need
    ch[0] = '0';
    ch[1] = '1';
    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
    Jun 2005
    Posts
    6,815
    Yes, indeed. The character that causes a zero to be printed does not have a value of zero (i.e. a test "0 == '0'" is always false). That is true for all real-world character sets.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. for loop not working properly
    By David_Baratheon in forum C Programming
    Replies: 18
    Last Post: 05-10-2012, 02:59 AM
  2. Not Working properly
    By Tejas Sanap in forum C Programming
    Replies: 7
    Last Post: 05-10-2011, 06:52 AM
  3. Fscanf not working properly
    By thefinalhero in forum C Programming
    Replies: 9
    Last Post: 10-05-2009, 10:06 AM
  4. '<=' operator not working properly?
    By fattysmo in forum C++ Programming
    Replies: 7
    Last Post: 05-05-2008, 02:51 PM
  5. tic tac toe not working properly
    By h_howee in forum Game Programming
    Replies: 2
    Last Post: 01-01-2006, 01:59 AM