数组的元素在C中成为随机数

时间:2019-12-04 10:00:09

标签: c arrays multidimensional-array

我在main中打开了一个2d数组,我试图在另一个函数中向其中添加项目。信息在功能上是正确的,但在其主要元素之外却变成了随机的事物。

void addpassenger(char** seatedbus,char** seatedeco,char** seatedstd,int busct,int ecoct,int stdct){

    busct++;
    seatedbus=realloc(seatedbus,sizeof(seatedbus)*busct);
    addtoarray(seatedbus,"bus",busct-1);
    ecoct++;
    seatedeco=realloc(seatedeco,sizeof(seatedeco)*ecoct);
    addtoarray(seatedeco,"econ",ecoct-1);
}

void addtoarray(char** array,char* item,int index){
    array[index]=malloc(sizeof(char)*strlen(item));
    strcpy(array[index],item);
}

int main() {
    char** seatedpassengerbus=(char **)malloc(sizeof(char)*1);
    char** seatedpassengereco=(char **)malloc(sizeof(char)*1);
    char** seatedpassengerstd=(char **)malloc(sizeof(char)*1);
    int busct=0;
    int ecoct=0;
    int stdct=0; 
    addpassenger(seatedpassengerbus,seatedpassengereco,seatedpassengerstd,busct,ecoct,stdct);
    return 0;
}

这是我正在做的工作的基本结构,因为这是我的功课,我无法共享代码的每个部分,但是这些通常是问题发生的地方,原因,原因以及如何解决的任何想法。它?

1 个答案:

答案 0 :(得分:4)

两个问题:

  1. 您会忘记count > yy不计算字符串空终止符。表示

    class Model(Base):
        __tablename__ = 'models'
    
        params = relationship('Param', cascade='all, delete-orphan', lazy='dynamic', back_populates='model')
    
    class Param(Base):
        __tablename__ = 'params'
    
        model = relationship('Model', back_populates='params')
        values = relationship('Value', cascade='all, delete-orphan', order_by='asc(Value.count)', back_populates='param')
    
    class Value(Base):
        __tablename__ = 'values'
    
        name  = Column(String(128))
        count = Column(Integer)
        param = relationship('Param', back_populates='values')
    

    将一个字节分配给一点,然后

    strlen

    因此将超出导致未定义行为的范围。

  2. 通过将值复制到函数局部参数变量中,您会忘记C中的参数通过值传递 。所以当你这样做时

    array[index]=malloc(sizeof(char)*strlen(item));
    

    您只能在strcpy(array[index],item); 函数内分配给 local seatedbus=realloc(seatedbus,sizeof(seatedbus)*busct); 变量。此分配不会发生在seatedbus函数中的addpassenger变量上。

解决第二个问题的一种可能方法是通过使用地址运算符seatedpassengerbus传递指向变量main的指针来通过引用 emulation 进行仿真。不幸的是,这意味着您将成为three-star programmer,因为需要修改&函数以使用三指针(需要取消引用)。

相关问题