int *ip1Array = new int[4];
This defines a pointer. You've initialised it to point to a dynamic array.
ip1Array = ipSplit(4);
This assignment overwrites the previous pointer value. Since that previous value was the only pointer to the dynamic array, nothing points to it anymore, and it can no longer be deleted. This is called a memory leak. Don't do this.
static int ipTab[4];
static means that the variable is same across all invocations of the function. Every call to the function will return a pointer to (first element of) the same array.
ip1Array = ipSplit(4);
ip2Array = ipSplit(2);
Both of these arrays point to the (first element of) same array that is returned by the function. And both of the dynamic arrays have leaked.
ip1Array = ipSplit(4);
You call the function with argument 4.
static int ipTab[4];
The array has 4 elements.
for (int i = 0; i <= ip; i++) {
You access through the indices 0,1,2,3,4. Count them. You access 5 different indices. You access outside the bounds of the array, and the behaviour of the program is undefined. Don't do this.
How to fix it?
- Don't use owning bare pointers.
- Don't access arrays outside of their bounds.
- If don't want all arrays to be the same, then don't use
static.
Since the sizes of the arrays are constant and small, you could use std::array:
auto
ipSplit(int ip)
{
assert(ip <= 4);
std::array<int, 5> ipTab{};
for (int i = 0; i <= ip; i++) {
ipTab[i] = ip
}
return ipTab;
}
// usage
auto ip1Array = ipSplit(4);
auto ip2Array = ipSplit(2);
ipTabstatic?