Advertisement
mateuspl

gifnass() problem

Jan 15th, 2013
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.52 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. /* gianass = Get Integer From "Numbers And Spaces" String */
  6. /* gianass(str[], lim) have to return an array with the integers
  7.  * from a given string. */
  8. /* str[] is that string and lim is the maximum number of digits */
  9. int *gianass(char str[], int lim) {
  10.     int strSize = strlen(str),
  11.         curdig = 0, // current digit
  12.         times = 0, // amount of integers
  13.         a, // any use
  14.         *got; // pointer to memory where the intergers will be allocated
  15.     char    digit[lim];
  16.  
  17.     got = (int *) calloc(1, sizeof(int)); // allocating just one space
  18.     for (a = 0; a < strSize; a++) {
  19.         /* \/ it will take only numbers to digit[curdig] \/ */
  20.         if (str[a] != ' ') {
  21.             digit[curdig] = str[a];
  22.             curdig++;
  23.         }
  24.         if (str[a] == ' ' && curdig != 0) {
  25.             if (times != 0) { // if it's not the first time
  26.                 got = realloc(got, (times + 1) * sizeof(int)); // reallocate more memory
  27.             }
  28.             digit[curdig] = '\0'; // finish the digit
  29.            
  30.             /* \\  //                 \\  //
  31.              *  \\// here is where the program crashes \\// */
  32.            
  33.             sscanf(digit, "%d", got[times]); // it would go get the integer to got
  34.             times++; // after that, go to the next integer, if the for loop isn't over
  35.             curdig = 0;
  36.         }
  37.     }
  38.     return(got); // returns the 'got' address to the pointer that called this function
  39. }
  40.  
  41. int main() {
  42.     char *str; // THE string
  43.     str = "10 20 30 40"; // example
  44.     int *v;
  45.     v = gianass(str, 3);
  46.     printf("%d %d %d %d \n\n", v[0], v[1], v[2], v[3]); // testing =)
  47.    
  48.     system("pause");
  49.     return(0);
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement