Code Newbie
News     Forums     Search     Members     Sign Up    

My Code Newbie
Username

Password

Articles/Snippets
ASP Classic
ASP.NET
C
C#
C++
HTML / CSS
Java
Javascript
Linux / BSD
Perl
PHP
Python
Ruby
SQL
VB 6
VB.NET

C.N. Friends
  Planet Rome

Link to Us!
Code Newbie
  Code Newbie
    forums
Old 11-14-2006, 02:07 AM   #1 (permalink)
joelw
Code Monkey
 
Join Date: Sep 2006
Posts: 36
joelw is on a distinguished road
help with dynamically allocated arrays

hello,
how would i write a function that will dynamically allocate an array of integers. The function should accept an integer argument indicating the number of elements to allocate. Then return a pointer to the array?
Thanks in advance.
joelw is offline   Reply With Quote
Old 11-14-2006, 08:42 AM   #2 (permalink)
redhead
Newbie
 
redhead's Avatar
 
Join Date: Jun 2002
Location: Denmark
Posts: 1,726
redhead is on a distinguished road
Code:
int* my_function(int* array, int size)
{
  if(size <= 0 || !(array = (int*) malloc(size*sizeof(int))))
    return NULL;
  return array;
}
Use it like:
Code:
...
int* my_array;
...
my_array = my_function(my_array, 10);
...
__________________
Don't worry Ma'am, We're university students, We know what We're doing.
-----
If you pull the pin, Mr.Grenade would no longer be your friend.
-----
01000111 01101111 00100000 01000011 00100000 00100001
redhead is offline   Reply With Quote
Old 11-16-2006, 05:54 AM   #3 (permalink)
joelw
Code Monkey
 
Join Date: Sep 2006
Posts: 36
joelw is on a distinguished road
Smile

ok now i need to fugure out how to write a program that dynamically allocates an array large enough to hold any number of test scores the user wishes to enter using the function i wrote in the earlier submission. after the score are enter, the array should be passed to a function that sorts theem in ascending order and another fucntion should then be called to calculate the average score. can anyone help?
Thanks in advance.
joelw is offline   Reply With Quote
Old 11-16-2006, 07:40 AM   #4 (permalink)
redhead
Newbie
 
redhead's Avatar
 
Join Date: Jun 2002
Location: Denmark
Posts: 1,726
redhead is on a distinguished road
Look at realloc() instead of malloc()
__________________
Don't worry Ma'am, We're university students, We know what We're doing.
-----
If you pull the pin, Mr.Grenade would no longer be your friend.
-----
01000111 01101111 00100000 01000011 00100000 00100001
redhead is offline   Reply With Quote
Old 11-18-2006, 01:12 AM   #5 (permalink)
joelw
Code Monkey
 
Join Date: Sep 2006
Posts: 36
joelw is on a distinguished road
what do you mean?
joelw is offline   Reply With Quote
Old 11-19-2006, 05:45 PM   #6 (permalink)
toe_cutter
Code Monkey
 
Join Date: Aug 2002
Location: Boston, MA
Posts: 79
toe_cutter is on a distinguished road
Send a message via ICQ to toe_cutter Send a message via AIM to toe_cutter Send a message via Yahoo to toe_cutter
man realloc
__________________
toe_cutter is offline   Reply With Quote
Old 11-20-2006, 12:50 PM   #7 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
Do you want the allocation to be done in C or C++ by the way?
__________________
Valmont is offline   Reply With Quote
Old 11-21-2006, 04:38 AM   #8 (permalink)
joelw
Code Monkey
 
Join Date: Sep 2006
Posts: 36
joelw is on a distinguished road
ok

ok i got my program written however im having two problems im trying to get the lowest score to drop off when doing the average score. secondly if you compile my program you can clearly see i have it in acsending order it looks something like this
score 1: 50
score 2: 25
score 3: 75

which is fine but i want it to look like this though
score 2: 25
score 1: 50
score 3: 75

here is my code if anyone can help much appreciated.

.

Code:
#include <iostream>


void sortArray( double arr[], int sz );
void sortArray( double ( &arr[] ), int sz );
void displayArray( double arr[], int sz );


