Thread: Casting in C++

  1. #1
    Registered User
    Join Date
    Apr 2002

    Casting in C++

    Hi there??
    How do you convert the following operation from java to C++?

    ncols = (int) floor[0].length;

    where ncols = number of columns and floor is an array declared as: char floor[20[20];



  2. #2
    Well the operation will work in C++ except for the .length
    Since characters can only hold one letter floor[0]'s length is 1 unless it is empty.
    If you want the length of a whole array like for example:

    int ncols; //Create
    char array[20]; // Variables
    strcpy(array, "afewletters"); // Cope a string into the array

    ncols = strlen(array); // return length of string in the array

    I think this'll work but since i've got no compiler here in school i dont know....

    And a question. Why do you cast floor[0].length to int, isnt it an int already?

  3. #3
    Registered User
    Join Date
    Apr 2002
    Hi ?
    what i meant was i have a 2d array called floor[20][20] of type char. and i want to cast it, like this: int ncols = (int) floor[0].length;
    this is in java how do i convert it to C++??


  4. #4
    Fingerstyle Guitarist taylorguitarman's Avatar
    Join Date
    Aug 2001
    C++ doesn't have the length() mehtod that Java has so you have to figure it out yourself. As mentioned above, if it's a string you can use strlen() or another common way is:
    int length = sizeof( array ) / sizeof( array_type );
    // so in your case
    int length = sizeof( floor[0] ) / sizeof( char );
    This only works on static arrays however, trying this on dynamic arrays will result in the size of the pointer divided by the type .
    If you use Java's ability to have non-rectangular matrices then this gets more difficult.
    An easy solution would be to create a data type (struct or class) that has length variables you can easily access and set. Then you could use the same style of code.
    If a tree falls in the forest, and no one is around to see it, do the other trees make fun of it?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Casting
    By morvick in forum C++ Programming
    Replies: 2
    Last Post: 06-17-2007, 11:06 PM
  2. Casting Question (I think)
    By fayte in forum C Programming
    Replies: 6
    Last Post: 03-08-2006, 05:31 PM
  3. casting the system exstracted date into seperate ints
    By bazzano in forum C Programming
    Replies: 1
    Last Post: 08-30-2005, 12:17 AM
  4. Type casting
    By Lionmane in forum C Programming
    Replies: 28
    Last Post: 08-20-2005, 02:16 PM
  5. question about casting pointers/other types also??
    By newbie02 in forum C++ Programming
    Replies: 3
    Last Post: 08-07-2003, 05:01 AM