I have the following code:
void word(char *a){
size_t length = strlen(a);
int max_cont = 0;
int size_arr = 1;
for(int j = 0; j < length; j++){
if(a[j] == ' '){
size_arr ++;
}
printf("For1 : %c\n",a[j]);
}
int arr_out[size_arr];
for(int y = 0; y<size_arr; y++){
arr_out[y] = 2;
}
for(int j = 0; j < length; j++){
if(j == 0){
arr_out[0] = 0;
}
printf("Char list for 2 ##:%c\n",a[j]);
if(a[j] == ' '){
arr_out[j] = (int) j;
printf("%d ---- %d\n", arr_out[j] ,j);
}
}
for(int k = 0; k < size_arr; k ++){
printf("%i FINAL -> %d\n",k, arr_out[k]);
}
}
The function gets a string (*a), in which I have to look for spaces ' ', and return an array with the starting position of each word I have passed the word() function.
The first for is to get the size of the array I will create.
The second one is for initialize the values. I know it is unnecessary but I was trying to see what was happening to the values.
In the last for, I try to initialize the first element of the array to 0, because the there is at least a word and it do not start with space, and then try to change each value of the array for the ones the J variable gives me, showing the position.
The problem arrives when I try to print the array in the last loop. The loop shows me that the first 0 value has been set, but the rest are still 2. I do not understand what is happening.
Sorry for the poor example, the question is more oriented to what is happening than to solve the problem it self.
My output is always like this:
0 FINAL -> 0
1 FINAL -> 2
...
...
N FINAL -> 2
arr_out[j] = (int) j;You can't usejas the index forarr_outas the array will not need to be updated for everyjindex. Use a seperate variable for that.for. Insideif(a[j] == ' '). That is,int out_i = 0; ... if(a[j] == ' ') { arr_out[out_i++] = (int) j; }