I need to get a specific line in a char * but im doing something wrong with the arrays… any ideas how can I do it?
The function is something like this:
char * line get_line(char * code, int num_line);
where should i put the frees and mallocs?
thanx!
Im sorry… I had to be more explicit, this is how I solved it (is in spanish)
char* obtenerLinea(char*cont, int numLinea)
{
int32_t lineaActual=0,comienzoLinea=0,caracterActual=0; // línea
char *cadena;
while(lineaActual<numLinea)
{
comienzoLinea=caracterActual;
while(contenido[caracterActual]!='\n')
{caracterActual++;}
caracterActual++;
lineaActual++;
}
cadena = sub_string(contenido, comienzoLinea, caracterActual-comienzoLinea);
return cadena;
}
My short answer is: put the
mallocinside the function and thefreeoutside.But the way you asked your question, it’s almost like saying “I want to throw a tea party… Where should I put the table and chairs?”
What I mean is your question is open to interpretation:
const).Well, it turns out that in cases 1 and 3 above, you’ll be making a call to either
mallocorstrdupinside the function. Ifmalloc, you’ll then copy string data into the new memory. Forstrdupyou’d have to modify the input string to null-terminate the line. In these cases, you’ll return a newly allocated pointer, which the caller is responsible for freeing when they are finished with it. Note there is also the possibility of usingstrndupwithout modifying the buffer.In the case of number 2, there will be no calls to
mallocorfreebecause you’re just modifying the buffer and returning a pointer to some part of it.In all cases, I’ve assumed that you already know where to call
mallocandfreefor the input buffer itself!