-
Pointer help
Hello, I am new here but i have a question regarding pointers.
I am using Dev-C++ and i have the following question:
I have a function
Code:
simbol* alfabet( FILE* fisier)
{ ...
simbol* v;
...
return v;
}
So in main I want to call this function. It returns the start address of the pointer v but I can't get the dimension of the pointer.
Any idea how can I get the dimension of the pointer that I filled in the function?
Thank you.
-
What do you mean by "dimension of the pointer"?
-
I mean the number of elements, of the type simbol,I put in the pointer.
For example:
In the function alfabet I add 10 element to v, all with the type simbol. In this i know the exact number of elements.
In main i call my function and it returns the start of the pointer.
How can i find out the number of element i added to the pointer.
I tried to make the dimension as a global variable but i want to know if there is another way, except this one.
-
A pointer is just a pointer, not a container.
There are a few ways to deal with this, but one way is to #include <vector> then just use and return (or modify through a reference parameter) a std::vector<simbol>.
-
Pass in a variable by reference to receive the number of elements you read?
Code:
simbol* alfabet( FILE* fisier, unsigned int &numElements)
{
// Set numElements in here
}
int main()
{
unsigned int numElements = 0;
simbol *s = alfabet(filePtr, numElements);
}
Hope you're dynamically allocating the memory for that pointer in the function, or you will lose whatever it's pointing to when you leave the function.
Also, there's no indication that this is actually a C++ program, as all you show is the use of FILE, which is C I/O. If you're actually writing C, then you need to pass a pointer to the argument as C does not support pass-by-reference:
Code:
simbol* alfabet( FILE* fisier, unsigned int *numElements)
{
*numElements = numRead;
}
int main()
{
unsigned int numElements = 0;
simbol *s = alfabet(filePtr, &numElements);
}
-
Thank you very much rags_to_riches. The first solution worked.
I am dynamically allocating the memory for the pointer in the function, and after I added the part you wrote it works perfectly.
For the thing about what language I use, I am also very confuse. My teacher told me that this is C++ but i find different things on the internet and I don't know what to belive anymore.
Thank you very much again because this is a very important project.
-
This code will indeed compile with a C++ compiler, hence it is valid C++ code.
However, this code will also compile with a C compiler, hence it is also valid C code.
This implies that this can be either C or C++ code.
So the conclusion we can make is:
- either the teacher is really teaching C that can or is compiled with a C++ compiler,
- or the teacher is teaching the C subset of C++ and is (possibly) intending to move over to C++ constructs in the future.
Hope that answers your question.