473,320 Members | 2,088 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

how to return an array from the function

Siddarth777
i have written the code below which should print the value int the first array location
<CODE>
#include<stdio.h>
int arr(int *n)
{
int a[20],i;
printf("ENTER THE ELEMENTS OF ARRAY:");
for(i=0;i<*n;i++)
scanf("%d",&a[i]);
return a;
}
main()
{
int a[50],i,s,*val;
printf("ENTER THE SIZE OF THE ARRAY:");
scanf("%d",&s);
val=arr(&s);
fflush(stdout);
printf("THE RETURNED ARRAY IS:%d",*val);
}
</CODE>
Though there are no errors,i am getting few warnings

retarr.c: In function ‘arr’:
retarr.c:8: warning: return makes integer from pointer without a cast
retarr.c:8: warning: function returns address of local variable
retarr.c: At top level:
retarr.c:11: warning: return type defaults to ‘int’
retarr.c: In function ‘main’:
retarr.c:15: warning: assignment makes pointer from integer without a cast
retarr.c:12: warning: unused variable ‘i’
retarr.c:12: warning: unused variable ‘a’
retarr.c:18: warning: control reaches end of non-void function

how to make the program print the value present in first location of the array,which i have given as input?

please help
thanks in advance
Dec 16 '10 #1

✓ answered by donbock

Referring to your original source code.
  1. Use square brackets (not angle brackets) around your CODE tags.
  2. Function arr fills local array a[20]. It would very bad if arr were called with a parameter value greater than 20. This function should protect itself.
  3. By the way, what's the benefit of using call-by-reference instead of call-by-value in function arr? There's no harm in doing it your way, although you might want to make the argument a pointer-to-const to guarantee arr can't change the caller's parameter value.
  4. The definition of function arr says that it returns an integer, but you return an array of int, which actually returns the address of the first element of the array (that is, a pointer-to-int). This is the source of the first warning.
  5. Function arr returns the address of local array a. Local variables cease to exist once their enclosing function returns. This means that main is referencing ghost variables if it tries to dereference the returned pointer. That is undefined behavior -- there is no way to predict what will happen. This is the source of the second warning.
  6. You defined the main function without specifying its return type. Without an explicit return type, the compiler assumes the function returns an int. This is the source of the third warning. By the way, the return type mandated for main by the Standard is int.
  7. Function main assigns the return value of function arr to variable val. Function arr is defined to return an int, but variable val is a pointer-to-int. This discrepancy is the source of the fourth warning.
  8. Function main defines local variables a[50] and i, but never uses them. This is the source of the fifth and sixth warnings.
  9. Function main has [implicit] return type int, but execution falls through to the bottom of the function without encountering a return statement. What int value should it return? This is the source of the seventh warning.

9 2368
johny10151981
1,059 1GB
with your current development can only print the first data in INT array.

to print all you will have to follow loop
Dec 16 '10 #2
thanks a lot for ur reply....................
but the problem is,it is not even printing the first value
Dec 16 '10 #3
johny10151981
1,059 1GB
i tested your program in my machine. it print the first value.

well try this way. return ->
Expand|Select|Wrap|Line Numbers
  1. return &a[0];
  2.  
Dec 16 '10 #4
manontheedge
175 100+
this code below will do what you're trying to do. I ran it in a C++ compiler just to make sure it was working. I tried to comment to help you out. Take a look, hope this helps ...

Expand|Select|Wrap|Line Numbers
  1. #include<iostream>
  2. #include<stdio.h>
  3.  
  4. //int arr(int *n)
  5. void arr(int a[], int size) // need to pass an array AND the size of it
  6. {
  7.     //int a[20]; don't need this
  8.     printf("ENTER THE ELEMENTS OF ARRAY:");
  9.     for( int i=0; i<size; i++ )
  10.     //scanf("%d",a[i]);
  11.     std::cin >> a[i];
  12.     //return a; // you can't return an array, must use passing by value
  13. }
  14. void main()
  15. {
  16. //    int a[50]; // it's a good idea not to hard code the size of an array if you can avoid it
  17. //    int i;    // not being used
  18.     int size = 0;
  19. //    int *val; // don't need this
  20.     printf("ENTER THE SIZE OF THE ARRAY:");
  21.     //scanf("%d",size);
  22.     std::cin >> size; 
  23.  
  24.     int* a = new int[size]; // here, a new, DYNAMICALLY allocated array is created
  25.  
  26.     //val=arr(&s); 
  27.     // instead of returning, you pass the array BY VALUE, along with the array's SIZE
  28.     //    this allows the array 'a' to be changed in another function and everyone can
  29.     //    see the changes
  30.     arr(a, size);
  31.  
  32.     fflush(stdout);
  33.  
  34.     for( int i = 0; i < size; i++ ) // added this to print ALL of the values
  35.     {
  36.         printf("THE RETURNED ARRAY IS:%d",a[i]);
  37.     }
  38.  
  39.     int x;
  40.     std::cin >> x;
  41. }
  42.  