int main()
{
    double *scores, total = 0;  // average;
    int count;
    int numAmount;
    
	cout << "How many test scores are you going to record? ";
	cin >> numAmount;
    scores = new double[numAmount];
    
	cout << "Please enter in your test scores below.\n";
    for ( count = 0; count < numAmount; count++ )
    {
        cout << "Test Score " << (count + 1) << ": ";
        cin >> scores[count];
    }
	
	
	sortArray( scores, numAmount );
	displayArray( scores, numAmount );
	
	delete [] scores;

	return 0;
}

void sortArray( double arr[], int sz )
{
	
}

void displayArray( double arr[], int sz )
{
	cout << std::endl;  // for spacing
	for ( int i = 0; i < sz; i++ )
	{
		std::cout << "Score " << ( i + 1 ) << " : ";
		
		std::cout << arr[i] << std::endl;
	}
}
joelw is offline   Reply With Quote
Old 11-21-2006, 06:06 AM   #9 (permalink)
toe_cutter
Code Monkey
 
Join Date: Aug 2002
Location: Boston, MA
Posts: 79
toe_cutter is on a distinguished road
Send a message via ICQ to toe_cutter Send a message via AIM to toe_cutter Send a message via Yahoo to toe_cutter
I'd bet good money it doesn't sort in any order.

I think your missing a little code.
__________________
toe_cutter is offline   Reply With Quote
Old 12-14-2006, 06:12 AM   #10 (permalink)
joelw
Code Monkey
 
Join Date: Sep 2006
Posts: 36
joelw is on a distinguished road
hello,
ok this code works fine but it still dosnt compute the avearage with the lowest score dropped.
here is my code.
Code:
#include <iostream>
#include <iomanip>

using namespace std;

void sortArray( double arr[], int sz, int scoresPos[], int size );
void displayArray( double arr[], int sz, int scoresPos[], int size );


int main()
{
    double *scores, total = 0;  // average;
	
    int count;
    int numAmount;
    
    cout << "How many test scores are you going to record? ";
    cin >> numAmount;
    scores = new double[numAmount];
    int *scorePos = new int[numAmount];

    cout << "Please enter in your test scores below.\n";
    for ( count = 0; count < numAmount; count++ )
    {
        cout << "Test Score " << (count + 1) << ": ";
        cin >> scores[count];
	scorePos[count] = count + 1;
    }
	

	sortArray( scores, numAmount, scorePos, numAmount );
	displayArray( scores, numAmount, scorePos, numAmount );
	
	delete [] scores;
	delete [] scorePos;


    return 0;
}

//**************************************************  *********************
// Definition of a sortArray                                            *
// This function excepts a double array and its size as an              *             
// argument. The results will be diplayed in ascending order            *
//**************************************************  *********************


void sortArray( double arr[], int sz, int scoresPos[], int size )
{
    double temp = 0;
    int posTemp = 0;

    for ( int i = 0; i < sz - 1; i++ )
    {
        for ( int j = ( i + 1 ); j < sz; j++ )
	{
            if ( arr[i] > arr[j] )
           {
                temp = arr[i];
		posTemp = scoresPos[i];
                arr[i] = arr[j];
		scoresPos[i] = scoresPos[j];
                arr[j] = temp;
		scoresPos[j] = posTemp;
           }
        }
     }
}

//**************************************************  ***********************
// Definition of a display array                                          *
// This function excepts array and its size as an argument. The           *
// average will be displayed dropping the lowest score.                   *
//**************************************************  ***********************


void displayArray( double arr[], int sz, int scoresPos[], int size )
{
	double average = 0;
	double sum = 0;

	std::cout << std::endl;  // for spacing
	for ( int i = 0; i < sz; i++ )
	{
		cout << "Score " << scoresPos[i] << " : ";
		cout << arr[i] << std::endl;
	}
	
	int j;
	for ( j = 1; j < sz; j++ )
	{
		sum += arr[j];
	}

	average = sum / j;

	cout << "\nThe average score disregarding the lowest score is: " << average << endl;
    cout << fixed << showpoint << setprecision(2);
    
}
joelw is offline   Reply With Quote
Old 02-09-2007, 03:30 AM   #11 (permalink)
moodsey211
Recruit
 
moodsey211's Avatar
 
Join Date: Aug 2005
Posts: 14
moodsey211 is on a distinguished road
Smile

