c 中带有指针的段错误

如何解决c 中带有指针的段错误

我有两个功能可以提示用户打印比萨的配料名称并将它们打印出来。但是每当我试图打印出可用的成分时,就会出现段错误。 当我提示输入成分时,如果我说我们今天有 3 个可用的成分,我只能输入 2 个(如输出图片所示)

    int get_ingredients(char** ingredients,int* num_ingredients) {
        char **ingredients_array = NULL; /*this is an array of pointers points to single ingredient in get_item*/
        int temp,i,j;
        ingredients = &ingredients_array; /*ingredients is a pointer points to the array of pointers*/
        temp = *num_ingredients;
        printf("How many available pizza ingredients do we have today? ");
        scanf("%d",&temp);
        ingredients_array = (char**)calloc(temp,sizeof(char*));
        i = 0;
        printf("Enter the ingredients one to a line: \n");
        while (i < temp){
            *(ingredients_array+i) = get_item();
            i++;
        }
        i = 0;      
        printf("Available ingredients today are: \n");
        while(i < temp) {
            j = i+1;
            printf("%d",j);
            print(". ");
            printf("%s",**(ingredients_array+i));
            i++;
        }
        *num_ingredients = temp;
        return EXIT_SUCCESS;
    }
    char* get_item(){
        int i,a;
        char *each_ingredient= (char*)malloc(61*sizeof(char)); /*points to each input*/
        a = getchar();
        i = 0;
        while (a != EOF && (char)a != '\n'){
            *(each_ingredient+i)= (char)a;
            a = getchar();
            i++;
        }
        *(each_ingredient+i) = '\n';
        return each_ingredient;
    }

How to replace environment variable value in yaml file to be parsed using python script

解决方法

您的 get_ingredients 问题有很多问题。

  1. 我注意到的第一个问题是您更改了参数 ingredients 的指针,将其更改为设置为 NULL 的指针 get_ingredients。因此,从现在开始访问 ingredients 指针中的数据将得到一个 segmentation fault,用于尝试访问非法地址。
int get_ingredients(char** ingredients,int* num_ingredients) {
        char **ingredients_array = NULL; /*this is an array of pointers points to single ingredient in get_item*/
        int temp,i,j;
        
        //ingredients pointer is lost forever and set to the address of the pointer of ingredients_array
        ingredients = &ingredients_array; /*ingredients is a pointer points to the array of pointers*/
  1. 现在第二个问题更像是一个优化问题。您设置了一个变量,然后在 scanf 上更改了它,这使得最初将其设置为某个值毫无用处。
        //Temp is set to num_ingredients,but this is of no use,becuase this value is never used and is overwritten by scanf("%d",&temp);
        temp = *num_ingredients;
        
        printf("How many available pizza ingredients do we have today? ");
        scanf("%d",&temp);
  1. 应该分配指向 char 的指针的指针。
ingredients_array = (char**)calloc(temp,sizeof(char*));

变化

ingredients_array = (char**)calloc(temp,sizeof(char**));
  1. while 循环可以替换为 for 循环。对于这种情况,哪种循环类型更合适。
        
        //This can write it better with a for loop
        i = 0;
        printf("Enter the ingredients one to a line: \n");
        while (i < temp){
            *(ingredients_array+i) = get_item();
            i++;
        }
        i = 0;      

        printf("Available ingredients today are: \n");
        //Use for loop intead,because it more appropiate for this case
        while(i < temp) {
            //better to use i+1 instead of j,simply things
            j = i+1;
            //These two printf can be on the same line
            printf("%d",j);
            printf(". ");
            
            //Allocation error?
            printf("%s",**(ingredients_array+i));
            i++;
        }

改用 for 循环,从标准函数获取用户输入,并使用较少混淆的索引。

printf("Enter the ingredients one to a line: \n");
//Using for loop
for(int i = 0;i < temp;i++)
{
    char ptr[80]; //Store user input
    scanf("%s",ptr); //Get user input
    ingredients_array[i] = strdup(ptr); //strdup is to make a another string with the same contents
}
        
printf("Available ingredients today are: \n");
for(int i = 0; i < temp;i++)
{
    //These two printf can be on the same line
    printf("%d",i+1);
    print(". ");
            
    //Allocation error?
    printf("%s\n",ingredients_array[i]);
}
  1. *num_ingredients 之前丢失了原来的指针,所以这没有用。
//This cannot be used because now points to ingredients_array and not to num_ingredients
*num_ingredients = temp;

现在是所有这些更改的代码。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
    
int get_ingredients(char** ingredients,int* num_ingredients) {
        char **ingredients_array = NULL; /*this is an array of pointers points to single ingredient in get_item*/
        int temp;
        
        
        printf("How many available pizza ingredients do we have today? ");
        scanf("%d",&temp);

        
        
        ingredients_array = (char**)calloc(temp,sizeof(char**));
        
        printf("Enter the ingredients one to a line: \n");
        //Using for loop
        for(int i = 0;i < temp;i++)
        {
            char ptr[80]; //Store user input
            scanf("%s",ptr); //Get user input
            ingredients_array[i] = strdup(ptr); //strdup is to make a another string with the same contents
        }
        
        printf("Available ingredients today are: \n");
        for(int i = 0; i < temp;i++)
        {
            printf("%d. ",i+1);   
            printf("%s\n",ingredients_array[i]);
        }
        *num_ingredients = temp;
        
        return EXIT_SUCCESS;
    }
    
    
    
int main()
{
    char** ingredients;
    int a;
    int foo = get_ingredients(ingredients,&a);
    return 0;
}

输出

How many available pizza ingredients do we have today? 4

Enter the ingredients one to a line: 
meat
MEAT
mEaT
no_salas
Available ingredients today are: 
1. meat
2. MEAT
3. mEaT
4. no_salad

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?