Dec 16 '10 #5
donbock
2,426 Expert 2GB
Referring to your original source code.
  1. Use square brackets (not angle brackets) around your CODE tags.
  2. Function arr fills local array a[20]. It would very bad if arr were called with a parameter value greater than 20. This function should protect itself.
  3. By the way, what's the benefit of using call-by-reference instead of call-by-value in function arr? There's no harm in doing it your way, although you might want to make the argument a pointer-to-const to guarantee arr can't change the caller's parameter value.
  4. The definition of function arr says that it returns an integer, but you return an array of int, which actually returns the address of the first element of the array (that is, a pointer-to-int). This is the source of the first warning.
  5. Function arr returns the address of local array a. Local variables cease to exist once their enclosing function returns. This means that main is referencing ghost variables if it tries to dereference the returned pointer. That is undefined behavior -- there is no way to predict what will happen. This is the source of the second warning.
  6. You defined the main function without specifying its return type. Without an explicit return type, the compiler assumes the function returns an int. This is the source of the third warning. By the way, the return type mandated for main by the Standard is int.
  7. Function main assigns the return value of function arr to variable val. Function arr is defined to return an int, but variable val is a pointer-to-int. This discrepancy is the source of the fourth warning.
  8. Function main defines local variables a[50] and i, but never uses them. This is the source of the fifth and sixth warnings.
  9. Function main has [implicit] return type int, but execution falls through to the bottom of the function without encountering a return statement. What int value should it return? This is the source of the seventh warning.
Dec 16 '10 #6
thanks a lot everyone for your valuable replies
especially DONBOCK thanks a lot for your explanation of the warnings

but it did not help
am unable to get the output, i.e to print the complete array
am not getting any errors or warnings

this is the code
Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2.  int* arr(int *n)
  3. {
  4. int a[20],i,*add;    //'add' is for storing the address of the first location in the array
  5. printf("ENTER THE ELEMENTS OF ARRAY:");
  6. for(i=0;i<*n;i++)
  7. scanf("%d",&a[i]);
  8. add= &a[0];
  9. return add;    //returning the address of the 'a[0]'
  10. }
  11. int main()
  12. {
  13. int s,i;
  14. int *val;
  15. printf("ENTER THE SIZE OF THE ARRAY:");
  16. scanf("%d",&s);
  17. val=arr(&s);
  18. fflush(stdout);
  19. for(i=0;i<s;i++)
  20. printf("THE RETURNED ARRAY IS:%d",*val);    //printing the  complete array
  21. return 0;
  22. }
  23.  
please help
thanks a lot in advance
Dec 18 '10 #7
donbock
2,426 Expert 2GB
  1. Refer to item #5 in my earlier post. You haven't fixed this yet. Note what I said: "there is no way to predict what will happen". You must fix this.
  2. Refer to the loop in lines 19 and 20 of your new source code. This loop prints the first entry in the array over and over again.
Dec 19 '10 #8
Thanks a lot for all,who helped me in my code development
i have figured a way to return the complete array it is working

heres the code i am posting

any enhancements needed?
please let me know

