【问题标题】:passing argument 1 of 'printf 'makes pointer from integer传递 'printf' 的参数 1 使指针来自整数
【发布时间】:2014-03-19 20:16:54
【问题描述】:

我不断收到此错误

box2.c: In function 'printchars':
box2.c:26:4: warning: passing argument 1 of 'printf' makes pointer from integer without  a      
cast [enabled by default]
/usr/include/stdio.h:363:12: note: expected 'const char * __restrict__' but argument is      
of type 'char' box2.c:26:4: warning: format not a string literal and no format arguments [-Wformat-security]
box2.c:39:8: warning: passing argument 1 of 'printf' makes pointer from integer without      a cast [enabled by default]
/usr/include/stdio.h:363:12: note: expected 'const char * __restrict__' but argument is     of type 'char'
box2.c:39:8: warning: format not a string literal and no format arguments [-Wformat-  
security]

当我尝试用 gcc 编译这个程序时

#include <stdio.h>

void printchars(char c, int n);

int main( int argc, char*argv){
    int n = argv[1];
    char c = argv[2];
    int nn = atoi(n);
    printchars(c, nn);
    return 0;
}

void printchars(char c, int n){
    int x;
    for (x = n + 2 ; x > 0; x--){
        if (x != 1 && x != n){
            printf(c);
            int count = n;
            while (count - 2 != 0){
                printf(" ");
                count--;
            }
        }
        else{
            int num = n;
            while (num != 0){
                printf(c);
                num--;
            }
        }
        printf("\n");
    }
}

我一直在尝试解决这个问题,但总是遇到同样的错误。 任何帮助将不胜感激。该程序的目的是打印出这样的一个盒子,给出它的数量和组成它的字符。

    ./box2 5 #
    #####
    #   #
    #   #
    #   #
    #   #
    #####

【问题讨论】:

  • 请修正你的缩进!另外,请仔细查看char c = argv[2];
  • 好肉汁,为什么99%的SO代码示例没有缩进???
  • 如果缩进得当,他们更有可能注意到他们的错误,而无需发布...

标签: c arguments


【解决方案1】:

这里

printf(c);

您将字符而不是格式字符串作为第一个参数传递给printf()。应该是

printf("%c", c);

或者

putchar(c);

【讨论】:

  • 这行得通,但现在在我编译它并尝试运行它之后,我得到了 Segmentation Fault (core dumped)
  • @user3015970:那是因为您的代码中还有一些错误:main() 的声明是错误的,int n = argv[1];char c = argv[2]; 都应该给出编译器警告或错误。 - 或许您应该先尝试修复 all 警告。如果您需要更多帮助,请更新问题。
【解决方案2】:

我知道已经过了一年,但请记住,# 可能会被您的 shell 用作内联注释。

所以 "./box2 5 #" 将 argc 作为 1 并将 argv 作为字符串数组,只包含一个位置:“5”。

# 之后的任何内容都会在 shell 调用您的程序之前被丢弃。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    • 2013-03-02
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多