Pointers to Structures in Objective C
Last Updated :
17 Mar, 2023
A pointer is a variable whose value is the address of another variable, e.g., stores the address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store variable addresses. It simplifies the programs and reduces their length. It is useful for allocating and deallocating memory during program execution. It improves the execution speed of a program. A pointer is created using *, it is known as dereference operator. It works on a pointer and gives the value stored in that pointer. & also known as a unary operator to return the memory address of its operand.
Syntax:
DataType *VariableName;
Example:
int* geekI, adres;
geekI = 5;
adres = &c;
The actual numbers stored in the pointer vary with different calls to the same program on the same system. On different computers of the same type as the original, they will differ, on different types and will also differ.
Pointers to Structures
A pointer can also use to point to the address of the memory stored in a structure. In objective C, we can easily point to the structure using pointers with the help of the following steps:
Step 1: Defining a Pointer to the structure:
struct Students *struct_pointer;
Step 2: Storing the address of a structure in a variable using & operator:
struct_pointer = &Students;
Step 3: Accessing the member of the structure we use the -> operator:
struct_pointer->Name;
Example 1:
ObjectiveC
#import <Foundation/Foundation.h>
struct Students
{
NSString *Name;
NSString *Branch;
int id ;
};
@interface GFG: NSObject
- ( void ) studentData:( struct Students *) student;
@end
@implementation GFG
- ( void ) studentData:( struct Students *) student{
NSLog ( @"Student name: %@\n" , student->Name);
NSLog ( @"Student branch: %@\n" , student->Branch);
NSLog ( @"Student id : %d\n" , student-> id );
}
@end
int main( )
{
struct Students student;
student.Name = @"Ayush Agarwal" ;
student.Branch = @"CSE" ;
student. id = 190;
GFG *exclass = [[GFG alloc]init];
[exclass studentData:&student];
return 0;
}
|
Output:
Student name: Ayush Agarwal
Student branch: CSE
Student id: 190
Example 2:
ObjectiveC
#import <Foundation/Foundation.h>
struct Car
{
NSString *Name;
NSString *Color;
int modelNumber;
};
@interface GFG: NSObject
- ( void ) carData:( struct Car *) car;
@end
@implementation GFG
- ( void ) carData:( struct Car *) car{
NSLog ( @"Car name: %@\n" , car->Name);
NSLog ( @"Car color: %@\n" , car->Color);
NSLog ( @"Car model : %d\n" , car->modelNumber);
}
@end
int main()
{
struct Car car;
car.Name = @"Buggati" ;
car.Color = @"Silver" ;
car.modelNumber = 1234656;
GFG *C = [[GFG alloc]init];
[C carData:&car];
return 0;
}
|
Output:
Car name: Buggati
Car color: Silver
Car model : 1234656
Share your thoughts in the comments
Please Login to comment...