gpt4 book ai didi

c - 在c中切片数组或结构的函数

转载 作者:行者123 更新时间:2023-11-30 16:19:14 25 4
gpt4 key购买 nike

我已经编写了一个函数来在 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");
}

~
更新,切片数组工作正常,但我想与结构相同,到目前为止我已经编写了以下代码。我收到以下错误: 来自不兼容指针类型的赋值[默认启用] 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com