If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register or Login
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Re: Segmentation fault

Originally Posted by !pjk!

I thought arrays would be call by reference. So the allocation should have an effect outside of the method.

C doesn't have call-by-reference like C++ does. The best C can do is to simulate it using pointers; which is the reason why arrays may appear to behave this way. What they're pointing to, the actual array contents, is (effectively, if not technically) being passed by reference. But the array pointer itself is *not*---the pointer is being copied by value.

In order to make a method as you are attempting, you either need to make the parameter an int**, or you need to make the return value of the function be the new pointer. The second is the approach taken by the realloc() method, incidentally.

Re: Segmentation fault

You shouldn't talk about an array being passed to the function. The array is *not* what's being passed. Instead, your are passing a pointer to the array.

The pointer itself is passed by value, so modifications to the pointer inside the function are not reflected afterwords. But the address held by the pointer is the same whether you're working from a copy of the pointer or not; so you're free to modify that memory at will, and it will be reflected outside the function.

Think of it like a dog on a leash. You can put as many leashes as you like on the same dog, and changes made to one leash won't affect any of the others. But they're all attached to the same dog. If you attach one of the leashes to a second dog, that doesn't affect anything relating to any of the leashes attached to the first. In this analogy, leashes are pointers and dogs are the arrays they're directed at.