variable declaration

If i declare any variable inside any loop then how can it be used outside of that loop?

eg:->

int main()
{ int t;
scanf("%d",&t);

for(l=0;l<t;l++)
{
char *a=(char*)malloc(sizeof(char));
gets(a);
it=strlen(a);
char c[t][it];   // it has to de declared inside...
}

for(l=0;l<t;l++)
{printf("%c",c[l][io]);}    // how can we use it here...

}

///// if, any other solution then please help…

The scope of variables is limited to the subpart they are declared in . If you try to use it and it is still in the memory then it is fine but in real world these memory locations get occupied almost immediately when their scope gets over . So it is not at all advisable .

You can declare the variable outside of the loop to use them in other loop .

This link would be helpful : https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope

1 Like

then how can we declare a dynamic 2d array?
or without knowing its length

we can declare a dynamic array because it is stored in a heap and you need to explicitly delete it . The normal variables are stored on a stack which get deleted when their scope get over .

You can declare an array with the maximum memory that will be used anytime in the program .

Why dont you try something on this lines-

if(l==t-1)
{
//print here
break; //break out of loop
}

But whats suggested by @trashmaster is the best method, which you will find yourself frequently using :slight_smile:

maximum memory will occupy much space …

couldn’t get u?
where to use this?

for(l=0;l<t;l++)
{
char *a=(char*)malloc(sizeof(char));
gets(a);
it=strlen(a);
char c[t][it];   // it has to de declared inside...
}

Here. Do the stuff in this loop and in last iteration print it and break out. :slight_smile:

Dont worry about memory consumption till you are within limits. Array of size ~{10}^{7} are fine always. Memory efficiency wont net you things, time efficiency will.

arrays of 107 have to be declared globally i guess?

Well, not sure. I always do declare them globally though. But i have also had instances where multiple arrays of {10}^{6} worked fine, so I think we can safe round off K*{10}^{6} to {10}^{7}

it’s working in the codechef IDE today :stuck_out_tongue: I remember getting a SIGSEGV because of local declaration long time back

Locally on our own machine , when using linux , I have seen that there is no limit on memory until the ram gets full and then my machine froze .

I get a segmentation fault on my mac when declaring array of 10^7 locally. Global arrays do work perfect!

I was talking about global only :slight_smile:

thanks will try