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! :)
Moved the definition of
convert()above abovemain()so the prototype is not required. As you know the size of theresultarray it is cleaner to pass it in as an argument, and as @kaylum noted above, the return type ofintis clearly incorrect. The loop is wrong (should bei < length). You cannot return a local arrayarreven 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. Inmain(), the expressionresult[4] =sets the 4th element and rest of result contains undefined data.Consider using
strtol()instead ofatoi()so you can implement error handling (atoi()returns 0 on error).