Hi all,
Could anyone help me about returning the array from a function? I believe that it is a syntax error (compile time error) to return an array from a function, but one book mentions briefly that using pointer will solve the issue.
However, my current knowledge does not allow me to see how the pointer can solve this C++ limitation (return a pointer might be dangerous because it might point to the address of local variable, and this variable will go out of scope. Hence, this pointer will point to invalid value). I appreciate for your information.
tlee
1
Newbie Poster
Recommended Answers
Jump to PostHowever, my current knowledge does not allow me to see how the pointer can solve this C++ limitation (return a pointer might be dangerous because it might point to the address of local variable, and this variable will go out of scope. Hence, this pointer will point to invalid value). …
Jump to PostOne way:
int* getArray() { static int array[LENGHT] = {1, 2, 3, 4, 5}; cout << "array in getArray()" << endl; printArray(array); return array; }
Jump to PostHence, although we want to have 2 different arrays, the first one is modified because 2 pointers in main() actually point in the same memory location.
Ah. You want a function that creates a new array each time it is called.
#include <iostream> #define LENGTH 5 using …
Jump to PostGosh! when did Jack Nichalson change his name and become a C
programmer?!!And what makes you think Nichalson doesn't know how to program in C ?
All 16 Replies
Dave Sinkula
2,398
long time no c
Team Colleague
tlee
1
Newbie Poster
tlee
1
Newbie Poster
Dave Sinkula
2,398
long time no c
Team Colleague
tlee
1
Newbie Poster
Dave Sinkula
2,398
long time no c
Team Colleague
tlee
1
Newbie Poster
Dave Sinkula
2,398
long time no c
Team Colleague
tlee
1
Newbie Poster
egemen
0
Newbie Poster
WaltP
2,905
Posting Sage w/ dash of thyme
Team Colleague
alleycat429
0
Newbie Poster
Ancient Dragon
5,243
Achieved Level 70
Team Colleague
Featured Poster
Ancient Dragon
5,243
Achieved Level 70
Team Colleague
Featured Poster
Salem
5,138
Posting Sage
Ancient Dragon
5,243
Achieved Level 70
Team Colleague
Featured Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.