Thread: How to copy array without create a new one

  1. #1
    Registered User
    Join Date
    Aug 2004
    Posts
    6

    How to copy array without create a new one

    If I would like to copy array like this:

    suppose I got and array of char, i.e. char buffer[50]. The want to copy them by reference to char* mydata.

    Code:
     mydata = buffer;
    but then if I change buffer, mydata also change. Is there any way to let the buffer change its address so that I don't have to copy them to another location.

  2. #2
    Registered User
    Join Date
    Aug 2004
    Posts
    6

    Another question

    When should I allocate and free memory? Do I have to free memory when declare array? Or only pointer needs to be freed?

  3. #3
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    You only free() memory that was allocated using malloc() or calloc().

    There's no way to get 2 seperate copies of an array without creating 2 arrays. You can easily copy the entire contents of an array using a simple memcpy() command though:
    Code:
    {
      char buffer[50];
      char mydata[50];
    
      // Fill buffer with whatever
    
      memcpy(mydata, buffer, 50);
    
      // Now mydata is an exact copy of buffer.
    }
    memcpy() will work with any data type, but for the 3rd arg you'll want to make sure you're copying the correct number of bytes. For instance, if buffer and mydata were arrays of type int you would do memcpy(mydata, buffer, sizeof(int)*50);.

  4. #4
    Quote Originally Posted by thone
    If I would like to copy array like this:

    suppose I got and array of char, i.e. char buffer[50]. The want to copy them by reference to char* mydata.
    "copy <...> by reference" has no meaning.
    Code:
     mydata = buffer;
    If you do that, you just assign a value to a variable. The value is the address of the buffer array, and the variable is a pointer to char. It's now pointing to 'buffer' (actually, buffer + 0).
    but then if I change buffer, mydata also change. Is there any way to let the buffer change its address so that I don't have to copy them to another location.
    If you want a copy, you need room. No miracle to be expected here!

    Statically:
    Code:
    {
       char mydata[sizeof buffer];
    
       memcpy (mydata, buffer, sizeof buffer); /* <string.h> */
    }
    Dynamically:
    Code:
    {
       char* mydata = malloc (sizeof buffer); /* <stdlib.h> */
       if (mydata != NULL)
       {
          memcpy (mydata, buffer, sizeof buffer);
          
           /* when finished */
          free (mydata), mydata = NULL;
       }
    }
    Emmanuel Delahaye

    "C is a sharp tool"

  5. #5
    Quote Originally Posted by thone
    When should I allocate and free memory? Do I have to free memory when declare array? Or only pointer needs to be freed?
    No. Only allocated blocs must be freed.

    BTW, try to be more accurate in your wording. You don't free a pointer. You free the pointed block.
    Emmanuel Delahaye

    "C is a sharp tool"

  6. #6
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    but then if I change buffer, mydata also change. Is there any way to let the buffer change its address so that I don't have to copy them to another location.

    that's because they point to the same block of memory. you might use a function to return a dynamically allocated copy, ie:

    Code:
    void * copy(const void * data, size_t length)
    {
     void * block = malloc(length);
     if(block) {
      memcpy(block, data, length);
      }
     return block;
    }
    
    char * strcopy(const char * str)
    {
     return copy(str, strlen(str)+1);
    }
    of course you'll need to delete the allocated block when you're done with it...
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  7. #7
    Registered User
    Join Date
    Aug 2004
    Posts
    6
    I have to thank you everyone, and then appologize that my description make you misunderstand about my question. What I really want to do is to pass a pointer to another variable.

    For example,

    buffer points to 0x0000

    then when I assigned

    mydata = buffer

    mydata will point to 0x0000

    then I would like to reallocate buffer so that it can be used for storing other data (e.g. change it to another address) and don't care its data anymore since mydata already pointed to them.

    buffer pointed to <new instance>

    To be more clear, what I want to do is this:

    I receive unsigned char buffer[512] from a socket, and I would like to process them but I don't want to copy them since it will eat up CPU and time (i write codes for an embeded device). So that I can use buffer for another incoming packet from network.

    I know that in Java or VB they has ketword new to do this. I wonder whether C has the same keyword or any technique to do that. If I can do this without malloc, it would be great (I do not have to free memory, my memory is only 512K).

  8. #8
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926
    realloc() doesn't change the data to another address. new is the equivalent to malloc in C++. either way you are getting memory. So you will have to use it.

  9. #9
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    realloc() and will move the data to another location if it needs to.

  10. #10
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by thone
    I receive unsigned char buffer[512] from a socket, and I would like to process them but I don't want to copy them since it will eat up CPU and time (i write codes for an embeded device). So that I can use buffer for another incoming packet from network.

    I know that in Java or VB they has ketword new to do this. I wonder whether C has the same keyword or any technique to do that. If I can do this without malloc, it would be great (I do not have to free memory, my memory is only 512K).
    new "eats up CPU time" also. How do you think it does anything? Magicly bypassing the CPU and instantly creating a copy of whatever it is you're trying to copy with it?

    You can't simply clone an item without there being overhead. It can't magicly appear. Somewhere, someplace, something is working to get the job done.

    If you need to "copy arrays" so that they "point someplace else", you'll need to not use arrays, and dynamicly allocate memory.

    And, yes, you must free anything you malloc. For each malloc call, there must be a call to free. If you don't, you'll have nice little chunks of memory allocated some place, eating up your spacious "512K", so eventually you'll run out. Then guess what happens? BadThings(TM)

    Quzah.
    Hope is the first step on the road to disappointment.

  11. #11
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708

    Lightbulb

    Quote Originally Posted by thone
    I have to thank you everyone, and then appologize that my description make you misunderstand about my question. What I really want to do is to pass a pointer to another variable.

    For example,

    buffer points to 0x0000

    then when I assigned

    mydata = buffer

    mydata will point to 0x0000

    then I would like to reallocate buffer so that it can be used for storing other data (e.g. change it to another address) and don't care its data anymore since mydata already pointed to them.

    buffer pointed to <new instance>

    To be more clear, what I want to do is this:

    I receive unsigned char buffer[512] from a socket, and I would like to process them but I don't want to copy them since it will eat up CPU and time (i write codes for an embeded device). So that I can use buffer for another incoming packet from network.

    I know that in Java or VB they has ketword new to do this. I wonder whether C has the same keyword or any technique to do that. If I can do this without malloc, it would be great (I do not have to free memory, my memory is only 512K).

    I think I see what you're trying to do here. something like:

    Code:
    const int max_chunk = 512; // amount to call recv on.
    const int max_ptrs = 1024;
    char * pool = (char*)0x00000000; // should be interesting...
    char * limit = (char*)0x00080000; 
    char * recbuf = pool;
    char * ptrs[max_ptrs];
    int bytes_received, ptr_count = 0; 
     while((recbuf + max_chunk < limit) && (ptr_count < max_ptrs)) {
      /* recv into recbuf and store 
         result into 'bytes_received' */
      recbuf[bytes_received] = 0;
      ptrs[ptr_count++] = recbuf; 
      recbuf += (bytes_received+1);
      }
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  12. #12
    Quote Originally Posted by thone
    I receive unsigned char buffer[512] from a socket, and I would like to process them but I don't want to copy them since it will eat up CPU and time (i write codes for an embeded device). So that I can use buffer for another incoming packet from network.
    Ok. You should have (at least) 2 arrays of 512 bytes. and a simple allocation algorithm
    Pseudo-code:
    Code:
       char a[512]
       char b[512]
    
    initialization:
    
       char *p_rec := a
       char *p_process := b
    
    Process loop:
    
       receive (p_rec)
       swap (p_rec, p_process)
       process (p_process)
    Emmanuel Delahaye

    "C is a sharp tool"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Create random array
    By Hunter_wow in forum C++ Programming
    Replies: 3
    Last Post: 09-21-2007, 05:29 AM
  2. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  3. Create Array size Question
    By popohoma in forum C++ Programming
    Replies: 3
    Last Post: 11-04-2002, 03:04 AM
  4. Create array of CArray
    By ooosawaddee3 in forum C++ Programming
    Replies: 0
    Last Post: 09-30-2002, 11:22 AM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM