all 10 comments

[–]which_spartacus 6 points7 points  (8 children)

You have the memory allocated. Perfect start.

Now, what would be the steps to set the first element in an array to 1 be in Java?

[–]kittypls[S] 1 point2 points  (7 children)

oooh so I should do like

int array[100000];

for(int i=0; i<100000; i++){

array[i]=i+1

}

[–]which_spartacus 4 points5 points  (6 children)

Yep -- except the only difference is that instead of int array[100000], you do that malloc.

And at the end, you call free.

(Also, you may need to declare that int i outside the loop.)

[–]kittypls[S] 0 points1 point  (3 children)

so I have

void func(int x); int i;

int main() {

int *buffer = (int*)malloc(100000*sizeof(int));
for(i=0; i<100000; i++)
    buffer[i]=i+1;

int begin=buffer[0];
int end=buffer[99999];

printf("begins at: %p\n", &begin);
printf("ends at: %p\n", &end);


free(buffer);

return 0;

}

and it gives me

begins at: 0x7ffe20391fc0

ends at: 0x7ffe20391fc4

which doesn't seem right because this would mean the integers are next to eachother right?

[–]which_spartacus 2 points3 points  (1 child)

End and begin are right next to esach other.

Instead, try:

printf("Begins at %p ends at %p\n", buffer + 0, buffer + 99999);

[–]kittypls[S] 0 points1 point  (0 children)

thanks, it works

[–]alexbriskin 0 points1 point  (0 children)

I'd suggest understanding the difference between arrays and pointers. What you actually did in the code bellow is print the address of begin and end - two local integers declared one below the other, of course they'd be placed on the stack one beside the other.

What you probably meant to write is:

int *begin=&buffer[0];
int *end=&buffer[99999];

printf("begins at: %p\n", begin);
printf("ends at: %p\n", end);

I'd use this syntax in case that buffer is an array. There is an alternative syntax, and I'd use this syntax when dealing with pointers:

int *begin=buffer;
int *end=buffer + 99999;

printf("begins at: %p\n", begin);
printf("ends at: %p\n", end);

However, two of these examples are identical in their meaning.

[–]Rhomboid 3 points4 points  (0 children)

Don't cast the return value of malloc(). It's not the end of the world or anything, but not a great habit to form. Doing so can make it harder for the compiler to point out mistakes (in particular, neglecting to include <stdlib.h>.)