2013-11-23 13 views
0

我期待做到以下幾點:(C)結構的數組和數據移動到它

結構DEF:

struct mystruct { 
    char cArr[500]; 
} 

全球:

struct mystruct **ptr; 
    int count = 0; 

ptr = malloc(20*sizeof(struct test *)); 
for (int i = 0; i != 20 ; i++) { 
    ptr[i] = malloc(sizeof(struct test)); 
} 

在某些被稱爲20次的函數中:

char burp[500]; 
//put whatever I want in burp; 
ptr[count]->cArr = burp //is this right? Or do I have to memcpy to it, and if so how? 
count++; 

所以在最後我會按順序用我想要的字符填充mystruct數組。我試圖用char **來做這件事,但沒有運氣;我現在將它包裝在一個結構體中,因爲它可以幫助我可視化發生的事情。

所以我想要一個char [500]全局數組,每次調用一個函數時,都會將該char [500]放入索引(即傳入函數或全局函數)。

任何意見是讚賞; Ofc我將需要在結束時釋放數組的每個索引。

謝謝!

編輯:

所以會是這樣的:那麼

memcpy(ptr[count]->cArr, burp, 500); 

工作?

+0

您應該執行'memcpy'。 – Rohan

+0

當'mystruct'沒有成員'field1'時,你不能'ptr [0] - > field1 = value;'請顯示真實的代碼! –

+0

對不起,我忘了擦除那一行;該代碼現在是正確的 –

回答

0

您可以使用strcpy來複制字符串。

strcpy(ptr[count]->cArr,burp); 

但strcpy終止於空字符。所以,確保你的字符串(即burp)被正確初始化。

1
#include <stdio.h> 

#include <stdlib.h> 

struct mystruct 

{ 
    char *cArr; 

    // U were trying to assign array using = operator 

    // Remember its not like in STL where u can perform deep copy of a vector  

}; 


struct mystruct **ptr; 


int count = 0; 


int main() 

{ int i; 

    ptr = malloc(20*sizeof(struct mystruct *)); 

    for (i = 0; i != 20 ; i++) 

{ 
    ptr[i] = malloc(sizeof(struct mystruct)); 

} 

    char burp[500]="No this is not correct boy."; 

    //put whatever I want in burp; 

    (*ptr+count)->cArr = burp ; 

    // Assigning pointer to a pointer , OK. Remember pointer != Array. 


    //is this right? Or do I have to memcpy to it, and if so how? 


    //count++; // Has no use in your code, enclose in a loop to then use it. 


    printf("%s\n",(*ptr + count)->cArr); // This works , I think. 


} 

對於數組,即焦卡爾[500],

如果你想使用memcpyü可以使用它:

的memcpy((* PTR +計數) - >卡爾,打嗝,500);

STRCPY也可以工作:

的strcpy((* PTR +計數) - >卡爾,打嗝);

有兩點非常重要:

  1. 指針的指針的分配是允許的,但陣列的深層副本是沒有的。

  2. ** ptr是一個雙指針。所以,(* ptr + count)或ptr [count]是一個指向struct的指針。

第二點不是你的答案所必需的。

0

我想你所要做的就是在你的結構中存儲一些文本以備後用。

struct mystruct { 
    char carr[500]; 
} 

struct mystruct *ptr = NULL; 
int count = 0; 

main{ 

    ... 
    ptr = malloc(20 * sizeof(struct test)); 
    //Function call func() 
    ... 
    //After performing work 
    free(ptr); 
} 

//Some function 
func() { 
    char burp[500]; 
    // burp has some data fed 
    memcpy(ptr[count]->carr, burp, 500); 
}