Thread: string array arithmetic

  1. #1
    Temporal Apparition qubit67's Avatar
    Join Date
    Jan 2007
    Posts
    85

    string array arithmetic

    I am trying to disscet this string into 2 parts at the char ';'
    Code:
    "crafted;def6049"
    
    the strlen of this is 15
    
     phrase_len = strcspn (buffer, ";");
    
    phrase_len = 7
    
     phrase = (char *) safe_malloc ((phrase_len + 1) * sizeof (char));
    Am i right to malloc for the extra byte concerning the NULL?

    Wont this create a string array starting at 0 finishing at 8 and then if i copied "crafted" to phrase, I would be left with 2 spaces at the end instead of one for the null.

    Is that right?

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Code:
     0   1   2   3   4   5   6   7
    'c' 'r' 'a' 'f' 't' 'e' 'd' '\0'
    8 bytes is what you need, and they are numbered 0..7.

    malloc counts the number of bytes, so 8 would be the correct value. You can check this by adding one extra byte, and assign this to some value, such as 0xAA, then check that you have 0x00, 0xAA at after the 'd' in the above string.

    --
    Mats
    Last edited by matsp; 09-12-2007 at 04:05 AM.
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Temporal Apparition qubit67's Avatar
    Join Date
    Jan 2007
    Posts
    85
    thanks for the explainantion

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Custom String class gives problem with another prog.
    By I BLcK I in forum C++ Programming
    Replies: 1
    Last Post: 12-18-2006, 03:40 AM
  2. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM
  3. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  4. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM