[英]Passing dynamic array struct through function
struct aPoint {
int somaVertical;
int somaHorizontal;
int valor;
};
我有一個在main()中動態創建的結構數組,如下所示:
struct aPoint *ps = malloc( sizeof(struct aPoint) * columns * rows )
我想在具有sscanf()
的函數中使用main() 之外的struct值 。 數組的初始化也被在主照顧 ()。
如何通過該函數傳遞 結構數組並設置它的一些結構值 ? 唉,我討厭指針 !
謝謝!
那將是:
int readStuff(struct aPoint *ps, size_t len, const char *someVar)
{
unsigned int i;
for (i = 0; i < len; i++) {
sscanf(someVar, "%d", &(ps[i].somaVertical));
/* And so on for the other fields */
}
/* Return whatever you're returning here */
}
const size_t len = colunas * linhas;
struct aPoint *ps = calloc(len, sizeof(struct aPoint));
int success = readStuff(ps, len, arrayOfNumbers);
這適合我
/* #include <assert.h> */
#include <stdio.h>
#include <stdlib.h>
struct aPoint {
int somaVertical;
int somaHorizontal;
int valor;
};
int readStuff(struct aPoint *data, int rows, int cols) {
sscanf("42", "%d", &data[3].somaVertical);
sscanf("142", "%d", &data[3].somaHorizontal);
sscanf("-42", "%d", &data[3].valor);
return 0;
}
int main(void) {
struct aPoint *ps;
int colunas, linhas;
colunas = 80;
linhas = 25;
ps = malloc(sizeof *ps * colunas * linhas);
/* assert(ps); */ /* thanks Tim */
if (ps) {
readStuff(ps, linhas, colunas);
printf("%d %d %d\n", ps[3].somaVertical, ps[3].somaHorizontal, ps[3].valor);
free(ps);
} else {
fprintf(stderr, "no memory.\n");
exit(EXIT_FAILURE);
}
return 0;
}
C中的所有函數都是按值傳遞參數,因此您可以將指針傳遞給要修改的struct數組:
int readStuff(struct aPoint *p, int numStruct)
{
...
for(i=0; i<numStruct; i++)
{
sscanf(someVar, "%d", &(*(p+i).valor) );
}
...
}
你可以用以下方法調用此函數:
struct aPoint *ps = malloc( sizeof(struct aPoint) * columns * rows );
...
readStuff(ps, columns * rows);
我想你也需要
readStuff(ps);
...
sscanf(someVar, "%d", &(ps[index].valor)); // using index in readStuff
要么
readStuff(ps + index); // using index in main
...
sscanf(someVar, "%d", &(ps->valor)); // or &ps[0].valor, that's equivalent
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.