pointers - dynamic allocation for an array in C -


 #define _crt_secure_no_warnings     #include <stdio.h>     #include <conio.h>     #include <stdlib.h>     int  *alocare(int *a, int *n)     {         printf("introduceti numarul de elemente din sir");         scanf("%d", n);         = (int*)(malloc(*n*sizeof(int))); //alocam memorie dinamica (in zona heap) pentru memorarea unui vector in mod dinamic de n elemente         if (!a)         {             printf("eroare la alocare\n");             return 0;         }         return a;      }     void citire(int *a, int n)     {         (int = 0; < n; i++)         {             printf("\telem %d\n", + 1);             scanf("%d", &a[i]);         }     }     void afisare(int *a, int n)     {         (int = 0; < n; i++)                 printf("%d\n", a[i]);      }     void main(void)     {         int *a, n;         a=alocare(a, &n);         citire(a, n);         afisare(a, n);         _getch();     } 

the error getting is

error c4700: unitialized local variable 'a' used.

how initialize variable a? , why must initialized? because have allocation function.

you passing a uninitialized in function call alocare(a, &n);. pointer dynamically allocated memory can returned function. remove parameter int *a , declare a local variable in alocare:

   int  *alocare(int *n)    {         printf("introduceti numarul de elemente din sir");         scanf("%d", n);         // local declaration of pointer         int *a = malloc(*n*sizeof(int));          if (!a)         {             printf("eroare la alocare\n");             return 0;         }         return a; }   

and make function call

a = alocare(&n); 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -