Thread: Declaring an array with an integer

  1. #1
    Registered User
    Join Date
    Apr 2007
    Posts
    4

    Declaring an array with an integer

    Hi,
    I want to create an array based on the result from a mysql query.

    ie.
    Code:
    int num_to_create;
    
    struct ftp_details {
    	char *host;
    	char *userpass;
    	char *options;
    	long sid;
    	long fid;
    };
    
    num_to_create = mysql_num_rows(res); // returns 1
    
    struct ftp_details ftpdetails_array[num_to_create];
    Later in program i get a segfault by code trying to use the array, however i can fix it by changing the code to

    Code:
    struct ftp_details ftpdetails_array[1];
    So is it possible to declare an array with an integer?

    Thanks,

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    It's permissible to do that if you are using a compiler that follows the C99 standard with that regard. If you are using a C89 compiler, it is not allowed.

    I would not recommend doing it, however. In a case like this, I would malloc() the needed memory. Memory allocated via malloc() comes from the heap while memory allocated like you are doing it comes from the stack. Stack sizes are usually limited, and there is no real way to check if you blew your limit. If you attempt to allocate memory from the heap, at least you'll be in a position to recover if the memory allocation fails.

  3. #3
    Registered User
    Join Date
    Apr 2007
    Posts
    4
    Ok Thanks.

    So to use malloc, I would have to change my char pointers to fixed length arrays?

    ie.
    Code:
    struct ftp_details {
    	char host[200];
    	char userpass[100];
    	char options[50];
    	long sid;
    	long fid;
    };

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    835
    Also, most compilers haven't fully implemented C99 yet, so until that happens it's probably a good idea to try to write code that complies with both C89 and C99, which in particular means not using C99-specific features.

  5. #5
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    No, you don't have to change them to fixed length arrays. If they are pointers, you can malloc() them as well, depending upon how long they need to be.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 07:25 PM
  2. Stack Overflow when declaring array
    By ejohns85 in forum C++ Programming
    Replies: 3
    Last Post: 04-03-2009, 05:00 AM
  3. Assignment HELP!!
    By cprogrammer22 in forum C Programming
    Replies: 35
    Last Post: 01-24-2009, 02:24 PM
  4. Converting Char Array Loop values to integer
    By azamsharp1 in forum C Programming
    Replies: 8
    Last Post: 10-27-2005, 09:13 AM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM