Untitled
unknown
plain_text
2 years ago
2.3 kB
4
Indexable
/* Author: Jason Fedin Purpose: This program is going to calculate the area of a rectangle */ // #include <stdio.h> // #include <stdlib.h> // #include <string.h> // int * parse_numbers(char *input, int *n_array){ // int count = 0, i = 0, ix = 0; // printf("Input : %s\n", input); // while(input[i]){ // if(input[i] == ',') // count++; // i++; // } // char *str = strdup(input); // if (str == NULL) { // fprintf(stderr, "Memory allocation failed\n"); // exit(1); // Exit with an error code // } // printf("Counter : %d\n", count + 1); // *n_array = count + 1; // int *array = calloc(count + 1, sizeof(int)); // char *token = strtok(str, ","); // while(token != NULL){ // printf("Token : %s \n", token); // array[ix] = (int)strtol(token, NULL, 10); // token = strtok(NULL, ","); // ix++; // } // free(str); // return array; // } // int main() // { // char *str = "2,3,5"; // int n_arr = 0, *arr = NULL, i = 0; // arr = parse_numbers(str, &n_arr); // for(int i = 0; i < n_arr; i++){ // printf("Array %d : %d \n", i, arr[i]); // } // return 0; // } #include <stdio.h> #include <stdlib.h> #include <string.h> int * parse_numbers(char *input, int *n_array){ int count = 0; int i = 0; int ix = 0; printf("Input : %s\n", input); while(input[i] != '\0'){ if(input[i] == ',') count++; i++; } char *str = strdup(input); if (str == NULL) { fprintf(stderr, "Memory allocation failed\n"); exit(1); } printf("Counter : %d\n", count + 1); *n_array = count + 1; int *array = calloc(count + 1, sizeof(int)); char *token = strtok(str, ","); while(token != NULL){ printf("Token : %s \n", token); array[ix] = atoi(token); // Using atoi instead of strtol token = strtok(NULL, ","); ix++; } free(str); return array; } int main() { char *str = "2,3,5"; int n_arr = 0; int *arr = NULL; arr = parse_numbers(str, &n_arr); for(int i = 0; i < n_arr; i++){ printf("Array %d : %d \n", i, arr[i]); } free(arr); return 0; }
Editor is loading...
Leave a Comment