好,早晨的大师,我遇到了一个问题,这使我意识到我对指针的了解不如我想的那样! test.h: #ifndef test_h_included #define test_h_included void getDataal ...

问题描述 投票:0回答:0
-test.h:

#ifndef TEST_H_INCLUDED #define TEST_H_INCLUDED void getDataAlt(char** dst); #endif // TEST_H_INCLUDED

-test.c
#include "test.h"

void getDataAlt(char** dst) {
    char* tmp = *dst;
    tmp = malloc(sizeof(char) * 50);
    sprintf(tmp, "This is a test.\r\n");
    *dst = tmp;
}

main.c
#include <stdio.h>
#include <stdlib.h>
#include "test.h"

#define enableOther

void getData(char** dst);

int main()
{
    char* anOther;
    getData(&anOther);
    printf("Hello %s\n", anOther);
    free(anOther);
    #ifdef enableOther
    char * anOtherAlt;
    getDataAlt(&anOtherAlt);
    printf("Hello Alt %s\n", anOtherAlt);
    free(anOtherAlt);
    #endif
    return 0;
}

void getData(char** dst) {
    char* tmp = *dst;
    tmp = malloc(sizeof(char) * 50);
    sprintf(tmp, "This is a test.\r\n");
    *dst = tmp;
}

,这是我的代码,所以我试图让函数进行分配等,并修改传递给它的字符*。
本地getData无问题,单独的.h /.c文件中的一个工作一直持续到免费(getDataalt),并且会出现“双免费”错误,而我不能一生我弄清楚了。
Windows 11,Mingw编译器版本8.1.0
上的框架块20.03 thanks

void getData(char** dst) { *dst = malloc(sizeof(char) * 50); if (*dst == NULL) { fprintf(stderr, "Memory allocation failed\n"); return; } sprintf(*dst, "This is a test.\r\n"); }

直接将内存分配给 *DST,然后检查您可以分配内存。

c pointers mingw codeblocks
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.