Advertisement
Guest User

q6

a guest
Mar 26th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. //program 1 crashes because no memory allocated at arr[index]
  2.  
  3. void setArr (int index, int v){
  4. int i = v;
  5. arr[index] = (int*)malloc(sizeof(int));//memory allocation required
  6. *(arr[index] )= i;
  7. }
  8.  
  9. program 2: gives wrong output because it store address of local declared and initialize value i;
  10.  
  11. corrected program(Arr3.c)
  12.  
  13. #include <stdio.h>
  14. #include<stdlib.h>
  15. void setArr (int, int);
  16.  
  17. int * arr[10]; // array of 10 int pointers, global variable
  18.  
  19. int main(int argc, char *argv[])
  20. {
  21. int i;
  22.  
  23. setArr(0, 0);
  24. setArr(1, 100);
  25. setArr(2, 200);
  26. setArr(3, 300);
  27. setArr(4, 400);
  28.  
  29. for(i=0; i<5;i++)
  30. printf("arr[%d] -*-> %d\n", i, *arr[i]); /* should be 0, 100, 200, 300, 400 */
  31.  
  32. return 0;
  33. }
  34.  
  35. /* set arr[index], which is a pointer, to point to an integer of value v */
  36. void setArr (int index, int v){
  37. int i = v;
  38. arr[index] = (int*)malloc(sizeof(int));//memory allocation required
  39. *(arr[index] )= i;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement