我已经编写了一个函数来在c中切片数组,但它返回的地址我认为。我曾经正确地工作过一次,但在某个地方搞砸了,任何帮助将不胜感激。

#include <stdio.h>
#include <stdlib.h>

int slice_array(int *input_array, int *sliced_array, int n){
    int i;
    for(i=0; i < n; i++) {
            sliced_array[i] = input_array[i];
    return 0;
    }
};

struct nbrs_ind {
    float value;
    int index;
};

//I also want to write a function which can slice the members of struct nbrs_ind (i.e. just slice first n indices nbrs_ind)

int main () {
    int k=4;
    int i;
    int a[7] = {1,2,3,4,6,5,7};
    int *ptr_a = a;
    int b[k];
    int *ptr_b = b;
    slice_array(a,b,k);
    for(i=0;i<k;i++) {
            printf("%d\t",b[i]);
    }
    printf("\n");
}



更新,切片数组工作正常,但到目前为止,我希望与struct相同,我已经编写了以下代码。我得到他以下错误:
 来自不兼容的指针类型的分配[默认启用]
  ptr_A =&A;

#include <stdio.h>
#include <stdlib.h>

//This function works fine in drivers program
void slice_array(int *input_array, int *sliced_array, int n){
    int i;
    for(i=0; i < n; i++) {
            sliced_array[i] = input_array[i];
    }
};

struct nbrs_ind {
    float value;
    int index;
};

//Need to make the slice of nbrs_ind struct using following function.
void slice_struct(struct nbrs_ind *input_struct, struct nbrs_ind   *sliced_struct, int n){
    int i;
    for(i=0; i < n; i++) {
            sliced_struct[i].index = input_struct[i].index;
            sliced_struct[i].value = input_struct[i].value;
    }
};

int main () {
    int k=3;
    int i;
    int a[7] = {1,2,3,4,6,5,7};
    float c[7] = {2.3,10,3,5,6.4,7.3,1};
    int *ptr_a = a;
    int b[k];
    int *ptr_b = b;

    struct nbrs_ind A[7]; // Declare 7 struct of nbrs_ind
    //Initilize the delare structs
    for (i=0;i<7;i++){
            A[i].index = i;
            A[i].value = c[i];
    }

    //How do I make a pointer to the struct so I can pass it to slice_struct function
    // I need to be able to do something like slice_struct(A,B,n);
    struct nbrs_ind *ptr_A ;
    ptr_A = &A;

    slice_array(a,b,k);
    for(i=0;i<k;i++) {
            printf("%d\t",b[i]);
    }
    printf("\n");
 }




最佳答案

#include <stdio.h>
#include <stdlib.h>

int slice_array(int *input_array, int *sliced_array, int n){
int i;
for(i=0; i < n; i++) {
        sliced_array[i] = input_array[i];
   }
  return 0;
};

struct nbrs_ind {
float value;
int index;
};

//I also want to write a function which can slice the members of struct nbrs_ind    (i.e. just slice first n indices nbrs_ind)

int main () {
int k=4;
int i;
int a[7] = {1,2,3,4,6,5,7};
int *ptr_a = a;
int b[k];
int *ptr_b = b;
slice_array(a,b,k);
for(i=0;i<k;i++) {
        printf("%d\t",b[i]);
}
printf("\n");


}

关于c - 在C中切片数组或结构的函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55671765/

10-09 04:53