如何使用c类型数组作为ivar?

发布于 2024-08-13 09:03:52 字数 220 浏览 1 评论 0原文

我的程序中需要一个好的老式二维整数数组,但无论我如何尝试将其声明为 ivar,然后使用 @property/@synthesize,我都会收到一个或另一个编译器投诉。

我声明

int spotLocations[10] [10] 

为伊瓦尔。

这很有效,但是 @property/@synthesize 过程永远不会通过测试。

I need a good old-fashioned 2-dimensional array of integers in my program, but no matter how I try to declare it as an ivar, and then use @property/@synthesize, I get one compiler complaint or another.

I declare

int spotLocations[10] [10] 

as an ivar.

That much works, but then the @property/@synthesize process never passes muster.

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

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

发布评论

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

评论(2

南城追梦 2024-08-20 09:03:52

你不能这样做。在 C 中,数组变量永远不能是左值,这意味着你永远不能声明返回数组的函数,因为不可能将函数的结果分配给数组变量(因为它不能是左值)。

属性只是声明返回类型的函数的简写方式。由于函数永远不能返回数组,因此你永远不能声明一个数组属性。

如果您绝对需要像这样移动矩阵,您可以将其包装在一个结构中,该结构可以是左值:

typedef struct {
  int value[10][10];
} matrix;

...

@property matrix spotLocations;

当然,访问位置有点复杂,您必须使用

spotLocations.value[x][y]

You can't do this. Array variabless can never be lvalues in C, which means you can never declare a function that returns an array, because it would be impossible to assign the result of the function to an array variable (since it can't be an lvalue).

Properties are just a shorthand way of declaring a function that returns a type. Since functions can never return arrays, you can never declare a property that is an array.

If you absolutely need to move matrices around like this, you could wrap it in a struct, which can be lvalues:

typedef struct {
  int value[10][10];
} matrix;

...

@property matrix spotLocations;

Of course, accessing the locations is a little more convoluted, you have to use

spotLocations.value[x][y]
雨的味道风的声音 2024-08-20 09:03:52

将实例变量声明为指针,然后在 init 方法中动态创建数组。使用@property 声明的分配参数。

分配:

spotLocations = malloc(100 * sizeof(int));

通过执行以下操作来访问列和行:

int aValue = spotLocations[x + y * 10];

使用完毕后记得释放指针。

Declare the instance variable as a pointer and then dynamically create the array in your init method. Use the assign parameter for the @property declaration.

Allocation:

spotLocations = malloc(100 * sizeof(int));

Access a column and row by doing:

int aValue = spotLocations[x + y * 10];

Remember to free() the pointer when you're done with it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文