Quote:
Originally Posted by joelw View Post

int j;
for ( j = 1; j < sz; j++ )
{
sum += arr[j];
}

average = sum / j;

[/code]
i guess your having problem because of the denominator. for example you have 3 elements in your array, with the scores 1,2,3 respectively. the above code would produce 1.66667 instead of 2.5. its because the code above would add 2 and three which would result to 5 and divide it with 3 which is the total number of elements. which should not be cause you only added two elements of the array and not the whole array.

tip: Life is simple, You just complicate things.
moodsey211 is offline   Reply With Quote
Old 08-19-2008, 01:16 PM   #12 (permalink)
DaveRErickson
Recruit
 
Join Date: Aug 2008
Posts: 1
DaveRErickson is on a distinguished road
Here is a code snippet that can allocate a dynamic (flexible) array of pointers to functions inside a struct

(also known as struct hacking)

I racked my brains looking and then nothing specific, so I just did it

http://aiss.suffield.drdc-rddc.gc.ca...s/c_tips1.html

This works on GCC as is, with no command line switches

[ $ gcc -o test_example example.c ]
[ ./test_example ]

Code:
# DRE 2008

#include <stdlib.h>
#include <stdio.h>

typedef struct 
{
	char name[200];   	//! name of thing
	int stuff;		//! data stuff
	// last member struct hack  - see  All Questions
	void (**a)( int  );	//! ptr to array of  pointer to functions
}struct_array_t;

void fcn1(int a);

int main ()
{
	// struct ptr on heap
	 struct_array_t *  test;
	
	test = malloc (sizeof( struct_array_t ));
	// dynamic malloc on stack
	test->a = malloc ( sizeof(void*) *3 );
	
	test->a[0] = fcn1;
	test->a[1] = fcn1;
	test->a[2] = fcn1;

	printf("these are the addresses contained by array a[0]=%p a[1]=%p a[2]=%p \n", test->a[0],test->a[1],test->a[2]);

	// calling the struct member to execute function (address to execution)
	test->a[0](1);
	test->a[1](2);
	test->a[2](3);	
	return 0;
}


void fcn1(int a)
{
	printf(" I work! %d  ", a);
}
DaveRErickson is offline   Reply With Quote
Old 08-22-2008, 07:29 PM   #13 (permalink)
landonmkelsey
Code Monkey
 
Join Date: Aug 2008
Posts: 74
landonmkelsey is on a distinguished road
the STL reduces tons of C code into a few statements

Long ago in an interview, I was asked to write a program to list the words(tokens) in a file and beside the word print the number of occurrences.

Well I wrote a long C program since I didn't know the STL.

I'll bet this is what they were looking for!

Did I get the job! NO!

Code:
// put this file in histo.cpp
#include <iostream>
#include <iterator>
#include <fstream>
#include <algorithm>
#include <map>
#include <string>
using namespace std;

map<string,int> histo;
void record(const string& s)
{
        histo[s]++;
}
void print(const pair<const string, int>& r)
{
        cout<<r.first<<" , "<<r.second<<endl;
}
int main()
{
        ifstream fin("histo.cpp");
        istream_iterator<string> is(fin);
        istream_iterator<string> eos;
        for_each(is,eos,record);
        for_each(histo.begin(), histo.end(), print);
        return 0;
}
great book on the STL by Schildt (available used)

Last edited by landonmkelsey; 08-22-2008 at 07:33 PM. Reason: code tags!
landonmkelsey is offline   Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

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 On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
[C#] Dynamically adding rows to DataGridView Melon00 MS Technologies ( ASP, VB, C#, .NET ) 0 06-09-2006 02:27 PM
Dynamic Arrays, the 'right' way. Mr.Anderson Standard C, C++ 10 10-05-2004 07:00 AM
Adjust physical output size dynamically metazai PHP 8 08-24-2004 11:15 AM
dynamic allocation..urgent help needed!!! kashif Standard C, C++ 4 04-21-2003 09:50 AM


All times are GMT -8. The time now is 05:24 PM.


Powered by vBulletin® Version 3.7.0
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.0.0 RC8





Copyright © 2000-2008, Milano Interactive
Web Hosting provided by Portal 360 Web Hosting