0

I have an object Student with 4 attributes(age,name,department,surname). and I create an array of that object like this;

Student students[10] blah blah init blah.

then i want to use an Student array as argument for a method;

-(void) displayStudentInArray : (????) studentarray atIndex: (int) index {.....}

'???' are my problem. what do i write there? i ve no idea.

need help. i m new on objective c.

4 Answers 4

1

Rather than using C notation the array should be made like this:

NSArray *studentArray = [[NSArray alloc] initWithObjects: student1, student2, student2, ..., nil];

In which case the parameter type will be NSArray

-(void) displayStudentInArray : (NSArray *)studentarray atIndex: (int) index {.....}
Sign up to request clarification or add additional context in comments.

4 Comments

then how can i access in displayStudentInArray method, student2's name or attribute.
Student studentTwo = [studentArray objectAtIndex:1]; or in general Student chosenStudent = [studentArray objectAtIndex:index]; also, in the new SDK's you may use studentArray[index]
-(void) displayStudentInArray:(Student **) studentarray.... then i get bad access on next line in that method Student *studentTwo = studentarray[index]; ??
@makin11 I had suggested you use Objective C notation, I don't see a benefit of doing otherwise.
1

The preferred method for creating arrays is using NSArray (or NSMutableArray if you want to modify the array after it is created):

NSArray *array = [[NSArray alloc]initWithObjects:student1, student2...];

Then your method signature would be:

-(void)displayStudentInArray:(NSArray *)studentarray atIndex:(int)index

Comments

1

These answers are correct, but if you really want to use C notation, you just need to add another asterisk to denote a reference to another pointer:

- (void)displayStudentInArray:(Student**)studentArray atIndex:(int)index {
    Student* firstStudent = studentArray[1];
    //do what you want with the array
}

This is because C arrays are really just pointers to an address in memory. If you wanted a C array for a primitive, it would look like this:

int* arrayOfInts = malloc(yourSize * sizeof(int));

You have an array of objects, but the idea is just the same. You just add one more asterisk to denote that it's a pointer to a pointer to an object.

Student** students = ...

Comments

1

Just write

Student *tempStudent = (array)[0];

Comments

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.