如何动态地将内存分配给结构数组 [英] How to assign memory dynamically to a array of structures

查看:91
本文介绍了如何动态地将内存分配给结构数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


我在将内存动态分配到阵列时遇到问题

结构。

假设我有一个结构


typedef struct hom_id {


int32_t nod_de;

int32_t hom_id;

int32_t hom_type;

int32_t hom_pid;

} hom_data;


我在程序中创建了一系列结构,所以我可以将

数据存储在数组中


hom_data arr [];


我想知道如何在
运行时将内存分配给这个结构数组。


这个代码有没有人指出这个问题。

我能够编译它但是它的打印垃圾值。


#include< stdio.h>

#include< stdint.h>

#include< string.h>

#include< sys / types.h>

#include< sys / stat.h>

#include< fcntl.h>

#include< unistd.h&g t;


typedef struct hom_id {


int32_t nod_de;

int32_t hom_id;

int32_t hom_type;

int32_t hom_pid;

} hom_data;


int main()

{

FILE * fout;


hom_data hom [30]; ---->如何为这个stuct数组分配内存

动态。

int i = 0;


/ *打开输入文件并测试它是否为空* /

if((fout = fopen(" momtext.txt"," r"))== NULL){

printf(" error ---- file read is空的\ n \\ nn \\;);

退出(1); }


/ *打开输出文件* /

fout = fopen(" momtext.txt"," r");

while(fscanf(fout,"%08x%08x",& hom [i] .nod_de,& hom [i] .hom_id)

!= 2)

{


fscanf(fout,"%08x%08x",& hom [i] .hom_type,& hom [i] .hom_pid);

printf("%08x%08x",hom [i] .nod_de,hom [i] .hom_id);

printf("%s%s %s \ n",hom [i] .hom_type,hom [i] .hom_pid);

i ++;


}

返回0;

}

提前致谢

解决方案

sk*******@gmail.com 说:


大家好,

我在将内存动态分配给数组时遇到问题

的结构。



#include< stdlib.h>

#include< stdio.h>


struct T

{

int this;

int class;

int teaches;

int dynamic;

int memory;

int allocation;

};


int main(void)

{

size_t capacity = 32;

size_t count = 0;

char line [256] = {0};


/ *从一开始就分配一堆结构* /

struct T * p = malloc(capacity * sizeof * p);

if(p!= NULL)

{

while(fgets(line,sizeof line,stdin)! = NULL)

{

if(count> = capacity)

{

struct T * new = realloc(p,capacity * 2 * sizeof * new);

if(new!= NULL)

{

p = new;

容量* = 2;

}

其他

{

/ *取一些一种纠正措施,或简单地...... * /

fprintf(stderr,

无法分配足够的内存

" for%lu items.\ n,

(无符号长)容量* 2);

退出(EXIT_FAILURE);

}

}

if(sscanf(line,

"%d%d%d%d%d%d",

& p [count] .this,

& p [count] .class,

& p [count] .teaches,

& p [count] .dynamic,

& p [count] .memory,

& p [count] .allocation)!= 6)

{

fprintf(stderr,

输入错误在线%lu \ n,

(unsigned long)count);

退出(EXIT_FAILURE);

}

++ count;

}


/ *以倒序显示总和* /

而(count-- 0)

{

int sum = p [count] .this;

sum + = p [count] .class;

sum + = p [count] .teaches ;

sum + = p [count] .dynamic;

sum + = p [count] .memory;

sum + = p [计数]。分配;

printf("%d \ n",sum);

}


fr ee(p);

}

其他

{

fprintf(stderr,不能分配记忆\ n");

}

返回0;

}


- -

Richard Heathfield

Usenet是一个奇怪的地方 - dmr 29/7/1999
http://www.cpax.org.uk

电子邮件:rjh在上面的域名(但显然放弃了www)


sk ******* @ gmail.com 写道:


我正面临着问题同时将内存动态分配给一个数组

的结构。



这看起来非常熟悉。你有没有开始其他几个线程

关于同样的问题?为什么不在原来的

线程中发布后续内容?


假设我有一个结构


typedef struct hom_id {


int32_t nod_de;

int32_t hom_id;

int32_t hom_type;

int32_t hom_pid;

} hom_data;



您的struct标签hom_id与您的某个struct

成员的名称相同。这是合法但令人困惑的。


如果你坚持为你的结构使用typedef,并且它没有
包含任何指向同一类型的指针,你实际上并不需要

标签:


typedef struct {

/ * members * /

} hom_data;


或者你可以为struct标签和typedef使用相同的标识符:


typedef struct hom_data {

/ *会员* /

} hom_data;


就个人而言,我会删除typedef而只是参考类型为struct

hom_data,但很多人喜欢typedef由于各种原因。


我创建了一系列结构我的程序,以便我可以将

数据存储在数组中


hom_data arr [];


我想要知道如何在
运行时将内存分配给这个结构数组。


任何人都可以指出这是错误的代码。

我能够编译它但是它的打印垃圾值。


#include< stdio.h>

# include< stdint.h>

#include< string.h>



好​​的。


#include< sys / types.h>

#include< sys / stat.h>

#include< fcntl.h>

#include< unistd.h>



这些最后4个标题未在标准C中定义;他们是

特定于Unix的。如果你真的使用了他们的任何东西,我会告诉你

来试试comp.unix.programmer。但据我所知,你不是,所以

你可以删除它们(至少在你发布的代码中)。


typedef struct hom_id {


int32_t nod_de;

int32_t hom_id;

int32_t hom_type;

int32_t hom_pid;

} hom_data;


int main()



更好:

int main(无效)


{

FILE * fout;


hom_data hom [30]; ---->如何动态地为这个stuct数组分配内存



int i = 0;


/ *打开输入文件并测试它是否为空* /

if((fout = fopen(" momtext.txt"," r" ;))== NULL){

printf(错误----文件读取为空\ n \\ nn);

退出(1) ; }



exit()在< stdlib.h>中声明;你需要一个#include。如果您的

编译器没有警告您,请调高警告级别。


exit(1)是不可移植的。使用exit(EXIT_FAILURE)。


>

/ *打开输出文件* /

fout = fopen(" momtext.txt" ;,r);



什么?你刚打开这个文件(并检查了fopen()的结果;

对你有好处)。现在你再次打开阅读,但你的意见

说打开输出文件,你不会检查结果。


和为什么你称它为fout当它被用于输入时?


while(fscanf(fout,"%08x%08x",& hom [i] .nod_de,& ; hom [i] .hom_id)

!= 2)

{


fscanf(fout,"%08x% 08x",& hom [i] .hom_type,& hom [i] .hom_pid);



您检查了第一个fscanf()的结果,但没有检查第二个结果。

始终检查fscanf()的结果。我想你假设在那里

输入文件中没有错误;这是一个危险的假设。


也许你应该用一个fcanf()来读取所有4个值。


(我'' d使用fgets()后跟sscanf();直接使用fscanf()应该

工作,但它在处理

错误时没有给你太大的灵活性。 )


printf("%08x%08x",hom [i] .nod_de,hom [i] .hom_id);



%08x fscanf()和printf()的格式指定一个参数

类型unsigned int(或指向fscanf()的unsigned int指针。

你正在使用类型为int32_t的参数,可能是也可能不是

相同的类型。 < inttypes.h提供int32_t的格式说明符,但是

它很笨重。对于输出,请使用%08lx;并将参数转换为

unsigned long。对于输入,您可以读取类型为

unsigned long的临时值,然后分配给您的uint32_t成员。


printf("%s %s%s \ n",hom [i] .hom_type,hom [i] .hom_pid);



你告诉printf你要给它三个char *参数指向

到字符串,然后你给它两个int32_t参数。当然你是
得到垃圾。


i ++;


}

返回0;


}



你真正的问题是关于如何动态分配数组

结构,当你需要的结构数量依赖于输入文件上的
时(即你事先不知道)。


您可以使用malloc()来分配数组,然后使用realloc()

根据需要增长它(并且*总是*检查两者返回的值

函数),或者你可以使用malloc()一次分配一条记录,并将
添加到一个链表中。 (后者不是一个阵列,这是你要求的,但它可能适合你的目的。如果没有,你

也可以建立链表,一旦你知道它有多大了

可以使用一个malloc()来分配一个数组并将链接的

列表元素复制到其中。这确实会增加你的内存要求,

虽然。)


但是对于初稿,你可能只是声明一个固定大小的数组

并将值存储到其中,跟踪使用的元素数量是多少。如果输入太大,这将失败,但实现起来应该更容易实现,并且它将使您有机会修复代码中的所有其他

错误在你开始担心内存分配之前。


-

Keith Thompson(The_Other_Keith) ks *** @ mib.org < http://www.ghoti.net/~kst>

圣地亚哥超级计算机中心< *< http:// users.sdsc.edu/~kst>

我们必须做点什么。这是事情。因此,我们必须这样做。


你好,

根据你的建议,我写了这段代码。我在这里复制每个

从文件行到一个结构。并将它传递给一个函数,

创建一个链表并将值存储在其中。


现在问题是我得到了一个segmentatin错误错误,我认为它是在addnode_hom()中加入的
;功能。


-我无法解决问题。

- >是因为我想使用相同的结构来创建链接

列出并将数据传递给函数。


-我很好但没有得到解决方案。


-你可以帮我吗

#include< stdio.h>

#include< stdint.h>

#include< string.h>

#include< stdint.h>

#include< stdlib.h>


typedef struct {

int32_t hom_node;

int32_t hom_id;

int32_t hom_rest;

int32_t hom_type;

struct hom_id * link;

} hom_data;


int addnode_hom(hom_data * homptr);

void printnode_data( hom_data * h_ptr);

int count(hom_data * h_ptr);


int main(无效)

{

FILE * fp;

int count = 0;

int ret;

char buff [1024];

hom_data * homptr;

homptr =(struct hom_data *)malloc(sizeof(hom_data));

// printf(" test_main1 \ n");

fp = popen(" grep 0044 momtext.txt"," r");

// printf(" test_main\\\
");

while(fgets(buff,sizeof(buff),fp)!= NULL){

fscanf(fp,"%08x%08x%04x%08x"& homptr-> hom_node,

& homptr-> hom_id,

& homptr-> hom_rest,

& homptr-> hom_type);

ret = addnode_hom(homptr);

if(ret == 0)

{

printf("错误\ n");

退出(1);

}

else {

/ * printf ("%08x%08x%04x%08x \ n",homptr-> hom_node,

homptr-> hom_id,

homptr-> hom_rest,

homptr-> hom_type); * /

count ++;

}

printf("%d \ n",count);

免费(homptr);

pclose(fp);

返回0;

}

}


void printnode_data(hom_data * h_ptr){

// printf(" test_print \ n");

if(h_ptr == NULL){

printf(flie is empty);


}

else {


printf("%08x%08x%04x%08x \ n",h_ptr-> hom_node,

h_ptr-> ; hom_id,

h_ptr-> hom_rest,

h_ptr-> hom_rest,

h_ptr-> hom_type);

printf(" \ n");

}


}

int addnode_hom(hom_data * homptr ){


hom_data * h_ptr,* current,* new;

int ctr;

ctr = count(h_ptr);

if(ctr == 0){

h_ptr =(struct hom_data *)malloc(sizeof(hom_data));

if(h_ptr == NULL){

printf(" error");}

memset(h_ptr,0,sizeof(hom_data));

// current = h_ptr;


h_ptr-> hom_node = homptr-> hom_node;

h_ptr-> hom_id = homptr-> ho m_id;

h_ptr-> hom_rest = homptr-> hom_rest;

h_ptr-> hom_type = homptr-> hom_type;

h_ptr-> link = NULL;

}

else {

current =(struct hom_data)malloc(sizeof(hom_data));

current = h_ptr;

while(current-> link!= NULL)

current = current-> link;

}

new =(struct hom_data *)malloc(sizeof(hom_data));

memset(当前,0,sizeof(hom_data));

current-> link = new;

new-> hom_node = homptr-> hom_node;

new-> hom_id = homptr- > hom_id;

new-> hom_rest = homptr-> hom_rest;

new-> hom_type = homptr-> hom_type;

new-> link = NULL;

current = new;

printnode_data(current);


}


int count(hom_data * h_ptr)

{

int ctr = 0;

while(h_ptr - > link!= NULL)

{

h_ptr = h_ptr-> link;

ctr ++;

}

返回ctr;

}


Keith Thompson写道:

sk*******@gmail.com 写道:
< blockquote class =post_quotes>
我在将内存动态分配给数组时面临问题

的结构。



这看起来非常熟悉。你有没有开始其他几个线程

关于同样的问题?为什么不在原来的

线程中发布后续内容?


假设我有一个结构


typedef struct hom_id {


int32_t nod_de;

int32_t hom_id;

int32_t hom_type;

int32_t hom_pid;

} hom_data;



你的struct标签hom_id与您的某个struct

成员的名称相同。这是合法但令人困惑的。


如果你坚持为你的结构使用typedef,并且它没有
包含任何指向同一类型的指针,你实际上并不需要

标签:


typedef struct {

/ * members * /

} hom_data;


或者你可以为struct标签和typedef使用相同的标识符:


typedef struct hom_data {

/ *会员* /

} hom_data;


就个人而言,我会删除typedef而只是参考类型为struct

hom_data,但很多人喜欢typedef由于各种原因。


我创建了一系列结构我的程序,以便我可以将

数据存储在数组中


hom_data arr [];


我想要知道如何在
运行时将内存分配给这个结构数组。


可以nybody point waht这个代码有问题。

我能够编译它但是它的打印垃圾值。


#include< stdio.h>

#include< stdint.h>

#include< string.h>



好​​的。


#include< sys / types.h>

#include< sys / stat.h>

#include< fcntl.h>

#include< unistd.h>



这些最后4个标题未在标准C中定义;他们是

特定于Unix的。如果你真的使用了他们的任何东西,我会告诉你

来试试comp.unix.programmer。但据我所知,你不是,所以

你可以删除它们(至少在你发布的代码中)。


typedef struct hom_id {


int32_t nod_de;

int32_t hom_id;

int32_t hom_type;

int32_t hom_pid;

} hom_data;


int main()



更好:

int main(无效)


{

FILE * fout;


hom_data hom [30]; ---->如何动态地为这个stuct数组分配内存



int i = 0;


/ *打开输入文件并测试它是否为空* /

if((fout = fopen(" momtext.txt"," r" ;))== NULL){

printf(错误----文件读取为空\ n \\ nn);

退出(1) ; }



exit()在< stdlib.h>中声明;你需要一个#include。如果您的

编译器没有警告您,请调高警告级别。


exit(1)是不可移植的。使用exit(EXIT_FAILURE)。



/ *打开输出文件* /

fout = fopen(" momtext.txt"," r" );



什么?你刚打开这个文件(并检查了fopen()的结果;

对你有好处)。现在你再次打开阅读,但你的意见

说打开输出文件,你不会检查结果。


和为什么你称它为fout当它被用于输入时?


while(fscanf(fout,"%08x%08x",& hom [i] .nod_de,& ; hom [i] .hom_id)

!= 2)

{


fscanf(fout,"%08x% 08x",& hom [i] .hom_type,& hom [i] .hom_pid);



您检查了第一个fscanf()的结果,但没有检查第二个结果。

始终检查fscanf()的结果。我想你假设在那里

输入文件中没有错误;这是一个危险的假设。


也许你应该用一个fcanf()来读取所有4个值。


(我'' d使用fgets()后跟sscanf();直接使用fscanf()应该

工作,但它在处理

错误时没有给你太大的灵活性。 )


printf("%08x%08x",hom [i] .nod_de,hom [i] .hom_id);



%08x fscanf()和printf()的格式指定一个参数

类型unsigned int(或指向fscanf()的unsigned int指针。

你正在使用类型为int32_t的参数,可能是也可能不是

相同的类型。 < inttypes.h提供int32_t的格式说明符,但是

它很笨重。对于输出,请使用%08lx;并将参数转换为

unsigned long。对于输入,您可以读取类型为

unsigned long的临时值,然后分配给您的uint32_t成员。


printf("%s %s%s \ n",hom [i] .hom_type,hom [i] .hom_pid);



你告诉printf你要给它三个char *参数指向

到字符串,然后你给它两个int32_t参数。当然你是
得到垃圾。


i ++;


}

返回0;

}



你真正的问题是关于如何动态分配数组

结构,当你需要的结构数量依赖于输入文件上的
时(即你事先不知道)。


您可以使用malloc()分配一个数组,然后使用realloc()

根据需要增长它(并且*总是*检查两者返回的值

函数),或者您可以使用malloc()一次分配一条记录,并将
添加到链表中。 (后者不是一个阵列,这是你要求的,但它可能适合你的目的。如果没有,你

也可以建立链表,一旦你知道它有多大了

可以使用一个malloc()来分配一个数组并将链接的

列表元素复制到其中。这确实会增加你的内存要求,

虽然。)


但是对于初稿,你可能只是声明一个固定大小的数组

并将值存储到其中,跟踪使用的元素数量是多少。如果输入太大,这将失败,但实现起来应该更容易实现,并且它将使您有机会修复代码中的所有其他

错误在你开始担心内存分配之前。


-

Keith Thompson(The_Other_Keith) ks *** @ mib.org < http://www.ghoti.net/~kst>

圣地亚哥超级计算机中心< *< http:// users.sdsc.edu/~kst>

我们必须做点什么。这是事情。因此,我们必须这样做。


Hi everybody,

I am faceing problem while assigning the memory dynamically to a array
of structures .
Suppose I have a structure

typedef struct hom_id{

int32_t nod_de;
int32_t hom_id;
int32_t hom_type;
int32_t hom_pid;
} hom_data;

I created array of structures in my program so that i can store the
data in array

hom_data arr[];

I want to know how to assign memory to this array of structure at
runtime.

Can anybody point waht is wrong with this code .
I able to compile it but its printing garbage values.

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

typedef struct hom_id{

int32_t nod_de;
int32_t hom_id;
int32_t hom_type;
int32_t hom_pid;
} hom_data;

int main()
{
FILE *fout;

hom_data hom[30];---->how to allocate memory to this array of stuct
dynamically.
int i=0;

/* open input file and test to see if it is empty */
if ((fout = fopen("momtext.txt", "r")) == NULL) {
printf("error ---- file read is empty\n\n");
exit(1); }

/* open output file */
fout = fopen("momtext.txt", "r");
while (fscanf (fout ,"%08x %08x ", &hom[i].nod_de, &hom[i].hom_id)
!= 2)
{

fscanf(fout ,"%08x %08x", &hom[i].hom_type, &hom[i].hom_pid );
printf("%08x %08x ", hom[i].nod_de, hom[i].hom_id);
printf("%s %s %s\n", hom[i].hom_type, hom[i].hom_pid);
i++;

}
return 0;
}
Thanks in advance

解决方案

sk*******@gmail.com said:

Hi everybody,

I am faceing problem while assigning the memory dynamically to a array
of structures .

#include <stdlib.h>
#include <stdio.h>

struct T
{
int this;
int class;
int teaches;
int dynamic;
int memory;
int allocation;
};

int main(void)
{
size_t capacity = 32;
size_t count = 0;
char line[256] = {0};

/* allocate a bunch of structs to start off with */
struct T *p = malloc(capacity * sizeof *p);
if(p != NULL)
{
while(fgets(line, sizeof line, stdin) != NULL)
{
if(count >= capacity)
{
struct T *new = realloc(p, capacity * 2 * sizeof *new);
if(new != NULL)
{
p = new;
capacity *= 2;
}
else
{
/* take some kind of corrective action, or simply... */
fprintf(stderr,
"Couldn''t allocate sufficient memory"
" for %lu items.\n",
(unsigned long)capacity * 2);
exit(EXIT_FAILURE);
}
}
if(sscanf(line,
"%d %d %d %d %d %d",
&p[count].this,
&p[count].class,
&p[count].teaches,
&p[count].dynamic,
&p[count].memory,
&p[count].allocation) != 6)
{
fprintf(stderr,
"Input error on line %lu\n",
(unsigned long)count);
exit(EXIT_FAILURE);
}
++count;
}

/* display sums in reverse order */
while(count-- 0)
{
int sum = p[count].this;
sum += p[count].class;
sum += p[count].teaches;
sum += p[count].dynamic;
sum += p[count].memory;
sum += p[count].allocation;
printf("%d\n", sum);
}

free(p);
}
else
{
fprintf(stderr, "Couldn''t allocate memory\n");
}
return 0;
}

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)


sk*******@gmail.com writes:

I am faceing problem while assigning the memory dynamically to a array
of structures .

This look awfully familiar. Haven''t you started several other threads
about this same problem? Why not just post a followup in the original
thread?

Suppose I have a structure

typedef struct hom_id{

int32_t nod_de;
int32_t hom_id;
int32_t hom_type;
int32_t hom_pid;
} hom_data;

Your struct tag "hom_id" is the same as the name of one of your struct
members. This is legal but confusing.

If you insist on using a typedef for your structure, and it doesn''t
contain any pointers to the same type, you don''t actually need the
tag:

typedef struct {
/* members */
} hom_data;

Or you can use the same identifier for the struct tag and the typedef:

typedef struct hom_data {
/* members */
} hom_data;

Personally, I''d drop the typedef and just refer to the type as "struct
hom_data", but a lot of people like typedefs for various reasons.

I created array of structures in my program so that i can store the
data in array

hom_data arr[];

I want to know how to assign memory to this array of structure at
runtime.

Can anybody point waht is wrong with this code .
I able to compile it but its printing garbage values.

#include <stdio.h>
#include <stdint.h>
#include <string.h>

Ok.

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

These last 4 headers are not defined in standard C; they''re
Unix-specific. If you actually used anything from them, I''d tell you
to try comp.unix.programmer. But as far as I can tell you''re not, so
you can just delete them (at least in code you post here).

typedef struct hom_id{

int32_t nod_de;
int32_t hom_id;
int32_t hom_type;
int32_t hom_pid;
} hom_data;

int main()

Better:
int main(void)

{
FILE *fout;

hom_data hom[30];---->how to allocate memory to this array of stuct
dynamically.
int i=0;

/* open input file and test to see if it is empty */
if ((fout = fopen("momtext.txt", "r")) == NULL) {
printf("error ---- file read is empty\n\n");
exit(1); }

exit() is declared in <stdlib.h>; you need a #include for it. If your
compiler didn''t warn you about that, turn up the warning level.

exit(1) is non-portable. Use exit(EXIT_FAILURE).

>
/* open output file */
fout = fopen("momtext.txt", "r");

What? You just opened this file (and checked the result of fopen();
good for you). Now you open it again for reading, but your commment
says "open output file", and you don''t check the result.

And why do you call it "fout" when it''s used for input?

while (fscanf (fout ,"%08x %08x ", &hom[i].nod_de, &hom[i].hom_id)
!= 2)
{

fscanf(fout ,"%08x %08x", &hom[i].hom_type, &hom[i].hom_pid );

You checked the result of the first fscanf(), but not the second.
Always check the result of fscanf(). I think you''re assuming there
will be no errors in your input file; that''s a dangerous assumption.

Maybe you should use a single fcanf() to read all 4 value.

(I''d use fgets() followed by sscanf(); use fscanf() directly should
work, but it doesn''t give you much flexibility in dealing with
errors.)

printf("%08x %08x ", hom[i].nod_de, hom[i].hom_id);

The "%08x" format for both fscanf() and printf() specifies an argument
of type unsigned int (or pointer to unsigned int for fscanf()).
You''re using arguments of type int32_t, which may or may not be the
same type. <inttypes.hprovides format specifiers for int32_t, but
it''s unwieldy. For output, use "%08lx" and cast the arguments to
unsigned long. For input, you can read into temporaries of type
unsigned long and then assign to your uint32_t members.

printf("%s %s %s\n", hom[i].hom_type, hom[i].hom_pid);

You tell printf you''re going to give it three char* arguments pointing
to strings, then you give it two int32_t arguments. Of course you''re
getting garbage.

i++;

}
return 0;
}

Your real question was about how to dynamically allocate an array of
structures, when the number of structures you need is going to depend
on an input file (i.e., you don''t know in advance).

You can either use malloc() to allocate an array, then use realloc()
to grow it as needed (and *always* check the value returned by both
functions), or you can use malloc() allocate one record at a time and
add each one to a linked list. (The latter isn''t an array, which is
what you asked for, but it might suit your purposes. If not, you
could also build the linked list, then once you know how big it is you
can use a single malloc() to allocate an array and copy the linked
list elements into it. This does increase your memory requirements,
though.)

For a first draft, though, you might just declare a fixed-size array
and store values into it, keeping track of how many elements are being
used. This will fail if the input is too big, but it should be easier
to implement, and it will give you a chance to fix all the other
errors in your code before you start worrying about memory allocation.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.


Hi there,
As per your suggestion i wrote this code .Here i am tring to copy each
line from the file into a structure .And passing it to a function which
creates a linked list and stores the values in it.

Now the problem is i am getting a segmentatin fault error , I think its
comming in the addnode_hom(); function.

-I am not able to rectify the problem .
->Is due to that i am tring to use same structure for creating a linked
list and passing the data to the function.

-I am tring but not getting the solution.

-can u help me
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>

typedef struct {
int32_t hom_node;
int32_t hom_id;
int32_t hom_rest;
int32_t hom_type;
struct hom_id *link;
}hom_data;

int addnode_hom (hom_data *homptr);
void printnode_data (hom_data *h_ptr);
int count(hom_data *h_ptr);

int main(void)
{
FILE *fp;
int count = 0;
int ret;
char buff[1024];
hom_data *homptr;
homptr = (struct hom_data *) malloc(sizeof(hom_data));
//printf("test_main1\n");
fp = popen("grep 0044 momtext.txt","r");
//printf("test_main\n");
while(fgets(buff,sizeof(buff),fp)!=NULL){
fscanf(fp,"%08x %08x %04x %08x",&homptr->hom_node,
&homptr->hom_id,
&homptr->hom_rest,
&homptr->hom_type);
ret = addnode_hom(homptr);
if(ret == 0)
{
printf("error\n");
exit(1);
}
else {
/*printf("%08x %08x %04x %08x\n",homptr->hom_node,
homptr->hom_id,
homptr->hom_rest,
homptr->hom_type);*/
count++;
}
printf("%d\n",count);
free(homptr);
pclose(fp);
return 0;
}
}

void printnode_data (hom_data *h_ptr) {
//printf("test_print\n");
if(h_ptr == NULL){
printf("flie is empty ");

}
else{

printf("%08x %08x %04x %08x\n",h_ptr->hom_node,
h_ptr->hom_id,
h_ptr->hom_rest,
h_ptr->hom_rest,
h_ptr->hom_type);
printf ("\n");
}

}
int addnode_hom (hom_data * homptr){

hom_data *h_ptr,*current,*new;
int ctr;
ctr=count(h_ptr);
if(ctr == 0){
h_ptr = (struct hom_data *) malloc (sizeof(hom_data));
if(h_ptr == NULL){
printf("error");}
memset(h_ptr, 0, sizeof(hom_data));
//current = h_ptr;

h_ptr->hom_node = homptr->hom_node;
h_ptr->hom_id = homptr->hom_id;
h_ptr->hom_rest = homptr->hom_rest;
h_ptr->hom_type = homptr->hom_type;
h_ptr->link = NULL;
}
else{
current = (struct hom_data)malloc(sizeof(hom_data));
current = h_ptr;
while(current->link != NULL)
current=current->link;
}
new=(struct hom_data *)malloc(sizeof(hom_data));
memset(current,0,sizeof(hom_data));
current->link=new;
new->hom_node = homptr->hom_node;
new->hom_id = homptr->hom_id;
new->hom_rest = homptr->hom_rest;
new->hom_type = homptr->hom_type;
new->link = NULL;
current=new;
printnode_data(current);

}

int count(hom_data *h_ptr)
{
int ctr=0;
while(h_ptr->link != NULL)
{
h_ptr = h_ptr->link;
ctr++;
}
return ctr;
}

Keith Thompson wrote:

sk*******@gmail.com writes:

I am faceing problem while assigning the memory dynamically to a array
of structures .


This look awfully familiar. Haven''t you started several other threads
about this same problem? Why not just post a followup in the original
thread?

Suppose I have a structure

typedef struct hom_id{

int32_t nod_de;
int32_t hom_id;
int32_t hom_type;
int32_t hom_pid;
} hom_data;


Your struct tag "hom_id" is the same as the name of one of your struct
members. This is legal but confusing.

If you insist on using a typedef for your structure, and it doesn''t
contain any pointers to the same type, you don''t actually need the
tag:

typedef struct {
/* members */
} hom_data;

Or you can use the same identifier for the struct tag and the typedef:

typedef struct hom_data {
/* members */
} hom_data;

Personally, I''d drop the typedef and just refer to the type as "struct
hom_data", but a lot of people like typedefs for various reasons.

I created array of structures in my program so that i can store the
data in array

hom_data arr[];

I want to know how to assign memory to this array of structure at
runtime.

Can anybody point waht is wrong with this code .
I able to compile it but its printing garbage values.

#include <stdio.h>
#include <stdint.h>
#include <string.h>


Ok.

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>


These last 4 headers are not defined in standard C; they''re
Unix-specific. If you actually used anything from them, I''d tell you
to try comp.unix.programmer. But as far as I can tell you''re not, so
you can just delete them (at least in code you post here).

typedef struct hom_id{

int32_t nod_de;
int32_t hom_id;
int32_t hom_type;
int32_t hom_pid;
} hom_data;

int main()


Better:
int main(void)

{
FILE *fout;

hom_data hom[30];---->how to allocate memory to this array of stuct
dynamically.
int i=0;

/* open input file and test to see if it is empty */
if ((fout = fopen("momtext.txt", "r")) == NULL) {
printf("error ---- file read is empty\n\n");
exit(1); }


exit() is declared in <stdlib.h>; you need a #include for it. If your
compiler didn''t warn you about that, turn up the warning level.

exit(1) is non-portable. Use exit(EXIT_FAILURE).


/* open output file */
fout = fopen("momtext.txt", "r");


What? You just opened this file (and checked the result of fopen();
good for you). Now you open it again for reading, but your commment
says "open output file", and you don''t check the result.

And why do you call it "fout" when it''s used for input?

while (fscanf (fout ,"%08x %08x ", &hom[i].nod_de, &hom[i].hom_id)
!= 2)
{

fscanf(fout ,"%08x %08x", &hom[i].hom_type, &hom[i].hom_pid );


You checked the result of the first fscanf(), but not the second.
Always check the result of fscanf(). I think you''re assuming there
will be no errors in your input file; that''s a dangerous assumption.

Maybe you should use a single fcanf() to read all 4 value.

(I''d use fgets() followed by sscanf(); use fscanf() directly should
work, but it doesn''t give you much flexibility in dealing with
errors.)

printf("%08x %08x ", hom[i].nod_de, hom[i].hom_id);


The "%08x" format for both fscanf() and printf() specifies an argument
of type unsigned int (or pointer to unsigned int for fscanf()).
You''re using arguments of type int32_t, which may or may not be the
same type. <inttypes.hprovides format specifiers for int32_t, but
it''s unwieldy. For output, use "%08lx" and cast the arguments to
unsigned long. For input, you can read into temporaries of type
unsigned long and then assign to your uint32_t members.

printf("%s %s %s\n", hom[i].hom_type, hom[i].hom_pid);


You tell printf you''re going to give it three char* arguments pointing
to strings, then you give it two int32_t arguments. Of course you''re
getting garbage.

i++;

}
return 0;
}


Your real question was about how to dynamically allocate an array of
structures, when the number of structures you need is going to depend
on an input file (i.e., you don''t know in advance).

You can either use malloc() to allocate an array, then use realloc()
to grow it as needed (and *always* check the value returned by both
functions), or you can use malloc() allocate one record at a time and
add each one to a linked list. (The latter isn''t an array, which is
what you asked for, but it might suit your purposes. If not, you
could also build the linked list, then once you know how big it is you
can use a single malloc() to allocate an array and copy the linked
list elements into it. This does increase your memory requirements,
though.)

For a first draft, though, you might just declare a fixed-size array
and store values into it, keeping track of how many elements are being
used. This will fail if the input is too big, but it should be easier
to implement, and it will give you a chance to fix all the other
errors in your code before you start worrying about memory allocation.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.


这篇关于如何动态地将内存分配给结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