Thread: struct with array of compile-time decided length via macro

  1. #1
    Registered User
    Join Date
    Jan 2020
    Posts
    4

    Question struct with array of compile-time decided length via macro

    I need something like this:

    Code:
    #define x 5;
    
    struct A{
        int array[x];
    };
    
    void main(void){
        struct A a = {0};
    
        for (int i = 0; i < x; ++i)
        {
            a.array[i] = rand();
        }
    }
    But it's complaining:
    line 1: error: expected ']' before ';' token
    line 10: error: expected expression before ';' token

    How do I make it work? I thought that macros were just like find/replace instructions for the compiler... Apparently not? I'm using gcc 9.3.0 targeting x86-64
    I'd rather not use something like

    Code:
    struct A{
        int* array;
    }
    because then the array's position in memory is not necessarily anywhere near the position of the struct. Apart from having to manually allocate the array's memory.
    Last edited by midyro edellve; 04-29-2020 at 11:25 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,201
    #defines don't normally end in a ;
    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
    Registered User
    Join Date
    Jan 2020
    Posts
    4
    Quote Originally Posted by Salem View Post
    #defines don't normally end in a ;
    Jeez, that was the problem. Thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sizeof struct with variable length array?
    By MOS-6581 in forum C Programming
    Replies: 5
    Last Post: 03-16-2015, 09:16 AM
  2. Length of string at compile time?
    By TriKri in forum C Programming
    Replies: 14
    Last Post: 05-23-2010, 11:16 AM
  3. So I decided to use function pointers in my code for the first time...
    By A10 in forum A Brief History of Cprogramming.com
    Replies: 12
    Last Post: 11-13-2007, 07:13 AM
  4. printing macro's at compile time
    By KIBO in forum Linux Programming
    Replies: 9
    Last Post: 06-28-2007, 08:11 AM
  5. Replies: 0
    Last Post: 11-29-2002, 10:24 PM

Tags for this Thread