im trying to fill a 2d array with strings, problem is that i manage to fill the first index, however when i proceed to the next string it keeps changing the previous indexes. probably an issue with the pointer, this is the relevant code.
char* get_song_name(const char* song)
{
strip(song);
FILE* fp = fopen(song, "r");
char str[9999];
while(!feof(fp))
{
fgets(str,9999,fp);
puts(str);
strip(str);
char* s = str;
return s;
}
` DIFFERENT FUNCTION:
for(i=0;i<lines;i )
{
char *st = fgets(buff, 250, fp);
st = create_path("c:\\Users\\Marian\\Desktop\\beatles", st);
name[i] = get_song_name(st); //WORKS HOWEVER CHANGES PRVIOUS INDEXES VALUE TOO
}`
CodePudding user response:
You need to dynamically allocate the string so its lifetime does not end then the functions exits.
Just replace
return s;
with
return strdup(s);
EDIT
As OP is not allowed to use string.h
here one can find
an implementation of strdup()
found in https://stackoverflow.com/a/37132824/4989451
#include <stdlib.h>
char *ft_strdup(char *src)
{
char *str;
char *p;
int len = 0;
while (src[len])
len ;
str = malloc(len 1);
p = str;
while (*src)
*p = *src ;
*p = '\0';
return str;
}
CodePudding user response:
This function
char* get_song_name(const char* song)
can invoke undefined behavior because it returns an invalid pointer that points to a local array of the function that will not be alive after exiting the function
char str[9999];
//...
char* s = str;
return s;
Moreover the function always returns the same pointer (the address of the first element of the local array). So this loop
for(i=0;i<lines;i )
{
char *st = fgets(buff, 250, fp);
st = create_path("c:\\Users\\Marian\\Desktop\\beatles", st);
name[i] = get_song_name(st); //WORKS HOWEVER CHANGES PRVIOUS INDEXES VALUE TOO
}`
does not make a sense.
You need to allocate dynamically a character array within the function get_song_name
a pointer to which will be returned from the function.