使用malloc定义字符串地址

问题描述 投票:0回答:1

运行此代码时没有任何输出。我期望使用大写值写入文件,并将大写值打印到屏幕上。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main(int argc, const char * argv[]) {
    
    FILE *fP;
    
    char *str = "this is an example";
    /* Im not sure if this line is right */
    str = (char *)malloc(sizeof(char) * 100);
    
    fopen("4.txt", "w");

    size_t length = strlen(str);

    for (size_t i = 0; i < length; i++)
    {
        /* This line fails */
        fprintf(fP, "%c", toupper(*(str +i )));
        printf("%c", toupper(*(str +i )));
    }
    
    return 0;
}
c file malloc
1个回答
0
投票

您正在运行 fopen() 而不返回 fp ,这只会打开文件流,但不会让它被 fp 引用,您需要将该行更改为

fp = fopen("4.txt" , "w");

您也在 str 上运行 strlen() ,但由于您分配了内存但没有在其中存储任何内容(之前分配的字符串被覆盖),它将返回一个随机数( malloc() 给出了一个内存块而不清除以前的内存,因此,无论以前使用它的程序都将存储在其中),您都需要使用 strcpy() 将字符串设置到其中,如下所示

strcpy(str , "this is an example");

如果解决了这两个问题,它应该可以运行。

© www.soinside.com 2019 - 2024. All rights reserved.