Search code examples
arrayscatoi

Converting a Char Array into an Int array using a Function


I have been tasked with converting a char* array into an int array using a function. I'm new to C so I do apologize if this is a simple fix or an easy solution that I have just failed to notice.

This is the code I currently have:

#include<stdio.h>
#include<stdlib.h>

int convert(char* str[], int length);

int main(void)
{
    int result[50], i, length = 4;
    char *str[] = {"7", "1", "14", "15"};

    result[4] = convert(str, 4);
    for(i = 0; i < length; i++) 
    {     
        printf("%d ", result[i]);
    }
    printf("\n");
    return 0;
}

int convert(char* str[], int length)
{
    int i;
    int arr[50];

    for(i = 0; i > length; i++)
    arr[i] = atoi(str[i]);

    return arr[50];
}

The output is currently this:

832 832 832 832 

Essentially, what the code is attempting to do is convert

char *str[] = {"7", "1", "14", "15"};

into this (output):

7 1 14 15

Any help would be appreciated! :)


Solution

  • Moved the definition of convert() above above main() so the prototype is not required. As you know the size of the result array it is cleaner to pass it in as an argument, and as @kaylum noted above, the return type of int is clearly incorrect. The loop is wrong (should be i < length). You cannot return a local array arr even if you tried as it will be out of scope when function returns. return arr[50] refers to an element that is out of bounds. In main(), the expression result[4] = sets the 4th element and rest of result contains undefined data.

    #include <stdio.h>
    #include <stdlib.h>
    #define ARRAY_LEN(A) (sizeof(A) / sizeof(*A))
    
    void convert(int length, char *str[length], int result[length]) {
        for(int i = 0; i < length; i++)
            result[i] = atoi(str[i]);
    }
    
    int main(void) {
        char *str[] = {"7", "1", "14", "15"};
        int result[ARRAY_LEN(str)];
        convert(ARRAY_LEN(str), str, result);
        for(int i = 0; i < ARRAY_LEN(result); i++) {
            printf("%d ", result[i]);
        }
        printf("\n");
    }
    

    Consider using strtol() instead of atoi() so you can implement error handling (atoi() returns 0 on error).