在 Objective C 中将动态 C 数组作为实例变量进行存储和访问
我想将动态数组(指向)存储为对象中的实例变量,并且能够将数组初始化为自定义大小。就像这个简单的代码一样:
@interface DummyClass: NSObject {
float * X;
}
@property float * X;
@end
@implementation DummyClass
@synthesize X;
-(id) init {
[super init];
X = malloc(100*sizeof(float));
}
@end
int main(int argc, const char * argv) {
float * mypointer;
DummyClass * myclass = [[DummyClass alloc] init];
mypointer = myclass.X;
mypointer[0] = 1;
NSLog(@"Vallue assigned succesfully");
getchar();
return 0;
}
当尝试为 mypointer[0] 赋值时,会出现“分段错误”错误。在对象中存储和访问动态数组的正确方法是什么?
I would like to store (pointers to) dynamic arrays as the instance variables in objects, and be able to initialize the arrays to custom size. Like in this simple code:
@interface DummyClass: NSObject {
float * X;
}
@property float * X;
@end
@implementation DummyClass
@synthesize X;
-(id) init {
[super init];
X = malloc(100*sizeof(float));
}
@end
int main(int argc, const char * argv) {
float * mypointer;
DummyClass * myclass = [[DummyClass alloc] init];
mypointer = myclass.X;
mypointer[0] = 1;
NSLog(@"Vallue assigned succesfully");
getchar();
return 0;
}
This gives "Segmentation fault" error when trying to assign value to mypointer[0]. What's the proper way of storing and accessing dynamic arrays within objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
init
方法需要返回一些内容:在进行更改后(并且在更正
main
的签名之后),您的程序在这里运行良好。不过,您应该收到有关该错误的警告或错误。你是如何建造和建造的?测试你的示例程序?Your
init
method needs to return something:Your program runs fine for me here after making that change (and after correcting the signature of
main
). You should have had a warning or error about that mistake, though. How did you build & test your example program?