通过C中的函数操作动态数组
我正在学习如何在C中使用动态数组。我想要做的是创建动态数组data
,并使用函数test()
将“1”放入第一个条目。
void test(void) { data[0] = 1; } int main(void) { int *data = malloc(4 * sizeof *data); test(); return 0; }
这在Visual Studio 2010中编译,但程序在运行时崩溃。 而不是使用test()
,使用data[0] = 1
工作。
我的(新手)猜测是我需要将指向data
的指针传递给函数test()
。 我该怎么写呢?
尝试
void test(int *data) { data[0] = 1; }
然后,在main
使用test(data)
而不仅仅是test()
。
编辑
尝试有效。 但是,这是一种“适当”的做法吗?
您可以通过两种方式动态传递数组:
- 使用简单的指针,然后使用指针算法进行操作
void test ( int * data, int i )
{ *(data + i) = 1; //This sets data[i] = 1 }
-
或者这样:
void test(int data[], int i)
{
data[i] = 1; //This is the more familiar notation
}
这两种方式中的任何一种都是“适当”的方式。
当您在C中使用局部变量(动态或静态,数组与否)时,需要将其传递给将使用它的函数。 这就是你初始代码的错误, test()
对data
一无所知。
声明数组(动态或静态)时,可以以相同的方式将其传递给函数。 下面的代码毫无意义,但它说明使用动态数组与静态数组没有什么不同。
void assign_function(int arr[], int len_of_arr, int *arr2, int len_of_arr2); void print_function(int *arr, int len_of_arr, int arr2[], int len_of_arr2); int main() { int data[2] = {0}; // static array of 2 ints int *data2 = malloc(3 * sizeof(int)); // dynamic array of 3 ints assign_function(data, 2, data2, 3); print_function(data2, 3, data, 2); free(data2); // One difference is you have to free the memory when you're done return 0; }
所以我们可以通过array[]
或作为指针传递数组,无论是动态的还是静态的,但我们也需要传递一个int
,所以我们知道数组有多大。
void assign_function(int arr[], int len_of_arr, int *arr2, int len_of_arr2) { int count; for(count = 0; count < len_of_arr; count++) //This is the static array arr[count] = count; for(count = 0; count < len_of_arr2; count++) //This is the dynamic array arr2[count] = count; }
然后只是为了好玩我反过来在arr
和arr2
传递哪个数组,以及它们是如何被访问的:
void print_function(int *arr, int len_of_arr, int arr2[], int len_of_arr2) { int count; for(count = 0; count < len_of_arr; count++) //This is the dynamic array now printf("arr[%d] = %d\n", count, *(arr+count)); for(count = 0; count < len_of_arr2; count++) //And this is the static array printf("arr2[%d] = %d\n", count, *(arr2+count)); }
指向,通过[]
或作为指针传递,并通过[]
或引用指针访问取决于你,两者都很好,两者都有效。 我尽量避免使用指针,因为它们往往难以阅读,写作时更容易出错。
测试中的变量“data”是本地范围的。 这与主要的“数据”不同。 你应该通过test()的参数传递一个指向’data’的指针。