2D array in file/program scope

孤街浪徒 提交于 2019-12-11 23:04:47

问题


I need an array which I can access from different methods, I have to allocate this array in main() and then let other functions like foo() get access to this array.

This question helped me with allocating the array: defining a 2D array with malloc and modifying it
I'm defining the array like this: char(*array)[100] = malloc((sizeof *array) * 25200); And I'm doing this in main()
I can store 25200 strings in this array an access them by array[1]

Is it now possible to access this array from different methods, how can I do that?


回答1:


With this declaration:

char (*array)[100] = malloc((sizeof *array) * 25200);

You can have a function foo:

void foo(char array[][100])
{
    array[42][31] = 'A';  // you can access characters elements this way
    strcpy(array[10], "Hello world\n");  // you can copy a string this way
}

and you can call foo this way:

foo(array);


来源:https://stackoverflow.com/questions/9280877/2d-array-in-file-program-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!