473,473 Members | 1,844 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

passing a pointer from a function help needed

4 New Member
Hi,
I'm very new to C and need help with what I'm doing wrong here and why this piece of code doesn't work (the total column prints rubbish):

/* Total 2 arrays into a 3rd array in a function and return the pointer for the first element of the 3rd array. Display the 1st, 2nd and 3rd array in columns */

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #define MAX34 5
  3.  
  4. long array3[MAX34] = {2,3,2,3,2};
  5. long array4[MAX34] = {3,4,3,4,3};
  6. long *point_a, *point_b; 
  7. long ctr = 0;
  8.  
  9. long * addarrays(long d[], long e[], long len);
  10.  
  11. main()
  12. {
  13.  
  14. point_a = addarrays(array3, array4, MAX34);
  15.  
  16. point_b = point_a;
  17.  
  18. for (ctr = 0; ctr < MAX34; ctr++)
  19. {
  20. printf("\n\t%ld\t\%ld\t%ld\n", array3[ctr], array4[ctr], *(point_b++));
  21. }
  22.  
  23.  
  24. return 0;
  25. }
  26.  
  27.  
  28. long * addarrays(long d[], long e[], long len)
  29. {
  30. long ctr = 0;
  31. long array5[] = {0,0,0,0,0};
  32. long *newpoint;
  33.  
  34. newpoint = array5;
  35.  
  36. for (ctr = 0; ctr < len; ctr++)
  37. {
  38. array5[ctr] = array3[ctr] + array4[ctr];
  39. }
  40.  
  41. return newpoint;
  42. }
  43.  
Sep 7 '08 #1
5 1192
Banfa
9,065 Recognized Expert Moderator Expert
Expand|Select|Wrap|Line Numbers
  1. long * addarrays(long d[], long e[], long len)
  2. {
  3.     long ctr = 0;
  4.     long array5[] = {0,0,0,0,0};
  5.     long *newpoint;
  6.  
  7. /* newpoint points to array5, array5 is on the stack */
  8.     newpoint = array5;
  9.  
  10.     for (ctr = 0; ctr < len; ctr++)
  11.     {
  12. /* You are using your global variables in stead of the function parameters */
  13.         array5[ctr] = array3[ctr] + array4[ctr];
  14.     }
  15.  
  16. /* You return newpoint, but newpoint points to array5 and array5 is on the stack.  As soon as the function returns array5 is released so you are returning a pointer to data that has just been relesed and is almost certainly used for something else by printf.  When returning a pointer it is imperative to make sure that the data you are returning a pointer to still exists after the function has ended.  In this particular case I would say the best thing would be to pass as a 4th parameter a pointer to the location to store the result of the function, however another option is to malloc data for the function to return but the the calling function has to remember to free it. */
  17.     return newpoint;
  18. }
  19.  
Sep 7 '08 #2
needchelp
4 New Member
Thanks for the reply, but I'm a bit lost. This was an exercise from "Teach yourself C in 21 days" - day 9, before malloc has been discussed. Unfortunately, it's an ON YOUR OWN exercise, so no answer is given at the back of the book, and the chapter doesn't have any examples of how to do this. I don't really understand your first option - would it be rude to ask for an example?
Sep 7 '08 #3
Banfa
9,065 Recognized Expert Moderator Expert
Instead of

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. static char *ReturnHelloWorld(void);
  5.  
  6. int main()
  7. {
  8.     printf("%s\n", ReturnHelloWorld());
  9.  
  10.     return 0;
  11. }
  12.  
  13. char *ReturnHelloWorld(void)
  14. {
  15.     char string[50];
  16.  
  17.     strcpy(string, "Hello World");
  18.  
  19.     return string;
  20. }
  21.  
which would have the same problem as your code, returning a pointer to an object that no longer exists do this


Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. static void ReturnHelloWorld(char *buffer);
  5.  
  6. int main()
  7. {
  8.     char string[50];
  9.  
  10.     ReturnHelloWorld(string)
  11.  
  12.     printf("%s\n", string);
  13.  
  14.     return 0;
  15. }
  16.  
  17. void ReturnHelloWorld(char *buffer)
  18. {
  19.     strcpy(buffer, "Hello World");
  20. }
  21.  
Now the result buffer is passed to the function by the caller. The caller has the responsibility for the data. This would be even better if ReturnHelloWorld also took a buffer length and ensured that the end of the buffer was not overwritten thus ensuring the function could not cause memory corruption.

Try both examples (there may be some compilation errors I have not been able to do a test compile as I have just switched from Windows to Linux and I have yet to get a development environment setup again).
Sep 7 '08 #4
needchelp
4 New Member
thanks, I'll try those.
Sep 7 '08 #5
needchelp
4 New Member
Thanks for your help - got it working at last.
Sep 8 '08 #6

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

Similar topics

58
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of...
7
by: James Vanns | last post by:
Sounds nasty doesn't it!! Well it's kinda what I need to do! I have an external C struct (external to the C++ project/classes etc.) which is wants a function ptr assigned to one of it's members: ...
6
by: Ian Robertson | last post by:
I am trying to write a function that takes a reference to an object as its arguement. The object is created in another function and I am trying to pass the object to another function from within...
3
by: Thomas Christmann | last post by:
Hi! Sorry for the weird topic, I don't know how to describe it better... I have a little problem here I can't wrap my mind around. If I do: ------------------------------------- #define DWORD...
11
by: truckaxle | last post by:
I am trying to pass a slice from a larger 2-dimensional array to a function that will work on a smaller region of the array space. The code below is a distillation of what I am trying to...
4
by: dogalacar | last post by:
Hi All, I am trying to pass array of structures from a C dll to C# as msdn sample does(outarrayofstructs sample) but PtrToStructure function gives error : --> "structure must not be a value...
12
by: Mike | last post by:
Consider the following code: """ struct person { char *name; int age; }; typedef struct person* StructType;
7
by: TS | last post by:
I was under the assumption that if you pass an object as a param to a method and inside that method this object is changed, the object will stay changed when returned from the method because the...
8
by: S. | last post by:
Hi all, Can someone please help me with this? I have the following struct: typedef struct { char *name; int age; } Student;
5
by: CapCity | last post by:
I'm sure I'm missing something simple - I do not code in C regularly, and the breaks are long enough for me to forget. The situation I have is I need to create an array but I do not know the...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.