#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2010
    Location
    Patras,Greece
    Posts
    4
    Rep Power
    0

    Unhappy Return an array from a function.


    Hello.

    I m trying to make a function that adds two arrays and returns the sum of them,but my code is not working.

    Code:
    int *test(int *ptr1,int *ptr2)
    {
     	int *ptr;
     	
     	
     	
     	while ( *ptr1!=0 && *ptr2!=0 )
    	{
    	 	  *ptr=*ptr1+*ptr2; 	      
    		  ptr2++;	  
    		  ptr1++;
        }
     	
        return ptr;	
    }
    Any ideas?Thanks!
  2. #2
  3. No Profile Picture
    I haz teh codez!
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Dec 2003
    Posts
    2,540
    Rep Power
    2337
    my code is not working
    Does it make your computer explode?

    You are:

    1. dereferencing an unallocated pointer
    2. returning a value local to the function
    (both of these are undefined behavior)

    3. repeatedly changing the same value in your "sum", not creating an array at all

    Think you need to go back to your book and notes and read some more of what you were supposed to be learning in this chapter.
    Last edited by ptr2void; September 3rd, 2012 at 10:05 AM.
    I ♥ ManiacDan & requinix

    This is a sig, and not necessarily a comment on the OP:
    Please don't be a help vampire!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2010
    Location
    Patras,Greece
    Posts
    4
    Rep Power
    0
    Originally Posted by ptr2void
    Does it make your computer explode?

    You are:

    1. dereferencing an unallocated pointer
    2. returning a value local to the function
    (both of these are undefined behavior)

    3. repeatedly changing the same value in your "sum", not creating an array at all

    Think you need to go back to your book and notes and read some more of what you were supposed to be learning in this chapter.

    Thanks for your reply.I m a beginner.The part of code I wrote was just the function.The whole program is that:

    Code:
    int *test(int *ptr1,int *ptr2);
    
    main()
    {
     	int k[]={1,1};
     	int l[]={2,2};
     	
        
        printf("%d %d\n",test(k,l),test(k,l)-1);
     	
     	
     	   
    system("PAUSE");
    }
    
    int *test(int *ptr1,int *ptr2)
    {
     	int *ptr;
     	
     	
     	
     	while ( *ptr1!=0 && *ptr2!=0 )
    	{
    	 	  *ptr=*ptr1+*ptr2; 	      
    		  ptr2++;	  
    		  ptr1++;
        }
     	
        return ptr;	
    }
    I ll follow your advice to study more.Thanks!
  6. #4
  7. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,091
    Rep Power
    2222
    Do you understand ptr2void's three points? If you do not, then you should ask for an explanation. In programming, we use words that mean specific things and the meaning of which every programmer learns and uses. On Wikipedia, I can see that Greeks use a native Greek word for "pointer" (that link is to the Greek Wikipedia article on pointers), but I do not know whether the other terms are borrowed or native, such as "dereference" or "allocate".

    Originally Posted by ptr2void
    1. dereferencing an unallocated pointer
    Memory is not an abstract concept, but rather actual hardware that you hold in your hand. It is organized as a block of locations, each able to contain 8 bits of data, a byte. Many kinds of data can be stored in memory, including your program's variables and the stack, which is where a function's local variables are stored (along with the function's arguments, the function's return value location, and information for how to access that data and how to return from the function). Every single location has a unique memory address which can be used to access it (ie, read from and write to that location). Most data requires more than one byte, so those values use multiple sequential bytes. Also, arrays consist of as many sequential bytes as are needed to contain its elements.

    A pointer is a memory address. A pointer has to point to something. When you declare a pointer variable inside a function, then it contains whatever value was already in memory, which we call garbage -- that is true of all local variables -- and when you declare the pointer outside a function (ie, as a global) then it is initialized to zero (NULL) -- which is also true of all global variables.

    If you do not initialize a pointer, then it could point anywhere (or to location zero if it's a global). Your program is only one of a large number of programs loaded into memory at the same time and running concurrently. The operating system gives each program its own memory space to use and which contains the program's executable code, stack, variables, and heap (a special memory segment; see below). The operating system does not allow your program to access anybody else's memory space and will terminate your program when it tries, usually reporting a "access" or "segmentation fault" (AKA "segfault") run-time error. If your uninitialized pointer contains garbage, then the probability is high that it will try to access memory that you do not have access to. If it's NULL, then it's guaranteed to try to access memory belonging to the operating system. Both cases will result in your program's immediate termination -- it will "crash". If your garbage pointer just happens to point inside your own memory space, then it will most likely point to code, the stack, or your global variables, such that writing to those locations will corrupt your program and result in it producing expected (and very wrong) output or even to fail to execute (cause it to crash).

    Never use a pointer until you have pointed it somewhere; ie, you must initialize it first to a valid address that it can use. Failure to do so will only cause you very grave problems. You have failed to do so in your program.

    You can point your pointer to a variable or array that already exists. That can be useful in some code and is necessary when passing an argument to a function which needs to change the value of that argument. Neither use is what you need. Instead, you need to create an array and to assign values to it. In order to do that, you need to allocate memory from the heap and point your pointer to that allocated memory.

    The functions you would need to learn how to use are malloc, calloc, and possibly realloc, as well as free for freeing up that heap memory after you no longer need it (failure to do so results in memory leaks).

    The bottom line is that until you have pointed a pointer to memory that it can safely use, you must not use that pointer!


    Originally Posted by ptr2void
    2. returning a value local to the function
    All local variables reside on the stack (H στοίβα. When you call a function, your program allocates new space on the stack (called "pushing") to contain all the data that the functions needs (eg, return information, arguments, local variables). Those local variables only exist as long as the function is being executed. As soon as the function returns, its stack data disappears (called popping) and that memory space is then reused by the next function to be called (whereupon your data will be its garbage).

    If you point to a local variable and return that pointer, then the value that you're pointing to can very well have changed before the calling function can use it. Hence the rule of not returning a reference (basically another term for "pointer") to a function's local variable.

    However, if you malloc or calloc an array into existence from within a function, then it does continue to exist even after you return from that function. In that case, it would be valid to return a pointer to that malloc'd array.

    Originally Posted by ptr2void
    3. repeatedly changing the same value in your "sum", not creating an array at all
    When you have an array, you need to iterate through the array in order to store multiple values in it. Always changing the same element, the zero-th element, does not do what you want.

    At the same time, you must always keep the pointer to the array itself. So malloc the array using one pointer, then set a second pointer to also point to that location and increment that second pointer to iterate through the array.

    If there are problems with language and terminology, make use of Wikipedia. In the left column is a list of other languages that article is in. So look up the article for an English programming term in the English Wikipedia, then switch over to the Greek version of the article. Or the reverse so that you can see what the English version of the terminology you've learned in class would be. As I said, we all know the English terminology for C programming, so that is our lingua franca that you also need to learn.
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2010
    Location
    Patras,Greece
    Posts
    4
    Rep Power
    0
    Thank you very much for your explanation!I ll follow your suggestions.I was a bit confused with the use of pointers.i would be grateful if someone has some time to post the code for a function that takes two arrays and returns their sum.Just to have it as an example.:)
  10. #6
  11. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,594
    Rep Power
    4207
    I'll give you a hint.
    Code:
    void add_arrays(int *ptr1, int *ptr2, int *out_result)
    Caller should call add_arrays() with three arguments and the third argument will be filled up by the add_arrays function.
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2010
    Location
    Patras,Greece
    Posts
    4
    Rep Power
    0
    Originally Posted by Scorpions4ever
    I'll give you a hint.
    Code:
    void add_arrays(int *ptr1, int *ptr2, int *out_result)
    Caller should call add_arrays() with three arguments and the third argument will be filled up by the add_arrays function.
    Thanks for the hint!The thing is that I want the result to be returned as an array...Could this be done?For example,to return a pointer that has the address of the first element of the sum_array and then to print the other elements...
  14. #8
  15. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,091
    Rep Power
    2222
    As I already explained to you: allocate the array, fill it, and return it.
  16. #9
  17. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    San Francisco Bay
    Posts
    1,939
    Rep Power
    1313
    Originally Posted by Kleanthis
    Thanks for the hint!The thing is that I want the result to be returned as an array...Could this be done?For example,to return a pointer that has the address of the first element of the sum_array and then to print the other elements...
    You can (by doing as dwise1_aol said), but Scorpions4ever's way is more idiomatic. Allocating an array inside the function is okay if it's difficult for the caller of the function to know large the result array will be, but that isn't the case here.

IMN logo majestic logo threadwatch logo seochat tools logo