pass argv[] to a function, return an array

hi, i am trying to write some code that passes argv[1] into a function, i know the code part works in main on its own, but im having an issue with how to pass argv[1] to a function. any help would be greatly appreciated.... ty.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int read_stream(argv[1])// my issue is here
{
	const int SIZE = 9;
	int widths[SIZE];
	int next;
	std::ifstream inStream(argv[1]); 

	if (inStream.fail( )) 
	{
		std::cout << "Input file opening failed.\n"; 
		return EXIT_FAILURE;
	}

	 while ( inStream >> next )
	 {
	 int i = 0;
	 widths[i] = next;
	 std::cout << "the array is.. " << widths[i] << ' ' << std::endl;
	 ++i;
	}

	inStream.close( );
	return widths;
}
http://cplusplus.com/doc/tutorial/functions/
1
2
3
4
std::vector<int> read_stream(const char *filename);

int main(int argc, char **argv){
   std::vector<int> meaningful_name = read_stream(argv[1]);


> return an array
You can't. Pass it as a parameter, or return a container (like `std::vector')
Last edited on
> return an array
You can't.

Disregard that. Arrays in C++ are pointers to the beginning of memory area containing array data. You can dynamically allocate memory for you array (so it won't deallocates when function returns) and return a pointer to it.
1
2
3
4
5
int* read_stream(/*...*/);
//...
int* widths = new int[SIZE];
//...
return widths;
closed account (S6k9GNh0)
1. That's incredibly slow.
2. It's unsafe without very strict overview of code.
3. You have no idea the size of the array unless it's hard coded, which in this case, it is not. You could set a global except this would ruin any type of re-entrancy rules and there are obviously better methods to go about this (such as passing the array as a parameter).

You might also be able to use std::array but I'm not sure if it uses an allocator or not, or how it handles copying.
Last edited on
1. That's incredibly slow.
Why?
Arrays are passed by reference. A pointer is a 4-byte integer. Do you mean the code itself?

@jonnyprogrammer
If your compiler supports C++11, use uniqe_ptr, if you want to return a dynamically allocated memory. It will deallocate it at the end of the main function. If does not support, vector is good enough for that.
Arrays are passed by reference
Technically pointer to the first element of the array is passed by value.
That's why you can't do staff like that:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

void process(int array[]) 
{
    array = new int[1]; //Memory leak here!!
    array[0] = 100;
}

int main()
{
    int x[1] = {1};
    process(x);
    std::cout << x[0] << std::endl; //Will print 1, not 100
    return 0;
}
closed account (S6k9GNh0)
Its slow because you make an unneeded allocation on heap.
You continue to propose methods that are looked down upon due to their proneness for error and fundamental issues such as performance.
Last edited on
Topic archived. No new replies allowed.