2

I'm new in C programming (my main area is java) and in java there exists the ArrayList which I can make like

    ArrayList<Class> arraylist = new ArrayList<Class>();

where my class Class can have several items, such as int, or string.

In c, I found I cannot do that but need to do something like that, so I did this

    typedef struct vectorObject {
      int myInt;
      char *charPointer;
    } vectorObject;

I define a pointer of my structure like this:

    vectorObject *listVectorObject;

and using

    #define MAX_FILE_SIZE   50000

when I want to allocate the memory of that, I use this:

    int i;
    listVectorObject = malloc(MAX_FILE_SIZE);
    if (listVectorObject == NULL ) {
         printf("Out of memory1\n");
         exit(1);
    }
    for (i = 0; i < MAX_FILE_SIZE; i++) {
         listVectorObject[i].charPointer= malloc(MAX_FILE_SIZE);
         if (listVectorObject[i].charPointer == NULL ) {
              printf("Out of memory2\n");
              exit(1);
         }
    }

The problem is I always get a

    Out of Memory2

I already tried everything and I cannot find where my mistake is. Could you please help me? Thanks!!

liwuen
  • 330
  • 2
  • 17

1 Answers1

3

I don't think you want 50000 vectorObjects each with 50000 bytes char-buffer.

So look at this:

  • first making a list of 1000 vectorObjects
  • then for each of those allocating a memory chunk to the char-pointer

.

int i, howmany= 1000;
vectorObject *listVectorObject = malloc(sizeof(vectorObject)*howmany);  // list of 1000 vectorObjects
if (listVectorObject == NULL ) {
     printf("Out of memory1\n");
     exit(1);
}

// one file-size char-pointer for each vector object above
for (i = 0; i<howmany; i++) {
     listVectorObject[i].charPointer= malloc(MAX_FILE_SIZE);
     if (listVectorObject[i].charPointer == NULL ) {
          printf("Out of memory2\n");
          exit(1);
     }
}
Nicholaz
  • 1,419
  • 9
  • 11
  • Thanks everyone for your response! It was the memory! (I stupidly thought it would not affect it... changed it to a smaller number and it worked like a charm!) Thanks again!! – liwuen Jun 04 '13 at 15:32
  • 1
    Glad to hear. Pls make sure to change the "sizeof(vectorObject)*howmany" in the first alloc also. – Nicholaz Jun 04 '13 at 15:33
  • Already did it! Wow I love the speed of your responses! Thanks again and sorry to bother you with such a dumb question (In java is not necessary to do this so I was a little bit confused) – liwuen Jun 04 '13 at 15:37
  • 2
    No worries, we already started there sometimes (and going fromm Java to C will be a path full of traps). – Nicholaz Jun 04 '13 at 15:38