简体   繁体   English

声明要作为参数传递的临时结构-结构被覆盖。 如何在新的内存位置声明该结构?

[英]Declaring temporary struct to pass as argument — Struct gets written over. How do I declare the struct in a new memory location?

I am trying to initialize a new struct during each iteration of this loop to pass into a function; 我试图在此循环的每次迭代中初始化一个新结构,以传递给函数; the problem is that the same struct keeps being written over or reused (the memory address is the same). 问题是相同的结构会不断被覆盖或重复使用(内存地址相同)。 How do I declare a new structure that won't be overwritten so that I can pass the pointer to another function? 如何声明一个不会被覆盖的新结构,以便可以将指针传递给另一个函数?

while(dirs[i] != NULL){
    thread_arg narg;

If you want the data to have persistence beyond that iteration of your while loop whilst other iterations continue then you need to dynamically allocate, like this: 如果您希望数据在while循环的迭代之后具有持久性,而其他迭代仍在继续,则需要动态分配,如下所示:

while(dirs[i] != NULL){
    thread_arg * nargp = (thread_arg *) malloc(sizeof(thread_arg)); 

You have a pointer now instead of a value, but that's probably appropriate to your use (ie, you should be thinking of it as a pointer rather than a value probably). 现在,您有了一个指针而不是一个值,但这可能适合您的使用(即,您应该将其视为指针而不是值)。

You need to free the data when you have finished with it of course. 当然,您需要在处理完数据后释放它们。 Where/how you do that depends on your use case - you mention you are passing the data to another function, so if that function uses it and there's no other use, then one solution is that function could free it ( free(nargp) ) before returning. 您在何处/如何执行此操作取决于您的用例-您提到要将数据传递给另一个函数,因此,如果该函数使用了它而没有其他用途,那么一种解决方案是该函数可以释放它( free(nargp) )返回之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM