Deal with char** and char* in Program C


  • 0
    J

    /**

    • Return an array of size *returnSize.

    • Note: The returned array must be malloced, assume caller calls free().

    • Example: given [0,1,2,4,5,7], return["0->2","4->5","7"]
      /
      char
      * summaryRanges(int* nums, int numsSize, int* returnSize) {
      char** results = (char**)malloc(sizeof(char*)numsSize);
      char
      temp = (char*)malloc(sizeof(char)*100);
      int current = nums[0];
      int head = nums[0];
      int tracker = 0;

      for(int i=1; i<numsSize; i++){
      if(nums[i]-current == 1){ //add into current temp array
      current = nums[i];
      printf("[%d]: %d -> %d \n", i, head, current); //this is test print line.
      }else{ //create new temp char array put into results
      char* temp = (char*)malloc(sizeof(char)*100);
      int2char(&temp, head, current);
      results[tracker] = temp;
      tracker++;
      head = nums[i];
      current = nums[i];
      }
      }

      return results;
      }

    void int2char(char** temp, int current, int nextone){
    int n = log10(current) + 1;
    char* cur = calloc(n, sizeof(char));
    int m = log10(nextone) + 1;
    char* next = calloc(m, sizeof(char));
    // int tsize = m+n+3; //with '->' and last one '\0'

    for(int i=0; i< n; i++, current/=10){
        cur[i] = current%10;
    }
    for(int j=0; j< m; j++, nextone/=10){
        next[j] = nextone%10;
    }
    for(int k=0; k<n; k++){
        (*temp)[k] = cur[k];
    }
    (*temp)[n] = '-';
    (*temp)[n+1] = '>';
    for(int q=n+2; q<n+2+m; q++){
        (*temp)[q] = next[q-n-2];
    }
    (*temp)[n+2+m] = '\0';
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.