Thread: quick casting question

  1. #1
    Registered User
    Join Date
    Feb 2002

    quick casting question

    char name[3]="456";
    int i=(int)name;

    i need to cast from a char array to an int. in this scenerio, it prints this to the screen


    can anyone help?

  2. #2
    Registered User
    Join Date
    Feb 2002
    You need to use atoi(name). This function is included in stdio.h or stdlib.h, not sure which.

    >>> int i = atoi(name);

    You can also use atof() to change it to a double.

    Also, your print should look like this:

    printf("%d", i);

  3. #3
    Join Date
    Aug 2001
    Groningen (NL)
    The variable name points to the start of the array. It is a pointer, so when you print name, you print the address of name [0]. In other words, i has the value &name[0].

    You cannot cast a string to an int. As drharv pointed out, you could use atoi, or write your own conversion function.

  4. #4
    Registered User
    Join Date
    Oct 2001
    char name[3]="456";
    This is incorrect, because the declared dimension of the char-array "name" is too low because the string "456" will be terminated (like all strings in C) by '\0' (usually ASCII 0). In your code the memory after "name" will be overwritten by the terminating '\0'. But the overwritten memory could be important and your system may crash or produce errors.
    You could write it as
    char name={'4', '5', '6'};
    but then the compiler canīt find the stringīs end.
    The correct version would so be:
    char name [4]="456";
    char *name="456";

    Last edited by klausi; 03-06-2002 at 08:59 AM.
    When I close my eyes nobody can see me...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. quick question (adding characters)
    By Cactus in forum C Programming
    Replies: 2
    Last Post: 09-24-2005, 03:54 PM
  2. very quick question.
    By Unregistered in forum C++ Programming
    Replies: 7
    Last Post: 07-24-2002, 03:48 AM
  3. quick question
    By Unregistered in forum C++ Programming
    Replies: 5
    Last Post: 07-22-2002, 04:44 AM
  4. Quick Question Regarding Pointers
    By charash in forum C++ Programming
    Replies: 4
    Last Post: 05-04-2002, 11:04 AM
  5. Quick question: exit();
    By Cheeze-It in forum C Programming
    Replies: 6
    Last Post: 08-15-2001, 05:46 PM