Hi i'm trying to write a recursive function to extract each line of a string. I don't know why it doesn't work i spent 2 hours trying to find the issue.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int safe_line(char* input, int end_of_line, int num_of_line, int num_sum_safe)
{
//takes an input, the coordinates of the previous end of the line
//the number of line already treated
//and a num_sum_safe which is not important
char temp_line[24];
int count;
int actual_line;
int temp_num_line;
actual_line = end_of_line;
temp_num_line = num_of_line + 1;
if (num_of_line == 3)
{
return num_sum_safe;
}
count = actual_line;
while (*(input + count) != '\n')
{
*(temp_line + count - actual_line) = *(input + count);
count++;
}
*(temp_line + count - actual_line ) = '\0';
actual_line += count + 1;
printf("%s\n", temp_line);
return safe_line(input, actual_line, temp_num_line, 0);
}
int main()
{
char input[15] = "n\natt\naa\na as";
safe_line(input,0 ,0 ,0 );
}
The value that it returns in stdout :
n
att
The expected value should be this :
n
att
naa
na as
mainfunction, and you should avoid as much dynamic allocation or similar operations that aren't strictly needed for debugging or testing. Then use a debugger to step through the code line by line, while monitoring variables and their values, to see what really happens.pand indexi, the expression*(p + i)is exactly equal top[i]. The latter,p[i], is usually easier to read and understand. And also less to write.