C:向动态分配的数组添加元素 [英] C: adding element to dynamically allocated array

查看:28
本文介绍了C:向动态分配的数组添加元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过谷歌搜索解决方案:我找不到任何有用的东西;甚至似乎我这样做是正确的.我能找到的关于通过一个函数发送我动态分配的数组的唯一页面,该函数处理位于结构内的数组,当然这是标量,因此行为不同.我现在不想使用结构——我正在尝试了解 DAM 并使用指针和函数.

I've tried to search out a solution via Google: I couldn't find anything that helped; it even seemed as if I was doing this correctly. The only pages I could find regarding sending my dynamically allocated array through a function dealt with the array being inside a struct, which is scalar of course, so behaves differently. I don't want to use a struct right now -- I'm trying to learn about DAM and working with pointers and functions.

也就是说,我确定这是非常初级的,但我被卡住了.代码可以编译,但是当我运行可执行文件时它会冻结.(我正在使用 minGW gcc,如果这很重要.我现在完全不清楚如何使用 gdb.)

That said, I'm sure it's very elementary, but I'm stuck. The code compiles, but it freezes up when I run the executable. (I'm using minGW gcc, if that matters. And I'm not clear at all, right now, on how to use gdb.)

这是代码(最终,我希望整个代码是一个类似 ArrayList 的数据结构):

Here's the code (eventually, I want the entire code to be an ArrayList-like data structure):

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

void add( int element, int *vector);
void display_vector( int *vector );
void initialize_vector( int *vector );

int elements = 0;
int size = 10;

int main(void)
{
    int *vector = 0; 
    initialize_vector(vector);
    add(1, vector);
    //add(2, vector);
    //add(3, vector);
    //add(4, vector);
    //add(5, vector);
    //add(6, vector);
    //add(7, vector);
    //add(8, vector);
    //add(9, vector);
    //add(10, vector);
    //add(11, vector);
    display_vector(vector); 

    return 0;
}

void add( int element, int *vector)
{
    vector[elements++] = element;
    return;
}

void display_vector( int *vector )
{
    int i;
    for( i = 0; i < elements; i++)
    {
        printf("%2d\t", vector[i]);
        if( (i + 1) % 5 == 0 )
            printf("\n");
    }
    printf("\n");
    return; 
}

void initialize_vector( int *vector )
{
    vector = (int *)malloc(sizeof(int) * size);

}

推荐答案

进行了编辑以使其更加清晰.

Edited to make a little bit more clear.

问题是您的 init 例程正在处理向量"的副本,并且正在将其分配到该副本而不是原始向量指针.您在初始化返回时丢失了指向内存块的指针.

The problem is your init routine is working with a copy of "vector" and is malloc'ing into that copy rather than the original vector pointer. You loose the pointer to the memory block on the return from the initialize.

在此函数中将向量的参数更改为句柄(指向指针的指针)

Change parameter for vector to a handle (pointer to pointer) in this function

void initialize_vector( int **vector )
{
    *vector = (int *)malloc(sizeof(int) * size);
}

然后把对init的调用改成这个

Then change the call to init to this

initialize_vector(&vector);

我没有编译这个,但它应该修复代码.

I didn't compile this, but it should fix the code.

这篇关于C:向动态分配的数组添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