Simple Question. Changing already assigned strings

This is a discussion on Simple Question. Changing already assigned strings within the C Programming forums, part of the General Programming Boards category; I can't get this simple example to work >_< Code: #include <stdio.h> main(){ char blah[]="dog"; int foo=3; if (foo==3){ char ...

  1. #1
    Registered User
    Join Date
    Jun 2007
    Posts
    4

    Simple Question. Changing already assigned strings

    I can't get this simple example to work >_<

    Code:
    #include <stdio.h>
    
    main(){
    char blah[]="dog";
    int foo=3;
    
    if (foo==3){
    char blah[]="cat";
    }
    
    printf("&#37;s",blah);
    }
    It prints dog -_-. I'm hopeless

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,801
    Code:
    if (foo==3){
    char blah[]="cat";
    }
    This creates a new blah variable local to this small block of code and which hides the original within said block of code and which disappears (is destroyed) once the bracket '}' is reached. The original is untouched. To do what you want you need to use the strcpy function. You need to be sure when you do this that the destination has enough space to store what you need to... which in this case is true.
    Code:
    if (foo==3){
        strcpy(blah,"cat");
    }
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User
    Join Date
    Jun 2007
    Posts
    4
    XD thank you very much it works now!

  4. #4
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,682
    You need int main and the return statment as well in you code. To make your code more perfect.

    ssharish2005

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple class question
    By 99atlantic in forum C++ Programming
    Replies: 6
    Last Post: 04-20-2005, 11:41 PM
  2. Simple question about pausing program
    By Noid in forum C Programming
    Replies: 14
    Last Post: 04-02-2005, 08:46 AM
  3. simple question.
    By InvariantLoop in forum Windows Programming
    Replies: 4
    Last Post: 01-31-2005, 11:15 AM
  4. simple scope question
    By 7stud in forum C++ Programming
    Replies: 18
    Last Post: 01-30-2005, 06:45 AM
  5. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21