Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //program 1 crashes because no memory allocated at arr[index]
- void setArr (int index, int v){
- int i = v;
- arr[index] = (int*)malloc(sizeof(int));//memory allocation required
- *(arr[index] )= i;
- }
- program 2: gives wrong output because it store address of local declared and initialize value i;
- corrected program(Arr3.c)
- #include <stdio.h>
- #include<stdlib.h>
- void setArr (int, int);
- int * arr[10]; // array of 10 int pointers, global variable
- int main(int argc, char *argv[])
- {
- int i;
- setArr(0, 0);
- setArr(1, 100);
- setArr(2, 200);
- setArr(3, 300);
- setArr(4, 400);
- for(i=0; i<5;i++)
- printf("arr[%d] -*-> %d\n", i, *arr[i]); /* should be 0, 100, 200, 300, 400 */
- return 0;
- }
- /* set arr[index], which is a pointer, to point to an integer of value v */
- void setArr (int index, int v){
- int i = v;
- arr[index] = (int*)malloc(sizeof(int));//memory allocation required
- *(arr[index] )= i;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement