This is a working version of your approach (with still one problem):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int * make_array(char s1[], int * arraylen){
// convert string and puts result into array
char *endp = s1;
int i, j=0;
int len=strlen(s1);
int *array = malloc(len*sizeof(int));
for (i=0;i<len;i++)
if(s1[i]!=' ') {
array[ j++ ]=strtol(s1, &endp, 10);
s1=endp;
}
*arraylen = j;
return array;
}
int main() {
int arraylen = 0, i;
int * array = make_array( "9 8 7 123", & arraylen );
for ( i = 0; i < arraylen; i ++ )
printf( "[%i]: %d\n", i, array[i] );
}
The main changes:
- set
s1
inside the if
;
- add a parameter
arraylen
- how else will the caller of make_array
know the length of the array?
- change the return type to
int *
since we're returning array
.
- compare the character
s1[i]
with the character ' '
(not the string " "
).
- using a separate index for the output array, since the input index counts the spaces aswell, which would end up as random entries in the output
array
(unless you memset( array, 0, len*sizeof(int))
first).
It outputs
[0]: 9
[1]: 8
[2]: 7
[3]: 123
[4]: 0
[5]: 0
[6]: 0
If you only expect single-digit numbers then it should work fine, but strtol
reads multiple digits if they are available.
If you only want to read digits, you can just:
array[ j++ ] = s1[i] - '0';
If the numbers can have more than one digit you would do:
for (i=0;i<len;)
if ( s1[i] == ' ')
i++;
else {
array[ j++ ]=strtol(s1, &endp, 10);
i += endp - s1;
s1=endp;
}
to get output
[0]: 9
[1]: 8
[2]: 7
[3]: 123