You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言数组操作代码无法进入if条件分支,求问题排查及解决方案

问题排查与修复方案

核心错误点

  • 选项存储变量类型定义错误
    main函数中你定义了char *new,这是字符指针类型,既不能直接存储单个输入的字符选项,也无法和字符常量'A'/'B'做等值比较,这是代码无法进入对应if分支的根本原因,需改为普通字符变量char new。
  • 数组传参类型不匹配
    调用add1(&newArray, size)时,&newArray是数组指针类型int (*)[size],和函数要求的int*形参类型不匹配,直接传入数组名newArray即可,数组名传参时会自动转换为指向首元素的int指针。
  • 语法冗余
    自定义函数add1、add2、print1的定义结束后不需要额外加分号,属于多余的语法符号。
  • 内存泄漏隐患
    add1和add2中通过malloc申请的堆内存没有释放,处理完数组后需要调用free释放对应指针,避免内存泄漏。

修正后完整代码

#include <stdio.h>
#include <stdlib.h>

int* add1(int* array, int size)
{
    int *novo = malloc(size*sizeof(int));
    for (int i = 0; i < size; i++){
        novo[i] = array[i] + 1;
    }
    return novo;
}

int* add2(int* array, int size)
{
    int *novo = malloc(size*sizeof(int));
    for (int i = 0; i < size; i++){
        novo[i] = array[i] + 2;
    }
    return novo;
}

void print1(int* array, int size)
{
    for (int i = 0; i < size; i++)
    {
        printf("%i\n", array[i]);
    }
}

int main(void)
{   
    int i, elemento, size;
    char option;

    printf("Insert Size:\n");
    scanf("%i", &size);
    int newArray[size];
    printf("Insert Elements:\n");
    for (i = 0; i < size; i++)
    {
        scanf("%i", &elemento);
        newArray[i] = elemento;
    }

    printf("Select option:\n");
    scanf(" %c", &option);

    if (option == 'A') {
        int* result = add1(newArray, size);
        print1(result, size);
        free(result);
    } else if (option == 'B') {
        int* result = add2(newArray, size);
        print1(result, size);
        free(result);
    }
    return 0;
}

内容的提问来源于stack exchange,提问作者digolira2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 04:06:04