120 likes | 244 Views
Today’s Agends. Structures and pointers Function returning pointers Dynamic Memory Allocation. Function returning pointer. Example Write a function sum() to add n natural numbers This function should return a pointer for returning sum. int main() { int n=10; int *p; p = sum(n);
E N D
Today’s Agends Structures and pointers Function returning pointers Dynamic Memory Allocation
Function returning pointer • Example • Write a function sum() to add n natural numbers • This function should return a pointer for returning sum.
int main() { int n=10; int *p; p = sum(n); printf("sum=%d\n",*p); }
#include<stdio.h> #include<stdlib.h> int* sum(int n) { int *psum; psum = (int *)malloc(sizeof(int)); *psum = 0; inti ; for(i=0;i<n;i++) *psum = *psum + i; return psum; }
#include<stdio.h> #include<stdlib.h> typedef struct { int real; int img; }complex;
int main() { complex c1,*c2,c3,*c4,*c5; read(&c1); c2 = read1(); printf("c2 ***%d %d\n",c2->real,c2->img); print(&c1); print(c2); c3 = add1(&c1,c2); printf("Addition using add1()****\n "); print(&c3); c4 = add2(&c1,c2); printf("Addition using add2()****\n "); print(c4); add3(&c1,c2,c5); printf("Addition using add3()****\n "); print(c5); free(c2); }
void read(complex *c) { printf("enter complex number c\n"); scanf("%d %d",&c->real,&c->img); } complex *read1(void) { complex *c; c = (complex*)malloc(sizeof(complex)); printf("enter complex number c\n"); scanf("%d %d",&c->real,&c->img); return c; }
void print(complex *c) • { • printf("real = %d img = %d\n",c->real,c->img); • }
complex add1(complex *c1,complex *c2) • { • complex c; • c.real = c1->real + c2->real; • c.img = c1->img + c2->img; • return c; • }
complex *add2(complex *c1,complex *c2) • { • complex *c; • c = (complex *)malloc(sizeof(complex)); • c->real = c1->real + c2->real; • c->img = c1->img + c2->img; • return c; • }
void add3(complex *c1,complex *c2,complex *c) • { • c->real = c1->real + c2->real; • c->img = c1->img + c2->img; • }