Saving some variables in an array using for loop


I want to save some variables in an an array(a) using for loop. here those variables are even numbers.

I used below code using malloc function in stdlib.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<stdio.h>
#include<stdlib.h>

int main(){
    int *a; //single dimension array
    int i;
    for(i=0;i<=20;i++){
        if(i%2==0){
        a=malloc(i * sizeof(int));
        printf("%d\n",i);
        }
    }
    return 0;
    
}


But its returning this error

error: invalid conversion from 'void*' to 'int*' [-fpermissive]
malloc function is of type void* which returns no data. you need to cast it to int* first

a = (int*) malloc(i*sizeof(int));

Refer http://www.cplusplus.com/reference/cstdlib/malloc/
It dosent seems to work

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<stdio.h>
#include<stdlib.h>

int main(){
    int *a; //single dimension array
    int i;
    for(i=0;i<=20;i++){
        if(i%2==0){
        a = (int*) malloc(i*sizeof(int));
        printf("%d\n",i);
        }
    }
    
     printf("%d\n",a[2]);
    
    return 0;
    
}


output I expected is 4 in the last but it give zero

1
2
3
4
5
6
7
8
9
10
11
12
0
2
4
6
8
10
12
14
16
18
20
0
closed account (LA48b7Xj)
Define an array instead of a pointer, and don't use malloc. I modified your program a little. You were creating a new array in dynamic memory every other loop iteration and not deleting them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<cstdio>

using namespace std;

int main(){
    int a[11];
    int top = 0;

    for(int i=0;i<=20;i+=2)
        a[top++] = i;

    for(auto e : a)
        printf("%d\n",e);
}

Last edited on
Yes as Krako said do not use malloc function. You can easily store even integers in an array using for loop. Krako has shown the code.
Last edited on
@krako @kamal this works when array size is known but what if the size of the array is unknown. what should then we do ?
Topic archived. No new replies allowed.