Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><code>int *findFactors(int, int);</code> line says you wanna return pointer from this function (it's better to use asteriks closer to the type name: <code>int* moo();</code> - this prevents misunderstandings i think).</p> <p>If you wanna dynamically change function argument (which is better way than just return pointer), you should just use argument as if you have this variable already.</p> <p>And the last your mistake: <code>malloc(X)</code> allocates <code>X</code> <strong>bytes</strong>, so if you want to allocate memory for some array, you should use <code>malloc(N * sizeof(T));</code>, where <code>N</code> is the size of your array and <code>T</code> is its type. E.g.: if you wanna have <code>int *a</code>, you should do this: <code>int *a = (int*) malloc(10 * sizeof(int));</code>.</p> <p>And now here's your code, fixed (as for me):</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int findFactors(int, int*); int main(int argc, char **argv) { int numToFind, *factors = 0, cnt = 0; do { printf("Enter a number to find the factors of: "); scanf("%d", &amp;numToFind); } while (numToFind &gt; 100); cnt = findFactors(numToFind, factors); printf("%d has %d factors.\n", numToFind, cnt); return 0; } int findFactors(int N, int* factors) { if (!factors) factors = (int*) malloc(N * sizeof(int)); int count = 0; for (int i = 2; i &lt; N; i++) { if (N % i == 0) { factors[count++] = i; printf("%d is factor number #%d\n", i, count); } } return count; } </code></pre> <p><strong>Note:</strong> do not forget to initialize your pointers any time (as i did). If you do want to call function, passing a pointer as its argument, you must be sure it has value of <code>0</code> at least before function call. Otherwise you will get run-time error.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload