1
int* dividers_of(int x, int ammount){
int i,j = 1;
int* dividers = (int*)calloc(ammount,sizeof(int)); /* calloc initializes int array to 0!*/

for(i=0;i<ammount;i++){

    while( (x%j) != 0){
        j++;
    }

*(dividers+i) = j;

/*DOESNT WORK ( int* dividers stays on 0-0-0)
*dividers = j;
dividers++; */ 

j++;
}
return dividers;
}

I'm trying to find out what's wrong with the code that doesn't work, I'm assigning int j to *dividers and then making dividers point to the next int in its array. The result should be a pointer to an array which contains the int dividers of an int x.

Unfortunately the result if i do it like this is the following array:

dividers[] = {0,0,0};

which means nothing has changed since calloc fills the array like this.

Whats happening at

*dividers = j;
dividers++;

?

Arthur VP
  • 17
  • 5
  • It's spelled `amount`, not `ammount`. – melpomene Oct 28 '17 at 12:03
  • Don't [cast the result of `calloc`](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – melpomene Oct 28 '17 at 12:04
  • 1/ **We can't reproduce the issue.** This is a common issue for newcomers, so please read the FAQ within the help center of this website to learn how to write questions in such a way that you allow others to reproduce (and thus experiment with) the issue. I'm done linking directly to the section. If we're going to talk about courtesy, you should have read that entire section before you posted here. It's kind of rude to ignore the community standards like this. – autistic Oct 28 '17 at 12:22
  • Could you please add some examples of the expected outcome of your function? – Bob__ Oct 28 '17 at 12:22
  • 2/ Along-side your MCVE (you'll read about those when you read the entirety of our *help center* to discover what questions are appropriate here), I highly recommend linking with debug symbols (i.e. `gcc -g ...`) and attaching `valgrind` output to your question, because it seems like it'll be *one of those* questions... – autistic Oct 28 '17 at 12:26
  • 2
    `*(dividers+i)` is the same as `dividers[i]`. No need to increment pointers. – Bo Persson Oct 28 '17 at 12:53

1 Answers1

0

If you increment dividers in the loop:

    dividers++;

then it won't have its original value at the end:

return dividers;

With the increment, your function returns a pointer past the end of the array, not a pointer to the beginning of the array.

The easiest way to fix this is to save the original pointer in another variable at the start:

int *dividers = ...;
int *dividers_start = dividers;

/* ... modify dividers here ... */

return dividers_start;

But you could also use pointer arithmetic to undo the increment:

return dividers - ammount;
melpomene
  • 84,125
  • 8
  • 85
  • 148