pointers frustration

closed account (4ET0pfjN)
Hi, I don't want pointers to frustrate me, but I was sure this was correct, which just empties an array for a given array and size passed as parameters.

1
2
3
4
5
6
7
8
9
int *emptyList(int *list, int arraySize)
{
	for ( int i = 0; i < arraySize; i++)
	{
		emptyList[i] = 0;
	}
		
	return *emptyList;//NB: WHY isn't it: return *emptyList
}


It works when I replace with:
return emptyList;

I know that a pointer to an array is always pointer to the first elem only, a constant pointer so it should work...I don't want pointers to haunt me if I am going to be a developer as a career.
emptyList is the name of the function, but you try to use it as an array.
closed account (4ET0pfjN)
that was a typo in my code, I meant

1
2
3
4
5
6
7
8
9
int *emptyList(int *list, int arraySize)
{
	for ( int i = 0; i < arraySize; i++)
	{
		emptyList[i] = 0;
	}
		
	return *list;//NB: WHY can't it be: return *list
}


Why is return *list not valid, it's just a pointer to the FIRST elem of this array?
closed account (1yR4jE8b)
Your function return value is int* ( a pointer to an int -- whether it's an array or a single one).

list is a pointer
*list is the value pointed at by the pointer.
closed account (4ET0pfjN)
So we use return list because our pointer is pointing to set of memory addresses b/c the compiler knows we will be passing an array in the parameter, and if I use
return *list I am referring to just the first element value, is that right?
Your initial code

1
2
3
4
5
6
7
8
9
10
11

int *emptyList(int *list, int arraySize)
{
	for ( int i = 0; i < arraySize; i++)
	{
		emptyList[i] = 0;
	}
		
	return *emptyList;//NB: WHY isn't it: return *emptyList
}


Corrected code

1
2
3
4
5
6
7
8
9
10
11

int *emptyList(int *list, int arraySize)
{
	for ( int i = 0; i < arraySize; i++)
	{
	         list[i] = 0;         //Modified here. emptyList is a function. list is an integer pointer
	}
		
	return list;   // so, after you have emptied it, you do this to return it. because list is an integer pointer. emptyList is a function
}
Topic archived. No new replies allowed.