gpt4 book ai didi

c - 输出指向文本文件的指针时为 "makes pointer from integer without a cast"

转载 作者:行者123 更新时间:2023-11-30 17:30:14 25 4
gpt4 key购买 nike

抱歉,我是个菜鸟,但我只是不明白这里出了什么问题。

我正在尝试创建一个函数来写入文本文件,并使用指向字符串的指针作为输入。函数为outstring();它的输入是我想要放在txt文件中的字符串。

在 main() 中我可以这样做:

printf("the string is: %s\n", charcall(stringoutptr));

但我做不到:

outstring(charcall(stringoutptr)); 

编译时出现以下错误:

mynamehere (~): gcc csvtest.c -o csvtest
csvtest.c: In function 'outstring':
csvtest.c:24:5: warning: passing argument 2 of 'fprintf' makes pointer from integer without a cast [enabled by default]
fprintf(ptr_file, outstringinput);
^
In file included from csvtest.c:1:0:
/usr/include/stdio.h:356:12: note: expected 'const char * __restrict__' but argument is of type 'char'
extern int fprintf (FILE *__restrict __stream,
^

我的源代码是:

#include<stdio.h>

static const char outfile[] = "LETS SEE IF THIS WORKS"; // just some sample string

int charcall(instring) // a function to return the value of the pointer
{
return instring;
}


int outstring(outstringinput)
{
FILE *ptr_file;
int x;

ptr_file =fopen("output.txt", "w");

if (!ptr_file)
return 1;

for (x=1; x<=12; x++)
fprintf(ptr_file,"%d\n", x);

fprintf(ptr_file, outstringinput);

fclose(ptr_file);
}

int main()
{
char stringoutput[50] = "somestring in main\n";
char *stringoutptr;
stringoutptr = stringoutput;

// bellow = line 39
outstring(charcall(stringoutptr)); // I'm trying to output "some strhing in main" onto the text file
// bellow = line 40
printf("the string is: %s\n", charcall(stringoutptr)); // this works and prints the string "some string in main"

// why does line 39 work and 40 not?

return 0;
}

最佳答案

这是一个代码示例,添加了适当的类型以允许它执行您希望它执行的操作。您的函数返回类型必须与您在代码中使用返回值的方式相匹配。 (即,如果您想使用 charcall 返回指向字符串的字符指针,则必须将其声明为 char *charcall)请查看下面的示例:

#include<stdio.h>

static const char outfile[] = "LETS SEE IF THIS WORKS";

char *charcall (char *instring)
{
return instring;
}


int outstring (char *outstringinput)
{
FILE *ptr_file;
int x;

ptr_file = fopen ("output.txt", "w");

if (!ptr_file)
return 0;

for (x=1; x<=12; x++)
fprintf (ptr_file, "%d\n", x);

fprintf (ptr_file, "%s\n", outstringinput); /* pass outstringinput as a char* (not as format with 0 shift) */

fclose (ptr_file);

return 1;
}

int main()
{
char stringoutput[50] = "somestring in main\n";
char *stringoutptr;
stringoutptr = stringoutput;

outstring (charcall (stringoutptr));

printf ("the string is: %s\n", charcall (stringoutptr));

return 0;
}

构建:

gcc -Wall -Wextra -o bin/ostr outstring.c

输出:

$./bin/ostr
the string is: somestring in main

$ cat output.txt
1
2
3
4
5
6
7
8
9
10
11
12
somestring in main

关于c - 输出指向文本文件的指针时为 "makes pointer from integer without a cast",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25224148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com