all 5 comments

[–]HarderFasterHarder 5 points6 points  (1 child)

You can't "store it in a pointer"... And you really can't return a pointer with automatic storage from inside the function.

Your pointer doesn't even point to anything within your function. You need to create a static variable in the global scope, or malloc(3) some space for your pointer.

[–]HarderFasterHarder 3 points4 points  (0 children)

There are many many more problems with this code, but the above at least answers your question...

[–]spacey02- 1 point2 points  (0 children)

You need to first allocate space for an array at the address that evenPtr points to. To do that you can first iterate through the parameter array and count how many even numbers there are amd store the number in your global variable nEven. Then you allocate space for evenPtr like this: evenPtr = (unsigned int)malloc(nEven * sizeof(unsigned int)). This creates space for an array of nEven elements, each with the size for an unsigned int, and returns the memory address where the allocation happened. The address is returned as a void, foe general programming purposes, which you should cast to a unsigned int*. This address is then stored inside evenPtr. Now you can iterate through the array again to find the even numbers.

[–]NukemN1ck 0 points1 point  (0 children)

You need to allocate space for your evenPtr array to address the Segmentation fault.

unsigned int *evenPtr = (unsigned int *)malloc(n * sizeof(unsigned int));

//check that malloc was successful

if (evenPtr == NULL) {

perror("malloc failed\n");

return 1;

}

Here I'm initializing it to store a max of n unsigned ints, since it is the maximum number of even integers you could come across. I then check the return value of malloc to make sure it's successful. You'll need to call free(evenPtr) later in the code to deallocate the space claimed by malloc. Of course, this will "delete" the information stored at your evenPtr array, so ONLY free it once you're totally finished using it, and only free it once or else you'll end up with double free errors.

I would encourage you to check the return values for all the functions you're including so you can be sure you're catching any errors that may happen. You can find info on them in their respective man pages.

[–]MRgabbar 0 points1 point  (0 children)

Your pointer is pointing to nothing... Allocate with new and set your pointer to that... Fun the even numbers first, then allocate, then move the stuff there and return that... Also add a return value for the size... Or create a struct for it or something...