使用指针/ C将字符串传递给函数

时间:2016-03-13 12:44:40

标签: c function pointers

我想在我的函数中传递这个,但是出了点问题

FILE *f = fopen("out.bmp", "rb");
    int countBit = 0;
    int size = 0;
    char* type;

    for (int i = 0; i < 54; i++)
        fgetc(f);
    printf("/* count bit to pixel */\n");
    scanf("%d", &countBit);
    size=DecodeInformationSize(f, countBit);
    type=DecodeInformationType(f, countBit);
    DecodeMessage(f,countBit,size,type);
在输入函数类型之前

是txt enter image description here

但是之后:

void DecodeMessage(FILE *f, int countBit, int size, char* type)
{
    char messageSize[8];
    char nameOut[15] = "outMessage.";
    strcat(nameOut, type);
    char* message = (char*)malloc(size * 8);

enter image description here

请解释问题

1 个答案:

答案 0 :(得分:1)

绝对确定我们需要了解DecodeInformationType(f, countBit);的作用。

然而,似乎它在堆栈上使用了一些数据。一旦返回,此信息可能仅适用于一些说明。因此,调试器显示对DecodeMessagetype的调用指向有效字符串,但是一旦输入DecodeMessage,堆栈将被DecodeMessage的变量覆盖,特别是char nameOut[15] = "outMessage.";

要解决此问题,请确保DecodeInformationType返回指向不在DecodeInformationType堆栈(而非自动变量)内存的指针。这可能是使用malloc或常量字符串分配的内存。