2

I need some way to create N variables(number greater than 1) by for?
for example, something like that:

 int N=1000;   
 for(int i=0; i < N; i++){  
    char* var_i = malloc(sizeof(1));  
    } 

NOTE: I know that the code above is not working, I wrote it just for explain my intent.

Zakir
  • 2,222
  • 21
  • 31
StackUser
  • 309
  • 2
  • 10
  • 7
  • 3
    Unrelated to your question, but remember that `1` is an `int` which means that `sizeof(1)` is equal to `sizeof(int)`. – Some programmer dude Jun 05 '17 at 17:29
  • I thought about it and i know that it's working, but, i aksed if it can be implement by for-loop without an array - Namely, just with single variable any iteration . – StackUser Jun 05 '17 at 17:29
  • @StackUser: No, and you wouldn't want to do this anyway. This is a pretty common beginner's question, but the answer is 'learn to use collections' – Ed S. Jun 05 '17 at 17:30
  • 1
    As for your question, C doesn't have [*reflection*](https://en.wikipedia.org/wiki/Reflection_%28computer_programming%29), you can not "create" new variables at runtime. You can define a single variable inside the loop, whose lifetime will be the current iteration, but that variable will be defined and allocated by the compiler at the time of compilation. – Some programmer dude Jun 05 '17 at 17:30
  • Ok , thank you about your answers. – StackUser Jun 05 '17 at 17:31
  • Not a particularly good idea, but you may want to experiment with the same method as [99 bottles of beer](http://www.99-bottles-of-beer.net/language-c-c++-preprocessor-115.html). – pmg Jun 05 '17 at 18:11

2 Answers2

2

You can use array. Here is two examples:

#include <stdio.h>
#define N 10000

int main(void)
{
    char array[N];
    for (size_t i = 0; i < N; i++) {  
         /* Do what you want. */
    } 
    return 0;
}

Or if you want in heap:

#include <stdio.h>
#include <stdlib.h>
#define N 10000

int main(void)
{
    char *array = malloc(sizeof *array * N);
    if (array == NULL) {
        perror("Malloc");
        exit(EXIT_FAILURE);
    }
    for (size_t i = 0; i < N; i++) {  
         /* Do what you want. */
    } 
    free(array);
    return 0;
}
Overflow 404
  • 482
  • 5
  • 20
-1

If you want to declare N count variables...

#include<stdio.h>
#define CHUNK 64

const int N=10; //count of the variables

int main(void){
    char* vars[N], i; //declare the array of variables

    for(i=0;i<N;i++){ //alloc variables
        vars[i]=(char*)malloc(CHUNK*sizeof(char));
        if(!vars[i]){
            printf("out of memory!");
            return 1;
        }
    }

    //do stuff

    //free memory
    for(i=0;i<N;i++)
        free(vars[i]);

    return 0;
}
Adam
  • 33
  • 4