"在没有强制转换的情况下从整数生成指针"输出指向文本文件的指针时

时间:2014-08-09 23:39:10

标签: c pointers casting printf

对不起是一个菜鸟,但我不明白这里有什么问题。

我试图创建一个函数来写一个文本文件,并指向一个字符串作为输入。该函数是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;
}

1 个答案:

答案 0 :(得分: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