开发者

declaring integer array in objective c without NSArray.n

开发者 https://www.devze.com 2023-01-17 15:57 出处:网络
(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;

(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.


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.


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));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号