Thread: How do you find the amount of space in a char array?

  1. #1
    Registered User
    Join Date
    Jan 2013
    Posts
    55

    How do you find the amount of space in a char array?

    Please help.

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    You can use sizeof for a char array. If all you have is a pointer then there is no way.
    Kurt

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Most of the time you do it by looking at the source code and going "Oh there it is!", otherwise you save the value of the variable that was used to initialise a VLA.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  4. #4
    Registered User
    Join Date
    Jan 2013
    Posts
    55
    Well, this doesn't pop up my error message when I wrote this code though with sizeof :
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int Concatenate(char * Destination, char * StringToConcatenate);
    
    int main()
    {
        int Valid = 1;
    
        char String1[10] = {'T','h','e',' ','b','o','y','s',' '};
        char String2[7] = {'a', 'r', 'e', '.','.','.'};
    
        Valid = Concatenate(String1, String2);
    
        if (!Valid) printf("\n %s \n", String1); else printf("\n \a Not valid function parameters! \n \n");
    
        Valid = Concatenate(String1, String2);
    
        if (!Valid) printf("\n %s \n", String1); else printf("\n \a Not valid function parameters! \n \n");
    
        return 0;
    }
    
    int Concatenate(char * Destination, char * StringToConcatenate)
    {
    /* Sets charcount equal to the number of characters before the null terminator */
    int charcount = 0;
    char * Cptr;
    
    Cptr = Destination;
    
    while ( *Cptr != '\0') { charcount++; Cptr++; }
    
    /* ------------------------------------------------------ */
    
    /* Saves the data from the loop in a variable, and resets the pointer to the next array */
    
    int String1CharacterAmount = charcount;
    charcount = 0;
    Cptr = StringToConcatenate;
    
    /* ------------------------------------------------------ */
    
    /* Same as the first segment of code in this function, except it counts the 2nd array */
    
    while ( *Cptr != '\0') { charcount++; Cptr++; }
    
    int String2CharacterAmount = charcount;
    charcount = 0;
    
    /* ------------------------------------------------------ */
    
    if ((sizeof(Destination) / sizeof(char)) > (((sizeof(Destination) / sizeof(char)) - String1CharacterAmount) + ((sizeof(StringToConcatenate) / sizeof(char)) - String2CharacterAmount))) /* Makes sure there is enough space in the first array for the second */
    {
        /* Returns 1 if not enough space */
        return 1;
    } else
    {
        /* This function returns 0 after sucessful completion, and this function also
        removes the null character and adds it back after concatenation */
    
        int c = 0;
        Cptr = Destination;
    
        if (*(Cptr+(String1CharacterAmount + 1)) == '\0') { *(Cptr+(String1CharacterAmount + 1)) = ' '; }
    
        for (; c < String2CharacterAmount; c++)
        {
            *(Destination + (String1CharacterAmount + c)) = *(StringToConcatenate + c);
        }
    
        *(Destination + ((String1CharacterAmount) + 1 + (String2CharacterAmount))) = '\0';
    
        return 0;
    }
    
    /* ------------------------------------------------------ */
    }

  5. #5
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    All you have in Concatenate() is a pointers so sizeof won't help. You have to pass the sizes as well.
    Kurt

  6. #6
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    You are not putting '\0' at the end of your character arrays, so they are not strings.

    You should declare your strings like this:
    Code:
        char String1[10] = "The boys ";
        char String2[7] = "are...";
    That will automatically append '\0' to the end of the character arrays.

    Also, String1 is not large enough to hold "The boys are..." -> You need to declare it as a larger size.
    Fact - Beethoven wrote his first symphony in C

  7. #7
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Here are your array sizes:
    Code:
        char String1[10] = ...
        char String2[7] = ...
    And no, String1 clearly isn't large enough to hold a concatenated string 15 or 21 characters long.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  8. #8
    Registered User
    Join Date
    Jan 2013
    Posts
    55
    I know it isn't large enough, I was trying to make it pop up an error message...

  9. #9
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    the most likely error message you'll get is a SIGSEGV on linux, or on windows it'll be "the program has performed an illegal operation and will be terminated." those are both runtime errors.

    but that's not guaranteed. you are not going to get compiler errors for something the compiler can't possibly know about.

    also, your indentation could use a little work.
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

  10. #10
    Registered User
    Join Date
    May 2012
    Posts
    505
    Unlike some other languages, C doesn't tag arrays with their size. An array is passed about as a pointer to its first element, and you have to pass a length parameter separately.
    What's confusing is that when you declare an array, you can use the sizeof() operator to get the amount of memory in the array, and thus the number of elements. But this is really just a little quirk of the language. Almost always you want either dynamically allocated arrays, or to pass an array to to subroutine. So normally you can't use the sizeof() method.
    I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
    Visit my website for lots of associated C programming resources.
    https://github.com/MalcolmMcLean


  11. #11
    Registered User
    Join Date
    Jan 2013
    Posts
    55

    Problem solved!

    Thanks for all you help guys! This is the program I came up with
    at the end.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int Concatenate(char * Destination, char * StringToConcatenate, size_t DestinationSize, size_t StringToConcatenateSize);
    
    int main()
    {
        int Valid = 1;
    
        char String1[24] = {'T','h','e',' ','b','o','y','s',' ','\0'};
        char String2[7] = {'a', 'r', 'e', '.','.','.','\0'};
    
        size_t SizeOfDestination;
        size_t SizeOfStringToConcatenate;
    
        SizeOfDestination = sizeof(String1);
        SizeOfStringToConcatenate = sizeof(String2);
    
        Valid = Concatenate(String1, String2, SizeOfDestination, SizeOfStringToConcatenate);
    
        if (!Valid) printf("\n %s \n", String1); else printf("\n \a Not enough array space! \n \n");
    
        Valid = Concatenate(String1, String2, SizeOfDestination, SizeOfStringToConcatenate);
    
        if (!Valid) printf("\n %s \n", String1); else printf("\n \a Not enough array space! \n \n");
    
        return 0;
    }
    
    int Concatenate(char * Destination, char * StringToConcatenate, size_t DestinationSize, size_t StringToConcatenateSize)
    {
    
    /* Sets charcount equal to the number of characters before the null terminator */
    
        int charcount = 0;
        char * Cptr;
    
        Cptr = Destination;
    
        while ( *Cptr != '\0') { charcount++; Cptr++; }
    
    /* ------------------------------------------------------ */
    
    /* Saves the data from the loop in a variable, and resets the pointer to the next array */
    
        int String1CharacterAmount = charcount;
        charcount = 0;
        Cptr = StringToConcatenate;
    
    /* ------------------------------------------------------ */
    
    /* Same as the first segment of code in this function, except it counts the 2nd array */
    
        while ( *Cptr != '\0') { charcount++; Cptr++; }
    
        int String2CharacterAmount = charcount;
        charcount = 0;
    
    /* ------------------------------------------------------ */
    
        if (DestinationSize < ((DestinationSize - (DestinationSize - (String1CharacterAmount + 1))) + (StringToConcatenateSize - (StringToConcatenateSize - (String2CharacterAmount + 1))))) /* Makes sure there is enough space in the first array for the second */
        {
            /* Returns 1 if not enough space */
            return 1;
        } else
        {
            /* This function returns 0 after sucessful completion, and this function also
            removes the null character and adds it back after concatenation */
    
            int c = 0;
            Cptr = Destination;
    
            if (*(Cptr+(String1CharacterAmount + 1)) == '\0') { *(Cptr+(String1CharacterAmount + 1)) = ' '; }
    
            for (; c < String2CharacterAmount; c++)
        {
            *(Destination + (String1CharacterAmount + c)) = *(StringToConcatenate + c);
        }
    
        *(Destination + ((String1CharacterAmount) + 1 + (String2CharacterAmount))) = '\0';
    
        return 0;
    }
    
    /* ------------------------------------------------------ */
    }
    This program now works and displays an error message if the first array is too small.

  12. #12
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    I'm glad you figured it out.
    Your check on line 62 is far longer than it needs to be though. It could be just :
    Code:
        if (DestinationSize < String1CharacterAmount + String2CharacterAmount + 1)
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Measuring amount of bytes of stack space needed for code?
    By blernblan in forum C Programming
    Replies: 18
    Last Post: 06-04-2009, 09:39 PM
  2. Check char for a space or for end of array?
    By BC2210 in forum C Programming
    Replies: 10
    Last Post: 11-16-2008, 04:14 AM
  3. Help discarding a space in char array
    By cjohnman in forum C Programming
    Replies: 18
    Last Post: 05-13-2008, 09:48 AM
  4. Find space inside Array?
    By hajas in forum C Programming
    Replies: 4
    Last Post: 06-21-2007, 06:46 AM
  5. Amount of memory space need?
    By jnwk888hwq in forum C Programming
    Replies: 8
    Last Post: 10-25-2003, 02:55 PM