PDA

Click to See Complete Forum and Search --> : FUNCTION & ARRAY ?!?!?!?!?


programmera
Jun 11th, 2000, 12:17 AM
It's a function "my" that takes a integer array that arguments.
Function shall return a pointers to the smallest numbers.
Problems is:
Why receives I 11 numbers instead receives 10 and that answer latest numbers of them ?????

Examples code:
#include <iostream.h>
#include <stdlib.h>
#include <time.h>
int *my (int *ta, int an)
{
int *temp;
temp = talen;
for (int i=0;i<an;i++)
{
if (ta < temp)
{
temp = ta;
}
ta++;
}
return (temp);
}
main()
{
int ta[10];
int *sv;
srand ((unsigned) time(NULL) );
ta[0]=rand();
for (int i=0; i<10; i++)
cout<<rand()<<endl;
cout << ta [0]<< " ";
cout << endl;
sv = my(ta, sizeof(ta) /sizeof(ta[0]));
cout<< " Smallest numbers is: " << *sv << endl << endl;
cout <<"\nPress any key to continue\n";
getch();
return(0);
}

HarryW
Jun 20th, 2000, 12:44 AM
Erm, I'm having trouble reading that so I'm going to try and repost the code using the code tags, and I'll tidy it up a bit too...


#include <iostream.h>
#include <stdlib.h>
#include <time.h>

int *my (int *ta, int an)
{ int *temp;
temp = talen;
for (int i=0;i<an;i++)
{ if (ta < temp)
temp = ta;
ta++;
}
return (temp);
}

int main()
{ int ta[10];
int *sv;
srand ((unsigned) time(NULL) );
ta[0]=rand();
for (int i=0; i<10; i++)
cout<<rand()<<endl;
cout << ta [0]<< " ";
cout << endl;
sv = my(ta, sizeof(ta) /sizeof(ta[0]));
cout<< " Smallest numbers is: " << *sv << endl << endl;
cout <<"\nPress any key to continue\n";
getch();
return(0);
}



Right, now I'm gonna have a look at it, I'm not sure if that's how you meant the code to be (I think there may be some {} brackets missing, and I took out any that looked unecessary.

HarryW
Jun 20th, 2000, 01:05 AM
Okay, I think this code should work:


#include <iostream.h>
#include <stdlib.h>
#include <time.h>

int* my(int* ta, int an)
{ int* temp;
temp = ta;
for(int j=0;j<an;j++)
{ if(*ta < *temp)
temp = ta;
ta++;
}
return(temp);
}

int main()
{ int ta[10];
int *sv;
srand((unsigned)time(NULL));

//Initialise ta[] array with random integers
for(int j=0; j<10; j++)
{ ta[j]=rand();
cout << "ta[" << j << "] = " << ta[j] << endl;
}

sv = my(ta, sizeof(ta)/sizeof(ta[0]));
cout<< " Smallest numbers is: " << *sv << endl << endl;

return(0);
}



It works for me, I'm using MS Visual C++ 6. I'm not sure what you're using; you have used C-style casts so I suppose you're using C. I've tried to stick to what you used, with corrections.

(I've edited this message to use j instead of i as a counter, because the i in square brackets is italic tags)

[Edited by HarryW on 06-20-2000 at 02:07 PM]