Thread: Character arrays - constant values in a constant expression

  1. #1
    Registered User
    Join Date
    Feb 2017
    Posts
    14

    Character arrays - constant values in a constant expression

    Hi, does anyone know why I can use 'sizeof()' but not 'strlen()' for defining the size of an array. I get the following error message in the picture I've attached:

    Character arrays - constant values in a constant expression-problem-png

    Thanks in advance.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,487
    Because sizeof() is evaluated at compile time, whereas strlen() is evaluated at run-time.

    Also, only C99 supports variable length arrays of the form you're using.

    What you need to write in C++ is
    char *asterisk = new char[ strlen(s) + 1 ];
    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.

  3. #3
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    What you need to write in C++ is:
    std::string asterisk;
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 05-17-2016, 06:35 AM
  2. expected constant expression?
    By GroogFish in forum C Programming
    Replies: 3
    Last Post: 05-08-2012, 12:17 AM
  3. illegal constant expression
    By nta in forum C Programming
    Replies: 3
    Last Post: 03-13-2008, 11:35 AM
  4. Does every expression results into constant value?
    By forumuser in forum C Programming
    Replies: 12
    Last Post: 04-18-2007, 08:08 AM

Tags for this Thread