here is my code:
Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2.  
  3. //#include<conio.h>
  4.  
  5. int siddu(int *x)
  6.  
  7. {
  8.  
  9. int i;
  10.  
  11. int a[20];
  12.  
  13. //printf("enter the size of array:");
  14.  
  15. //scanf("%d",x);
  16.  
  17. fflush(stdin);
  18.  
  19. printf("ENTER THE ARRAY ELEMENTS:");
  20.  
  21. for(i=0;i<*x;i++){
  22.  
  23. scanf("%d",&a[i]);
  24.  
  25. //for(i=0;i<*x;i++)
  26.  
  27. return a[i];
  28.  
  29. }
  30.  
  31. }
  32.  
  33. int siddu2(int *x)
  34.  
  35. {
  36.  
  37. int a[20],i;
  38.  
  39. for(i=0;i<*x;i++){
  40.  
  41. scanf("%d",&a[i]);
  42.  
  43. //for(i=0;i<*x;i++)
  44.  
  45. return a[i];
  46.  
  47. }
  48.  
  49. }
  50.  
  51. void main()
  52.  
  53. {
  54.  
  55. int n,j,ret[20];
  56.  
  57. //clrscr();
  58.  
  59. printf("enter the no of sides:");
  60.  
  61. scanf("%d",&n);
  62.  
  63. for(j=0;j<n;j++){
  64.  
  65. if(j>0){
  66.  
  67. ret[j]=siddu2(&n);
  68.  
  69. continue;
  70.  
  71. }
  72.  
  73. ret[j]=siddu(&n);
  74.  
  75. }
  76.  
  77. fflush(stdout);
  78.  
  79. for(j=0;j<n;j++)
  80.  
  81. printf("%d",ret[j]);
  82.  
  83. //getch();
  84.  
  85. }
  86.  
Dec 21 '10 #9
donbock
2,426 Expert 2GB
What do you intend to be the difference between siddu and siddu2? I don't see any practical difference between them. siddu calls fflush on stdin, but that is undefined behavior. The other difference is that siddu prints an annunciator string before entering the data entry loop.

Both siddu and siddu2 enter a data entry loop but return to the caller after the first pass through the loop. Why have code for a loop that you don't intend to execute? Similarly, why allocate a 20-entry array when you don't intend to use more than its first entry?

Line 51: it is illegal for main to return void. It must return int. If you change the definition on line 51 then you need to terminate the function with a return statement.

The loop between lines 63 and 75 has complicated logic that has the effect of calling siddu the first time through the loop and siddu2 for all other iterations. Presumably the reason for doing this is so the siddu annunciator string (line 19) is only printed once. It would be much easier to do that by moving line 19 to somewhere between lines 61 and 63 and simplifying the loop.

The essence of siddu and siddu2 is their calls to scanf (lines 23 and 41). What do you gain by having main call siddu/siddu2 rather than simply calling scanf directly?

Some C platforms have buffered output on stdout. If so, then all printed characters go to an internal buffer. They don't go to the output device until either fflush is called or a newline is printed. You should insert a line between lines 81 and 85 to print a newline (or move line 77 there).

The user does not have to enter what you expect. If the user types in something crazy then scanf will fail and the variable you are trying to load won't change. This would be especially bad if it happened at line 61. You should be checking the return code from scanf.
Dec 21 '10 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: BrianP | last post by:
Hi, I have had to invent a work-around to get past what looks like a JavaScript bug, the malfunctioning Perl-like JavaScript array functions including SPLICE() and UNSHIFT(). I have boiled it...
0
by: Marc van Boven | last post by:
I'm stuck with the following problem: My nusoap-client calls a server-function giveCombination(). The function giveCombination should return something like array( => array( 'a_id' => 6,...
16
by: priya | last post by:
Hi all, I am new to this group.I am working in c language.I have dount in pointer? how to retun array of pointer in function? example main()
2
by: kathy | last post by:
how to return array from function?
2
by: Ali | last post by:
hi i need to send some data to the function and want to return array of object bac lik dim obj() as myclass=AddIt(i,j i dont know that is write syntax or no public function addit(byval i as...
0
by: DWalker | last post by:
VBA, as used in Excel 2000 and Excel 2003, has a function called Array. It's commonly seen in statements like the following: Workbooks.OpenText Filename:=ACFileName, _ StartRow:=1,...
26
by: MLH | last post by:
How would I modify the following to achieve a 2-dimensional array? Dim MyWeek, MyDay MyWeek = Array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") ' Return values assume lower bound set to 1...
10
by: Raj | last post by:
I need a VB function to return array of collections like Private Type Employee empname as string address as string salary as integer deptno as integer End Type dim employees() as Employee
9
by: =?Utf-8?B?RGFya21hbg==?= | last post by:
Hi, I am wondering how you multi-dimension an array function? My declared function looks like this: Public Function GetCustomerList(ByVal Val1 As String, ByVal Val2 As Long, ByVal Val3 As...
4
by: tyv | last post by:
Hi, I encountered a bug on a website that I am working on. The enter/ return key function works in certain parts of the website and doesn't work in other parts. I went through all the scripts...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.