通过C函数操纵动态数组 [英] Manipulating dynamic array through functions in C

查看:131
本文介绍了通过C函数操纵动态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何使用C.动态数组我想要做的是创建一个动态数组数据,并用把1进入第一个条目功能测试()

I am learning how to use dynamic arrays in C. What I want to do is to create a dynamic array data, and put "1" into the first entry using the function test().

void test(void)
{

data[0] = 1;

}


int main(void)
{

int *data = malloc(4 * sizeof *data);

test();

return 0;
}

这编译在Visual Studio 2010,但程序崩溃时运行。而不是使用测试(),使用数据[0] = 1

This compiles in Visual Studio 2010 but the program crashes when run. Instead of using test(), using data[0] = 1 works.

我(新手)的猜测是,我需要一个指针传递给数据来函数测试()。我应该怎么写呢?

My (newbie) guess is that I need to pass a pointer to data to function test(). How should I write this?

尝试

void test(int *data)
{

data[0] = 1;

}

然后,在使用测试(数据),而不是仅仅测试()

修改

的尝试工作。然而,这是做一个正确的方式?

The attempt works. However, is this a "proper" way of doing it?

推荐答案

您可以动态地传递数组有两种方式:

You can pass arrays dynamically in two ways :


  • 使用一个简单的指针,然后使用指针运算来操纵

无效测试(INT *数据,int i)以

    {

    *(data + i) = 1; //This sets data[i] = 1

    }


  • 或者是这样的:

    • Or this way :

      无效测试(int数据[],int i)以

      {

      data[i] = 1; //This is the more familiar notation
      

      }

      以下方式之一是正确的方式来进行此事。

      Either of these ways is the 'proper' way to go about this.

      这篇关于通过C函数操纵动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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