title: When working with pointers in C, when and why do we need to use malloc?
body: <pre><code> /* Note: The returned array must be malloced,
      assume caller calls free(). */
  int* twoSum(int* nums, int numsSize, int target) {
      int *ans; //why error
      for(int i = 0; i &lt; numsSize; i++){
          for(int j = i+1; j &lt; numsSize; j++){
              if(nums[i] + nums[j] == target){
                  ans[0] = i;
                  ans[1] = j;
                  break;
              }
          }
      }
      return ans;
  }
  </code></pre>
  
  <p>Why code above is incorrect and code below correct (with <code>malloc</code> added)?</p>
  
  <pre><code> /* Note: The returned array must be malloced,
      assume caller calls free(). */
  int* twoSum(int* nums, int numsSize, int target) {
      int *ans = (int*)malloc(2*sizeof(int)); //why not error
      for(int i = 0; i &lt; numsSize; i++){
          for(int j = i+1; j &lt; numsSize; j++){
              if(nums[i] + nums[j] == target){
                  ans[0] = i;
                  ans[1] = j;
                  break;
              }
          }
      }
      return ans;
  }
  </code></pre>