1

How can I set a pointer to a C array in my constructor?

@implementation NSBufferedInputStream {
    char *buffer;
    int bufferSize;
}

- (id)initWithFileAtPath:(NSString *)path
{
    self = [super initWithFileAtPath:path];
    if (self) {
        bufferSize = 100;
        buffer = char[bufferSize]; // ERROR: Expected expression
    }
}
@end
1
  • 1
    From a quick glance, I'd say its because c doesn't support dynamic arrays without using malloc or something like that. Commented May 7, 2012 at 1:48

2 Answers 2

1

If you truly need a dynamically-sized array,

- (id)initWithFileAtPath:(NSString *)path
{
    self = [super initWithFileAtPath:path];
    if (self) {
        bufferSize = 100;
        buffer = malloc(sizeof(char) * bufferSize);
    }
}

- (void)dealloc
{
    free(buffer);
    [super dealloc];
}

Otherwise, if your array size is known at compile time, just change your ivar from char *buffer; to:

char buffer[100]
Sign up to request clarification or add additional context in comments.

2 Comments

Why would you use dealloc if apple now has Automatic Reference Counting?
ARC cannot handle the freeing of your malloc() calls for you--if you use malloc(), you must use free(). So implementing -dealloc here is important--but if you are using ARC, you should not call [super dealloc]; as that will be handled automatically.
0

If the size of the array is dynamic - use malloc, if not, you need to do it at the declaration:

@implementation NSBufferedInputStream {
    char buffer[100];
    int bufferSize;
}

2 Comments

When you say dynamic, is it possible to increase the size of the array without copying its contents? That would be very useful. In this situation, I have a setBufferSize method in which I can change the buffer size before loading a file.
Would you know if NSMutableArray uses realloc? Currently I have a NSObject wrapper for my structs so I can use NSMutableArray and this is inefficient.

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.