我想制作一個包含字串矩陣的結構。
像 |0|1|2|..|10 這個位置的每一個都應該有這樣的字串:hello, world, 1234, ...
我想添加字串,除非我得到限制(= SO_BLOCK_SIZE),所以我創建了一個函式來知道我已經添加了多少個字串。我收到了一些這樣的錯誤:
錯誤:數字常量前的預期宣告說明符或“...”#define SO_REGISTRY_SIZE 10
注意:在宏 'SO_REGISTRY_SIZE' char (*matrice)(SO_REGISTRY_SIZE) 的擴展中;
警告:結構或聯合結束時沒有分號
錯誤:'libroMastro' {aka 'struct libroMastro'} 沒有名為 'matrice' 的成員 if((libro->matrice[i][j]) == NULL)
這是我的代碼:
#include <stdio.h>
#include <stdlib.h>
#define BUF_SIZE 64
#define SO_REGISTRY_SIZE 10
#define SO_BLOCK_SIZE 5
typedef struct libroMastro{
char (*matrice)(SO_REGISTRY_SIZE);
}libroMastro;
int whatIndex(libroMastro *libro){
int i = 0;
int j = 0;
for(i; i < SO_REGISTRY_SIZE; i ){
for(j; j < SO_BLOCK_SIZE; j ){
if((libro->matrice[i][j]) == NULL)
return j;
}
}
return j;
}
int main(){
libroMastro *libro;
whatIndex(libro);
}
uj5u.com熱心網友回復:
您的代碼在許多地方無效。
我會這樣實作:
typedef struct libroMastro
{
size_t nmessages;
char *matrice[];
}libroMastro;
libroMastro *addString(libroMastro *lm, const char *str)
{
if(str)
{
size_t newsize = lm ? lm -> nmessages 1 : 1;
lm = realloc(lm, sizeof(*lm) newsize * sizeof(lm -> matrice[0]));
if(lm)
{
if((lm -> matrice[newsize - 1] = strdup(str)))
{
lm -> nmessages = newsize;
}
else
{
lm -> nmessages = newsize - 1;
}
}
}
return lm;
}
size_t how_many(libroMastro *lm)
{
if(lm) return lm -> nmessages;
}
int main(){
libroMastro *libro = NULL;
libro = addString(libro, "Hello");
libro = addString(libro, "World");
libro = addString(libro, "Next");
printf("Libro contains %zu strings\n", libro -> nmessages);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/371816.html
上一篇:此代碼段中指標的用途
下一篇:帶指標的字串陣列函式
