Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In your code:</p> <pre><code>person * setName() { person * array; array = malloc (2 * sizeof(person)); array-&gt;name = strdup("Robert"); array++; array-&gt;name = strdup("Jose"); return array; } </code></pre> <p>you allocate space for two elements in the array and set <code>array</code> to point to the first:</p> <pre><code>+-------+ +----------+ | array | ---&gt; | array[0] | +-------+ +----------+ | array[1] | +----------+ </code></pre> <p>You then increment the element pointer with <code>array++</code> and <em>that</em> is what gets returned to the calling function at the end. That pointer points to the <em>second</em> array element which is why it seems to be wrong (and why you will almost certainly crash when you try to free that memory later by the way):</p> <pre><code>+-------+ +----------+ | array | -+ | array[0] | +-------+ | +----------+ +-&gt; | array[1] | +----------+ </code></pre> <p>What you need is:</p> <pre><code>person * setName() { person * array; array = malloc (2 * sizeof(person)); array[0].name = strdup("Robert"); array[1].name = strdup("Jose"); return array; } </code></pre> <p>as you've already pointed out. This solution does <em>not</em> change the <code>array</code> pointer at all. But, if you really want to use pointers, you can just reverse the actions of the <code>array++</code> with an <code>array--</code> before returning so that <code>array</code> is set back to the right value:</p> <pre><code>person * setName() { person * array; array = malloc (2 * sizeof(person)); array-&gt;name = strdup("Robert"); array++; array-&gt;name = strdup("Jose"); array--; return array; } </code></pre> <p>Or, another way, which doesn't change the original pointer, doesn't use array indexing and doesn't use a second pointer is to use pointer arithmetic. The compiler knows what type the pointer points to so can adjust the pointer correctly to find the next element (you already know that it knows how to do this since <code>array++</code> is shorthand for <code>array = array + 1</code> and that statement adjusts the value by the correct amount also):</p> <pre><code>person * setName() { person * array; array = malloc (2 * sizeof(person)); (array+0)-&gt;name = strdup("Robert"); (array+1)-&gt;name = strdup("Jose"); return array; } </code></pre>
 

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