AL-zami AL-zami - 1 month ago 9
C Question

array undeclared ,first used in the function error during dynamic memory allocation

Here i am writing a program which will do two things

1.get a number between 0 to 102,separate them and store them in an array

2.print the array for each number

For that purpose i wrote an if-else block which will initialize an array each time exactly according to the size of the current integer value which is denoted by variable called

num


Meaning that if i have a number of single digit it will create an array of one element,If number is two digit long it will create an array of two element.But whenever i run the code i get the error mentioned in question title.

What might be the reason for that and how to solve this issue?

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

int mirror(int num,int *arr,int i);

int main(){
int num=0,range=1;

while(num<102){
if(num<(int)pow(10,range))
{
int *arr =(int *)malloc(range*sizeof(int));
}else{
range+=1;
int *arr =(int *)malloc(range*sizeof(int));

}
int i = 0;
mirror(num,arr,i);
for(i=0;i<range;i++){
printf("%d ",arr[i]);
}
printf("\n");
num++;
}
}

int mirror(int num,int *arr,int i){

if(num == 0){
return 0;
}
arr[i] = num%10;
mirror(num/10,arr,++i);

}

Answer

The scope of pointer arr is only within the if-else block. So, it's not available outside of it. Declare it outside the if-else block and you'll be able to use it as you have.

      int *arr;

      if(num<(int)pow(10,range))
      {
          arr = malloc(range*sizeof(int));
      }else{
          range += 1;
          arr = malloc(range*sizeof(int));

      }

Notice I have removed the cast of the malloc() return value. It's needless in C and error-prone. See: http://c-faq.com/malloc/mallocnocast.html

Comments