Code in C, same result in Custom Testcase, but Runtime Error when submit


  • 0
    S

    Hi, I wrote C code below. It runs fine in Custom Testcase with arguments ("glzamzp", 5), but meets Runtime Error. Please see the attached screenshot. Does anyone have solution for this?

    #include <stdio.h>
    #include <string.h>
    
    char *convert(char *s, int numRows) {
    	size_t length = strlen(s);
    
    	// no need to do conversion
    	if (numRows <= 1 || numRows >= length) {
    		return s;
    	}
    
    	// allocate memory
    	char *result = (char *) calloc(length, sizeof(char));
    	char **r = (char **) calloc(numRows, sizeof(char *));
    
    	int i = 0;
    	for (i = 0; i < numRows; i++) {
    		*(r + i) = (char *) calloc(length, sizeof(char));
    	}
    
    	// step =  1: down
    	// step = -1: up
    	int step = 1;
    
    	int row = 0;
    
    	// start to traverse s
    	for (i = 0; i < length; i++) {
    		// decide direction by setting step
    		if (row == 0) {
    			step = 1;
    		} else if (row == numRows - 1) {
    			step = -1;
    		}
    
    		// concatinate s[i] to r[i]
    		strncat(r[row], s + i, 1);
    		row += step;
    	}
    
    	// set result
    	for (i = 0; i < numRows; i++) {
    		strcat(result, r[i]);
    	}
    
    	// free memory
    	for (i = 0; i < numRows; i++) {
    		free(r[i]);
    	}
    	free(r);
    
    	return result;
    }
    

    0_1472499867560_Screen Shot 2016-08-29 at 14.43.41.png
    0_1472499876274_Screen Shot 2016-08-29 at 14.43.51.png


Log in to reply
 

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