简体   繁体   中英

Save pointer passed to function to array in C

I find this hard to explain but I'll do my best. I am passing an array to a function. I want to be able to grab the pointer of the array in the function and put the values of the array back into an array in the function.

If that doesn't make sense maybe this code will give you an idea of what I'm trying to attempt.

#define LENGTH 3
void FIR(short *filter) {
    short temp[LENGTH] = {*filter, *(filter+1), *(filter+2)};
}
int main() {
    short filter[LENGTH] = {1,2,5};
    FIR(filter);
}   

This code works but is quite ridiculous if the filter length is long. How could I do this for any length of filter array? Keep in my mind, I'm trying to preserve efficiency.

Use a loop, *(filter+x ) is equivalent to filter[x]

#include <stdio.h>
#define LENGTH 3
void FIR(short *filter) {
    short temp[LENGTH];
    int i;
    for(i = 0; i < LENGTH; ++i){
        temp[i] = filter[i];
    }
}
int main() {
    short filter[LENGTH] = {1,2,5};
    FIR(filter);
    int i;
    for(i = 0; i < LENGTH; ++i){
        printf("%d ", filter[i]);
    }
}

You can make your code look good by using loops or just use memcpy() to copy the whole array.

void FIR(short *filter)
{
   short temp[LENGTH];
   int i=0;
   for(i=0;i<LENGTH;i++)
   temp[i] = filter[i];
   // or memcpy(temp,filter,sizeof(short) * LENGTH);
}

Since you talk about efficiency then go for the latter approach ie memcpy()

The most efficient approach is likely a memcpy. Since you know the type and size of the array.

#define LENGTH 3
void FIR(short *filter) {
    short temp[LENGTH];
    memcpy(temp, filter, sizeof(short)*LENGTH)
}

You could use memcpy() , or you could initialize your local array in a loop. For example,

void FIR(short *filter) {
    short temp[LENGTH];
    memcpy(temp, filter, LENGTH * sizeof(short));
}

or

void FIR(short *filter) {
    short temp[LENGTH];
    int i;

    for (i = 0; i < LENGTH; i += 1) {
        temp[i] = filter[i];
    }
}

Other than memcopy() , one way is by using pointers:

void FIR(short *filter)
{
   short temp[LENGTH], *tempP;
   int i = 0;

   tempP = temp;
   while(LENGTH > i++) *tempP++ = *filter++;

}

If you want the length to be variable then use this

#include <stdio.h>

void FIR(short *filter, int length) {
    short *temp = new short[length];
    int i;
    for(i = 0; i < length; ++i){
        temp[i] = filter[i];
    }
}

int main() {
    short filter[3] = {1,2,5};
    FIR(filter, 3);
    int i;
    for(i = 0; i < 3; ++i){
        printf("%d ", filter[i]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM