LinuxQuestions.org
Review your favorite Linux distribution.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 07-06-2020, 07:52 PM   #1
bkelly
Member
 
Registered: Jan 2008
Distribution: Centos 7-4
Posts: 205

Rep: Reputation: 13
new array in a function


My app needs to call a function that will read some number of values from a text file and put them in the array. The count is not known until the function opens the file. The array must be new'ed within the function. What is the syntax that allows the new'ing of the array within the function. Below are some code fragments showing the concept. I know the syntax is wrong but cannot create a search function that covers new'ing the array in the function.
Code:
int main( ... )
{
float test_data[ ];
int  test_count;
status = get_test_data( &test_data, &test_count );
for( int i = 0; i < test_count; i ++ ) { do something with the data };
... }


bool get_test_data( &test_data, &test_count )
{...
test_count = 128;  // gets set from an fscanf( ... )
test_data = new float[ test_count ];
for( j = 0; j < test_count; j ++ )
     fscanf( test_data_file, "%f", test_data[ j ] );
... }
Resolved: I used the format from post #9

Last edited by bkelly; 07-07-2020 at 06:44 PM. Reason: final details
 
Old 07-06-2020, 07:58 PM   #2
rtmistler
Moderator
 
Registered: Mar 2011
Location: USA
Distribution: MINT Debian, Angstrom, SUSE, Ubuntu, Debian
Posts: 9,882
Blog Entries: 13

Rep: Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930
You mean malloc()?

Or are you using C++?
 
Old 07-06-2020, 08:15 PM   #3
bkelly
Member
 
Registered: Jan 2008
Distribution: Centos 7-4
Posts: 205

Original Poster
Rep: Reputation: 13
Quote:
Originally Posted by rtmistler View Post
You mean malloc()?

Or are you using C++?
Yes, but this part is not C++ anything, just standard C code, just procedural and not Object Oriented anything.
And no, I meant new. As I recall, possibly a faulty recall, we should prefer new over malloc. Should that change? And does it make a significant difference?

Last edited by bkelly; 07-06-2020 at 08:16 PM.
 
Old 07-06-2020, 08:58 PM   #4
rtmistler
Moderator
 
Registered: Mar 2011
Location: USA
Distribution: MINT Debian, Angstrom, SUSE, Ubuntu, Debian
Posts: 9,882
Blog Entries: 13

Rep: Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930
Quote:
Originally Posted by bkelly View Post
Yes, but this part is not C++ anything, just standard C code, just procedural and not Object Oriented anything.
OK, so C code only.
Quote:
Originally Posted by bkelly View Post
And no, I meant new. As I recall, possibly a faulty recall, we should prefer new over malloc. Should that change? And does it make a significant difference?
Any reference to the "new" capability, or some advisory where programmers are supposed to use new over malloc?

Just my $0.02, malloc() works. And has done so for ... can't guess how many years, I've been using it for about 30 years. Searching for references using new in C programs only found descriptions of how to use new in C++.

Sorry, but perhaps I'm still reading you in reverse or something.
 
Old 07-06-2020, 10:55 PM   #5
bkelly
Member
 
Registered: Jan 2008
Distribution: Centos 7-4
Posts: 205

Original Poster
Rep: Reputation: 13
Quote:
Originally Posted by rtmistler View Post
OK, so C code only.Any reference to the "new" capability, or some advisory where programmers are supposed to use new over malloc?

Just my $0.02, malloc() works. And has done so for ... can't guess how many years, I've been using it for about 30 years. Searching for references using new in C programs only found descriptions of how to use new in C++.

Sorry, but perhaps I'm still reading you in reverse or something.
I did state it might be a faulty memory. Lets presume it is and go with malloc. So,..., what is the syntax to pass a pointer to a function such that the function can malloc the memory, put data in that memory, and the caller can use said data?
 
Old 07-06-2020, 11:04 PM   #6
SoftSprocket
Member
 
Registered: Nov 2014
Posts: 399

Rep: Reputation: Disabled
Here's a simple example of creating an array with new.

Code:
#include <iostream>
#include <string>

int main () {
	std::string *strs = new std::string [3];

	for (int i = 0; i < 3; ++i) {
		std::cin >> strs[i];
	}

	
	for (int i = 0; i < 3; ++i) {
		std::cout << strs[i] << "\n";
	}

        delete [] strs;

	return 0;

}
 
Old 07-07-2020, 09:51 AM   #7
bkelly
Member
 
Registered: Jan 2008
Distribution: Centos 7-4
Posts: 205

Original Poster
Rep: Reputation: 13
Quote:
Originally Posted by SoftSprocket View Post
Here's a simple example of creating an array with new.

Code:
#include <iostream>
#include <string>

int main () {
	std::string *strs = new std::string [3];
...
That does not answer the question. What is the syntax to new or malloc an array when the pointer is passed to a function and the malloc/new is performed within the function:
Code:
int main(){...
float *the_data;
int    data_size;
status = my_function( &the_data, &data_size  ... }

status = my_function( float &the_data, & data_size ){... 
   data_size = 128;
   the_data = new float[ data_size ];
// or if preferred
   the_data = malloc( data_size );
   ... }
 
Old 07-07-2020, 10:10 AM   #8
SoftSprocket
Member
 
Registered: Nov 2014
Posts: 399

Rep: Reputation: Disabled
Code:
#include <iostream>

void allocate_array (float** farr, int n) {                                                                                     
    *farr = new float[n];                                                                                                                                                                                                                           
    for(int i = 0; i < 4; ++i) {                                                                                                    
        (*farr)[i] = (float) i;                                                                                         
    }                                                                                                                                                                                                                                       
}                                                                                                                                                                                                                                               

int main () {                                                                                                                   
    float* farr;                                                                                                                                                                                                                                    
    allocate_array (&farr, 4);                                                                                                                                                                                                                      
    for (int i = 0; i < 4; ++i) {                                                                                                   
        std::cout << farr[i] << "\n";                                                                                   
    }                                                                                                                                                                                                                                                 
    return 0;                                                                                                       
}

Last edited by SoftSprocket; 07-07-2020 at 10:11 AM. Reason: formatting
 
Old 07-07-2020, 10:16 AM   #9
SoftSprocket
Member
 
Registered: Nov 2014
Posts: 399

Rep: Reputation: Disabled
In a C++ function signature the & sign denotes a reference not a pointer.

This will also work:
Code:
#include <iostream>
                                                                                                     
void allocate_array (float* &farr, int n) {
        farr = new float[n];

        for(int i = 0; i < 4; ++i) {
                farr[i] = (float) i;
        }

}

int main () {
        float* farr;

        allocate_array (farr, 4);

        for (int i = 0; i < 4; ++i) {
                std::cout << farr[i] << "\n";
        }

        return 0;
}
 
Old 07-07-2020, 10:52 AM   #10
bkelly
Member
 
Registered: Jan 2008
Distribution: Centos 7-4
Posts: 205

Original Poster
Rep: Reputation: 13
I am working on post 9 from SoftSprocket. But, I am using a computer from work at home in an odd setup and just lost two days work due to a reboot. Starting over. But I do note that the answer looks much simpler that I was expecting. I often make things too complicated and cannot see the easy solution.
 
Old 07-07-2020, 01:51 PM   #11
pan64
LQ Addict
 
Registered: Mar 2012
Location: Hungary
Distribution: debian/ubuntu/suse ...
Posts: 21,848

Rep: Reputation: 7309Reputation: 7309Reputation: 7309Reputation: 7309Reputation: 7309Reputation: 7309Reputation: 7309Reputation: 7309Reputation: 7309Reputation: 7309Reputation: 7309
Just you need to remember to free the memory. Sometimes.
 
Old 07-07-2020, 02:10 PM   #12
SoftSprocket
Member
 
Registered: Nov 2014
Posts: 399

Rep: Reputation: Disabled
Yes, negligence on my part.
 
Old 07-07-2020, 03:47 PM   #13
bkelly
Member
 
Registered: Jan 2008
Distribution: Centos 7-4
Posts: 205

Original Poster
Rep: Reputation: 13
Quote:
Originally Posted by SoftSprocket View Post
In a C++ function signature the & sign denotes a reference not a pointer.

This will also work:
Code:
#include <iostream>
                                                                                                     
void allocate_array (float* &farr, int n) {
                     ^^^^^^^^^^^^
The combination of * and the & befuddles me. Please explain.
 
Old 07-07-2020, 05:11 PM   #14
SoftSprocket
Member
 
Registered: Nov 2014
Posts: 399

Rep: Reputation: Disabled
The pointer (*) is necessary for the allocated array. The reference (&) can be thought of as a constant pointer that automatically dereferences. In the example "float* &farr" is a reference to a pointer. It can't be reassigned like a pointer and in that way is different from a pointer to a pointer, "float** far", like in my earlier example.

An address doesn't exist for the float* that is passed in until it is allocated so in order for the address from the call to new to be accessible outside the function the address of the float* needs to be created - either through the extra pointer or a reference.

I hope that makes sense. There's probably a cleared way to say it but my thinking cap isn't working at the moment.
 
Old 07-07-2020, 06:41 PM   #15
bkelly
Member
 
Registered: Jan 2008
Distribution: Centos 7-4
Posts: 205

Original Poster
Rep: Reputation: 13
Yes, it mostly makes sense. I think you explained it well. I was thinking along the lines of **. Combining the * & gives the compiler more information, I presume. And yes, the code does work for me.
Thank you for your time and patience.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Java Array's.... Making An array bigger??? Tru_Messiah Programming 11 08-17-2016 01:45 PM
BASH-Adding array element: Naming issue using array[${#array[*]}]=5 calvarado777 Programming 8 07-26-2013 09:48 PM
Bash array Add function example using indirect array reference as function argument bobywelsh Programming 10 07-05-2010 04:44 AM
[SOLVED] Threaded function cannot call a function with extern "C" but nonthreaded function can morty346 Programming 16 01-12-2010 05:00 PM
PERL: Size of an array of an Array inspleak Programming 2 03-10-2004 02:24 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 03:08 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration