memcpy.

Discussion in 'Mac Programming' started by farmerdoug, Mar 15, 2010.

  1. farmerdoug macrumors 6502a

    Joined:
    Sep 16, 2008
    #1
    As I understand memcpy takes from one memory location and copies it to another. Therefore it needs the address of both locations.


    Code:
    float *A,  *B;
    
     if ((A = (float *)calloc(reduced_image ,sizeof(float))) == NULL)
            {
                printf("no cys1 memory\n");
                exit(0);
            }
    
        if ((B = (float *)calloc(slices*reduced_image,sizeof(float))) == NULL)
            {
                printf("no cys1 memory\n");
                exit(0);
            }
    
    memcpy(B + slice*reduced_image, A, sizeof(float)* reduced_image); 
    
    Now I want to copy a part of a large array B into a part of a large array C defined as a **:

    Code:
    float *B,  **C;
    
     if ((B = (float *)calloc(slice* reduced_image ,sizeof(float))) == NULL)
            {
                printf("no cys1 memory\n");
                exit(0);
            }
    
     C = calloc(slice, sizeof(float*));
        for (i = 0; i < slice; i ++)
            C[i] = calloc(imagesize,sizeof(float));
      
    
    memcpy(?,B + slice*reduced_image, sizeof(float)* reduced_image); 
    
    So what replaces the question mark? I would have thought that C[slice] would work but neither that nor &C[slice] works nor does &C + slice*imagesize but I get a can't access memory at that line.
     
  2. iSee macrumors 68040

    iSee

    Joined:
    Oct 25, 2004
    #2
    I don't understand what you are trying to accomplish, but I have one questiona and noticed one problem:

    * When you say it doesn't work, you mean it crashes? (vs. e.g., doesn't complile, etc.)

    C is an array of float pointers (float*). The size of the array is slice. That is, you have slice pointers, where the index of the first one is 0 and the index of the last one is slice-1.

    So C[slice] is not going to be a valid pointer because you're accessing a pointer out of bounds of the array you allocated. But I can't suggest how to fix it since I don't know what you're trying to do.
     
  3. ChrisA macrumors G4

    Joined:
    Jan 5, 2006
    Location:
    Redondo Beach, California
    #3
    What are you trying to do? If is never a good idea to put "alloc" inside a loop and allocate hundreds of tiny pieces. It is FAR better to allocate the entire array at once.

    Assuming two large arrays..

    memcpy ( &(B), &(A[j]), n*sizeof(float))

    this should move n elements from a[j] to b.
     

Share This Page