简体   繁体   English

函数的指针返回不断改变数组中的先前值

[英]Function's pointer return keeps changing previous values in an array

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
    }`

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由于不允许 OP 在此处使用string.h ,因此可以在https://stackoverflow.com/a/37132824/4989451中找到strdup()的实现

#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;
}

This function本 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可以调用未定义的行为,因为它返回一个无效指针,该指针指向 function 的本地数组,该数组在退出 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).此外,function 总是返回相同的指针(本地数组的第一个元素的地址)。 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.您需要在 function 中动态分配一个字符数组get_song_name一个从 function 返回的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM