2

(Question updated after first comment)

int max_size = 20;
int h[max_size];

Debugging gives a value of [-1] for h when using max_size to initialize;

If instead I initialize using an integer. So the code is:int h[20] , it works fine.

This was with GCC 4.2 on Mac OS X 10.6.

4
  • 6
    Works for me. It might help if you reduce it to a simple test case and update your question to include that code so we can see specifically what's going wrong. Commented Sep 27, 2010 at 22:14
  • +1 @Chuck. Anything you can do in C you can do in Objective-C. Commented Sep 27, 2010 at 22:39
  • 1
    Where are you declaring your array? Inside a method/function? Or in the global scope? And what exactly is -1 according to the debugger? Commented Sep 28, 2010 at 11:03
  • All the code is written in the same function scope. h[0] or h[max_size] gives -1. I'm using GCC 4.2 as a compiler. Commented Sep 29, 2010 at 19:59

2 Answers 2

2

I just compiled and ran the following program incorporating your code:

#import <Foundation/Foundation.h>

int main() {
    int max_size = 20;
    int h[max_size];

    h[0] = 5;
    NSLog(@"It is %d", h[0]);

    return 0;
}

It worked fine. The problem is something besides simply declaring an array.

This was with GCC 4.0.1 on Mac OS X 10.4.

Sign up to request clarification or add additional context in comments.

2 Comments

My complier is GCC 4.2 on Mac OS X 10.6. And if I change it to LLVM GCC 4.2, then it works fine, but I don't see the variable in my debugger window. I don't even know what LLVM is. There must be an alternate solution.
In this case the compiler knows that max_size can not be changed between the first two lines of your function thus it can decide the size if the h array at compile time. Your code will not work if the value of max_size is calculated in a more complicated way.
0

If I recall correctly, some compilers need to know the size of stack-allocated arrays explicitly at compile-time. This (possibly) being the case, you could make your max_size variable const or an #define macro (or an integer literal, as you've done.) Alternatively, you could dynamically allocate the array and then the size could be any-old variable

ex:

int *array = calloc(max_size, sizeof(int));

2 Comments

This is not the case for GCC, and when it is the case, a compiler that doesn't support that feature will normally flag the declaration as an error rather than silently compiling nonsense.
Ah, that shows some ignorance on my part. Thanks for the correction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.