0

I am trying to parse a string passed in as an input parameter. Basically if the input string is under 50 characters I want to add additional zeros in the new string. If the input string is over 50 characters, just take the first 50. I am getting segmentation faults and could use a big of guidance.

Extra information: I have a struct in the beginning of the program defined as follows:

typedef struct Integer50
{
  int *digits;
} Integer50;

ParseString Function:

Integer50 *parseString(char *str){
     int x = 0, y = 0, temp = 0;
        int length_string;
        Integer50 *large_num;
        large_num = malloc(sizeof(large_num));
        int i;

     if (str == NULL)
        {
         return NULL;
        }

    if(strlen(str) < MAX50){
        fprintf(stderr, "Error, input string is less than fifty (50).\n");
        for(i = 0; i < MAX50; i++){
            large_num->digits[i] = str[i]; 
        }
    }
    else{
         for(i = 0; i < MAX50; i++){
            large_num->digits[i] = str[i]; 
    }
    }

    return large_num;
}
9
  • 3
    You have to allocate memory for large_num->digits
    – Seek Addo
    Commented Apr 3, 2017 at 0:45
  • how can I do that? Commented Apr 3, 2017 at 0:47
  • 1
    dynamic memory allocation with malloc
    – Seek Addo
    Commented Apr 3, 2017 at 0:49
  • What do you have in str, i hope there no whitespaces in there. If str contains integers then is better to use strtol to convert them to integer before assigning them
    – Seek Addo
    Commented Apr 3, 2017 at 0:51
  • 4
    this large_num = malloc(sizeof(large_num)); allocate memory for the struct not the pointer in the struct.
    – Seek Addo
    Commented Apr 3, 2017 at 0:53

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.