Thread: Length of string at compile time?

  1. #1
    Algorithm engineer
    Join Date
    Jun 2006
    Posts
    286

    Length of string at compile time?

    Hi. Is there any way to get the length of a constant string at compile time, by following ISO C? I have this test code:

    Code:
    #include <string.h>
    
    int main()
    {
        const char *text_base = "text base";
        char text_full[strlen(text_base) + 10];
        return 0;
    }
    It compiles, but I get the following warning:

    Code:
    main.c:6: warning: ISO C90 forbids variable length array 'text_full'
    Is there any way fix this so that it follows the C standard?
    Come on, you can do it! b( ~_')

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    I believe it is allowed under C99 but not C90. You may have to use a compiler switch, for gcc:

    gcc --std=c99

    The other option is to malloc text_full instead.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Algorithm engineer
    Join Date
    Jun 2006
    Posts
    286
    That's it! Thanks!
    Come on, you can do it! b( ~_')

  4. #4
    Making mistakes
    Join Date
    Dec 2008
    Posts
    476
    It's also possible to declare text_base as an array and use sizeof text_base.

  5. #5
    Algorithm engineer
    Join Date
    Jun 2006
    Posts
    286
    What is the practical difference between declaring text_base as an array and declaring it as a char*?
    Come on, you can do it! b( ~_')

  6. #6
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Not much. It might be easier to circumvent the const qualifier with a cast that way, but that's kind of irrelevant. Using const provides enough of a warning.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  7. #7
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    You can do something like:
    Code:
    #define YOUR_STRING "text base"
    
    const char *text_base = YOUR_STRING;
    char text_full[ sizeof(YOUR_STRING)-1 + 10 ];

  8. #8
    Making mistakes
    Join Date
    Dec 2008
    Posts
    476
    If you declare it an array, the compiler automatically knows its size.

  9. #9
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Quote Originally Posted by Bayint Naung View Post
    You can do something like:
    Code:
    #define YOUR_STRING "text base"
    
    const char *text_base = YOUR_STRING;
    char text_full[ sizeof(YOUR_STRING)-1 + 10 ];
    I don't think that works. Since YOUR_STRING is #define'd as a string literal, you're really just taking the size of a string literal. But I'm pretty sure this is just the same as taking the size of a char* and always evaluates to the size of a pointer (i.e. 4 on a 32-bit system). Also, you never use text_base . . . .

    I would definitely use an array, because then you can take the size of it.
    Code:
    char str[] = "Hello, World!\n";
    char copy[sizeof(str) + 10];
    The difference between a const char * and a char array is this. With a const char * initialized to a string literal like "hello", the string "hello" gets put into a special segment of the program -- usually the read-only .text segment, on Intel-compatible platforms. Your const char * variable just points to this memory location. A char[] array, however, is allocated on the stack (if it is an auto variable, declared inside a function) or in a read-write static data segment (if it is a global or static variable); the string literal that you initialized it to is copied into the array. An array is mutable and a literal is not.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  10. #10
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    sizeof on a string constant is a pretty neat way of looking at the problem
    Code:
    $ cat bar.c
    #include <stdio.h>
    int main ( ) {
        printf("%zd\n", sizeof("hello world") );
        return 0;
    }
    $ gcc bar.c
    $ ./a.out 
    12
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  11. #11
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Interesting -- I didn't know sizeof() would return the length of a string literal. I guess that means string literals must have type char[N] instead of char* like I thought they did.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  12. #12
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    sizeof() does not return length of string but total bytes (ie. including NUL byte for C string).

  13. #13
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875
    sizeof() does not return length of string but total bytes (ie. including NUL byte for C string).
    No it does not. The null is ignored:
    strlen

    Specifically:
    The strlen() function shall compute the number of bytes in the string to which s points, not including the terminating null byte.
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by dwks
    I guess that means string literals must have type char[N] instead of char* like I thought they did.
    Yes, a string literal is an array, not a pointer, though perhaps const char[N] comes closer.

    Quote Originally Posted by jeffcobb
    No it does not. The null is ignored:
    strlen
    strlen and sizeof are not the same thing
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875
    Quote Originally Posted by laserlight View Post
    Yes, a string literal is an array, not a pointer, though perhaps const char[N] comes closer.


    strlen and sizeof are not the same thing
    Thats what I get for replying before becoming fully caffeinated.
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling C in Visual Studio 2005
    By emanresu in forum C Programming
    Replies: 3
    Last Post: 11-16-2009, 04:25 AM
  2. C# Compile Time Debugging
    By mindtrap in forum C# Programming
    Replies: 4
    Last Post: 09-17-2007, 09:40 AM
  3. MSVC 7.1 Compile time
    By cboard_member in forum Tech Board
    Replies: 10
    Last Post: 08-05-2006, 04:04 PM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. Debugging mode selection during compile time
    By YALINI in forum C Programming
    Replies: 1
    Last Post: 09-03-2001, 09:56 AM

Tags for this Thread