在 Objective C 中重新定义/调整 C 数组的大小?

发布于 2024-09-19 19:38:42 字数 291 浏览 4 评论 0原文

我在 Objective C 中有一个 C 数组,定义如下:

id keysArray;

然后在 if 块中,我想根据条件重新定义数组:

if (somethingIsTrue){
    id keysArray[4][3];
}
else {
    id keysArray[6][1];
}

然后在 if 块之外,当我访问数组时,我收到错误消息 keysArray 不存在。

谢谢。

I have a C array in Objective C defined as follows:

id keysArray;

Then in an if block, i would like to redefine the array based on a condition:

if (somethingIsTrue){
    id keysArray[4][3];
}
else {
    id keysArray[6][1];
}

Then outside of the if block, when i access the array, i get errors saying the keysArray does not exist.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你丑哭了我 2024-09-26 19:38:44

这是因为当您离开 if 的范围时,该范围内定义的所有局部变量都将被销毁。如果你想这样做,你将不得不使用动态分配。我不知道 Objective C 的做事方式,但在常规 C 中你应该使用 malloc。

That's because when you leave the scope of the if, all local variables defined within that scope are destroyed. If you want to do this, you will have to use dynamic allocation. I don't know the Objective C way of doing things, but in regular C you shall use malloc.

南风几经秋 2024-09-26 19:38:44

C中,数组一旦创建,就无法更改大小。为此,您需要指针和 malloc() 以及朋友。

C99 中,有一个名为“可变长度数组”(VLA) 的新功能,它允许您使用在运行时定义长度的数组(但在对象的持续时间内是固定的) )

while (1) {
    /* C99 only */
    int rows = 1 + rand() % 10; /* 1 to 10 */
    int cols = 1 + rand() % 10; /* 1 to 10 */
    {
       int array[rows][cols];
       /* use array, different sizes every time through the loop */
    }
}

In C, once created, arrays cannot change size. For that you need pointers and malloc() and friends.

In C99 there's a new functionality called "variable length array" (VLA) which allows you to use arrays with lengths defined at run time (but fixed for the duration of the object)

while (1) {
    /* C99 only */
    int rows = 1 + rand() % 10; /* 1 to 10 */
    int cols = 1 + rand() % 10; /* 1 to 10 */
    {
       int array[rows][cols];
       /* use array, different sizes every time through the loop */
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文