1 / 12

Today’s Agends

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);

tieve
Download Presentation

Today’s Agends

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Today’s Agends Structures and pointers Function returning pointers Dynamic Memory Allocation

  2. Function returning pointer • Example • Write a function sum() to add n natural numbers • This function should return a pointer for returning sum.

  3. int main() { int n=10; int *p; p = sum(n); printf("sum=%d\n",*p); }

  4. #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; }

  5. Complex number operations using pointers

  6. #include<stdio.h> #include<stdlib.h> typedef struct { int real; int img; }complex;

  7. 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); }

  8. 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; }

  9. void print(complex *c) • { • printf("real = %d img = %d\n",c->real,c->img); • }

  10. complex add1(complex *c1,complex *c2) • { • complex c; • c.real = c1->real + c2->real; • c.img = c1->img + c2->img; • return c; • }

  11. 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; • }

  12. void add3(complex *c1,complex *c2,complex *c) • { • c->real = c1->real + c2->real; • c->img = c1->img + c2->img; • }

More Related