简体   繁体   English

分段错误(核心转储)C程序

[英]Segmentation Fault (Core Dumped) C Program

I am trying to run this program with the command 我正在尝试使用以下命令运行该程序

./box2 5 ./box2 5

/*
 * box2.c
 *
 *  Created on: Mar 19, 2014
 *      Author: Ian
 */
 #include <stdio.h>
 void printchars(char c, int n);
 int main( int argc, char*argv)
 {
    int n = argv[1];
    printchars('*', n);
    return 0;
 }

 void printchars(char c, int n)
 {
    int x;
    for (x = n + 2 ; x > 0; x--)
    {

        if (x != 1 && x != n)
        {
            printf("%c", c);
            int count = n;
            while (count - 2 != 0)
            {
                printf(" ");
                 count--;
            }
        }
        else
        {
            int num = n;
            while (num != 0)
            {
                printf("%c", c);
                num--;
            }
        }
        printf("\n");
     }
 }

I always get the error Segmentation Fault(core dumped) each time i try it. 每次尝试时,我总是收到错误Segmentation Fault(core dumped)。

    *****
    *   *
    *   *
    *   *
    *   *
    *   *
    *****

This is what I should get. 这就是我应该得到的。

I have no idea what to do to fix this. 我不知道该怎么办才能解决此问题。 I get no errors when I compile and that error is the only thing that comes up when I try to run the program. 编译时没有任何错误,并且该错误是我尝试运行程序时唯一出现的错误。

argv[1] is a char * . argv[1]char * You need to convert that to an int . 您需要将其转换为int You could do that by calling atoi() as follows: 您可以通过如下调用atoi()来做到这一点:

int n = atoi(argv[1]);

Note that this will not handle argument errors. 请注意,这不会处理参数错误。 Note also that your definition of argv is wrong: it should be char * argv[] . 还要注意,您对argv的定义是错误的:应该为char * argv[]

int main( int argc, char*argv)更改为int main( int argc, char**argv)

This is wrong: 这是错误的:

 int main( int argc, char*argv)

since argv must be declared as a ptr-to-ptr-to-char. 因为必须将argv声明为ptr-to-ptr-char。 Likewise, this: 同样,这:

 int n = argv[1];

can't work. 不能工作。 You need something like 你需要类似的东西

 int main(int argc, char **argv)
 ...
 int n = atoi(argv[1]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM