0

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 Answer 1

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Maybe i should have added i have to malloc it in main()
@Joelmob Does it change something?
this is working good but is it possible without needing to have inparameter to foo()
@Joelmob you can declare char (*array)[100] at file scope, malloc it in your main and directly use it in a foo function that takes no parameter; this will work but it is bad style.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.