Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- /* gianass = Get Integer From "Numbers And Spaces" String */
- /* gianass(str[], lim) have to return an array with the integers
- * from a given string. */
- /* str[] is that string and lim is the maximum number of digits */
- int *gianass(char str[], int lim) {
- int strSize = strlen(str),
- curdig = 0, // current digit
- times = 0, // amount of integers
- a, // any use
- *got; // pointer to memory where the intergers will be allocated
- char digit[lim];
- got = (int *) calloc(1, sizeof(int)); // allocating just one space
- for (a = 0; a < strSize; a++) {
- /* \/ it will take only numbers to digit[curdig] \/ */
- if (str[a] != ' ') {
- digit[curdig] = str[a];
- curdig++;
- }
- if (str[a] == ' ' && curdig != 0) {
- if (times != 0) { // if it's not the first time
- got = realloc(got, (times + 1) * sizeof(int)); // reallocate more memory
- }
- digit[curdig] = '\0'; // finish the digit
- /* \\ // \\ //
- * \\// here is where the program crashes \\// */
- sscanf(digit, "%d", got[times]); // it would go get the integer to got
- times++; // after that, go to the next integer, if the for loop isn't over
- curdig = 0;
- }
- }
- return(got); // returns the 'got' address to the pointer that called this function
- }
- int main() {
- char *str; // THE string
- str = "10 20 30 40"; // example
- int *v;
- v = gianass(str, 3);
- printf("%d %d %d %d \n\n", v[0], v[1], v[2], v[3]); // testing =)
- system("pause");
- return(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement