Malloc,结构帮助 [英] Malloc, Structure Help

查看:93
本文介绍了Malloc,结构帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我正在制作一个快速程序,用一个

文本文件将圣经带进记忆中。无论如何,我有三个问题要问。


首先,我的程序中malloc()的实现是否正确

跟随?


其次,我是否正确地将结构的指针传递给了这个程序中的

函数?


最后,怎么做我在

给定函数中初始化结构变量?


这是'程序:


* ---------------------------------------- *


#include< stdio.h>

#include< stdlib.h>


struct bibtxt

{

char book [32];

int chapter;

int verse;

char text [500 ];

};


typedef struct bibtxt BIBLE;


void fillverse(BIBLE * pverse);


int main(无效)

{

BIBLE * pverse;

int x;


pverse = malloc(1000 * sizeof(BIBLE));

if(pverse == NULL)

{

printf(它没有工作。\ n);

返回-1;

}


printf(" pverse =%d \ n",(sizeof(BIBLE)* 1000));


为(x = 0; x< 1000; x ++)

fillverse(pverse);


for(x = 0; x< 1000; x ++)

printverse( pverse);


免费(pverse);


返回0;

}


void fillverse(BIBLE * pverse)

{

int x,y;


for(x = 0; x <1000; x ++)

for(y = 0; y <500; y ++)

{

printf( "%s \ n",pverse.text);

pverse.text [y] =''\ 0'';

}

}


* -------------------------------- -------- *


我知道在函数fillverse中,我有pverse.text [y]

错了。我已经玩了好几个小时试图找到

正确的方式来做我想做的事。


请给我任何关于风格的建议或者你认为可能的任何建议

合适。


谢谢!

-M。

Hi all,
I''m working on a quick program to bring the Bible into memory from a
text file. Anyway, I have three questions to ask.

First, is my implementation of malloc () correct in the program to
follow?

Second, have I correctly passed the structure''s pointer to the
functions in this program?

Last, how do I go about initializing the structure variables in the
given function?

Here''s the program:

*----------------------------------------*

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

struct bibtxt
{
char book[32];
int chapter;
int verse;
char text[500];
};

typedef struct bibtxt BIBLE;

void fillverse (BIBLE *pverse);

int main (void)
{
BIBLE *pverse;
int x;

pverse = malloc (1000 * sizeof (BIBLE));
if (pverse == NULL)
{
printf ("It didn''t work.\n");
return -1;
}

printf ("pverse = %d\n", (sizeof (BIBLE) * 1000));

for (x = 0; x < 1000; x++)
fillverse (pverse);

for (x = 0; x < 1000; x++)
printverse (pverse);

free (pverse);

return 0;
}

void fillverse (BIBLE *pverse)
{
int x, y;

for (x = 0; x < 1000; x++)
for (y = 0; y < 500; y++)
{
printf ("%s\n", pverse.text);
pverse.text[y] = ''\0'';
}
}

*----------------------------------------*

I know that in the function fillverse, that I have the pverse.text[y]
wrong. I''ve been playing with this for several hours trying to find the
right way to do what I''m wanting to do with this.

Please give my any advice on style or whatever you think may be
appropriate.

Thanks!
-M.

推荐答案

2004年4月10日星期六11:08:29 -0500,Mannequin *< ma ******* @ primary.net>

写道:
On Sat, 10 Apr 2004 11:08:29 -0500, Mannequin* <ma*******@primary.net>
wrote:
大家好,
我正在制定一个快速的程序,将圣经带入记忆中。
文本文件。无论如何,我有三个问题要问。

首先,我的程序中的malloc()的实现是否正确?

第二,我是否正确将结构的指针传递给了这个程序中的
函数?

最后,我如何在
给定函数中初始化结构变量?


不要直接回答问题,请允许我评论

代码en passant。你已经在这里做了一些设计决定,你可能需要重新考虑



这是程序:

* - -------------------------------------- *

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

struct bibtxt
{char book [32];
int chapter;
int verse;
char text [500];


就在这里,看起来文本数组应该代表一节经文。

而不是有一个最坏的情况。固定大小,你做得好得多

这是一个指向char的指针并动态处理分配。额外的

复杂性需要的是内存效率的总体增加。我不会展示全部的变化

这会带来什么,但我会试着点击亮点。对于初学者,将上面的内容更改为:

char * text;};

typedef struct bibtxt BIBLE;

void fillverse(BIBLE * pverse);

int main(void)
{BIBLE * pverse;
int x;

pverse = malloc(1000 * sizeof(BIBLE));


这个值''1000''(以及希望即将退休的''500'')

渗透你的代码。我们不情愿地将此称为幻数

,最好将其表示为符号常量。在C中,如果将

用作数组维度,那么你几乎不得不使用

#define''d符号,但这样更好而不是乱丢1000的代码。


你们组织中的另一个严重缺陷就是你在整个1000年内迭代

你的诗歌数组的元素范围无论多少实际上已经加载了多少数据(实际上你似乎并没有从这里找到任何代码中的
) )。在这样的情况下你想要做什么是

检查你已装载多少(如果有的话),记住这个值,并将其用作

的限制那些迭代数据的循环。使用像

这样的版本的fillverse()我会在下面给你看,你会在你的代码部分中管理那种实际上是b / b
的东西调用fillverse。

if(pverse == NULL)
{
printf(它没有工作。\ n);
返回 - 1;


EXIT_FAILURE是失败时从main()返回的犹太人。

}

printf(" pverse =% d \ n",(sizeof(BIBLE)* 1000));


如果malloc没有失败,那么它返回一个指向所需金额的指针

的内存。无论如何,你上面所做的可能不是你认为你在做什么。你的文字说pverse =,但你是/不/显示

pverse的值。你正在显示你从malloc获得的内存量,这是pverse现在指向的。你真的不是在学习

这里有什么有趣的事情,即使你/他/你显示了pverse的价值,也不会。顺便说一句,正如我最近通过这个小组了解到的那样,

显示pverse值的正确方法(如果你关心的话)将是:

printf(" pverse =%p \ n",(void *)pverse);

for(x = 0; x< 1000; x ++)
fillverse(pverse);


哇。你叫1000次反对;在fillverse中,你有一个内部500次迭代循环的
1000次迭代循环。这张照片有什么问题

? :-)


现在是时候重新考虑数据结构和你使用

的方法了。首先要弄清楚反向是什么。我应该这样做。

是填写一节经文,还是填写所有经文?如果是前者(我认为

这里是更好的选择),那么请考虑将指针传递给

只是在/ one / verse所在的位置走。这可能看起来像这样:

for(x = 0; x< whatever; x ++)

fillverse(& pverse [x]); / *将指针传递给THE verse以填充* /


在反向内容中,/ if /您决定使文本数据成员成为

指向 - char并执行动态分配(我建议你这样做),然后

每次调用时都会执行一个malloc.

for(x = 0; x< ; 1000; x ++)
printverse(pverse);


同样的想法(现在,你没有向我们展示printverse,所以我不能检查它的

签名是否一致,但整体方法会影响你用反向做的所有



自由(pverse);
再次,如果你使用动态文本,我建议你使用一个函数

,你必须释放每个文本指针(一个在

动态pverse数组的每个元素)在释放pverse

指针作为最后一步之前。

返回0;
} <对于(x = 0; x <1000; x ++)
for(y = 0; y <500; y ++)
{/> printf("%s \ n",pverse.text);
pverse.text [y ] =''\ 0'';
}


这是一个严重的问题。你不应该真的需要

迭代字符串中的每个字符,就像你的内循环
似乎在做的那样;几乎总会有一些库函数(或者你自己设计的一些函数)用来处理行,

或者 ;诗歌或者其他什么(无论是输入还是输出,这个函数

似乎有点混淆它在做什么)。如果这个函数是

读入一节经文,实际上在/ all /中不应该有任何循环,而只是

这样的东西:


#include< string.h>

#define MAX_VERSE 500 / *你想要的最长诗歌+ 1 * /

FILE * fp ; / *假设你已经在某处管理了这个... * /


BIBLE * fillverse(BIBLE * pverse)

{

char buffer [MAX_VERSE];

if(fgets(buffer,MAX_VERSE,fp)== NULL)

{

printf( EOF到达。\ n;);

返回NULL;

}

其他

如果( (pverse-> text = malloc(strlen(buffer)+ 1))== NULL)

{

printf(" Allocation error.Giving up.\ n");

退出(EXIT_FAILURE);

}

返回pverse;

}


我设置它的方式,该函数返回NULL表示已加载

来自输入流(fp)的所有可用文本。

}

* ------------------------------------ ---- *

我知道在函数fillverse中,我有pverse.text [y]
错误。我已经玩了好几个小时试图找到正确的方法去做我想做的事情。

请给我任何关于风格的建议或者无论你怎么想都可能是合适的。


我要停在这里,让你消化这个。回来看项目

演变了!


祝你好运,

-leor

谢谢!
-M。
Hi all,
I''m working on a quick program to bring the Bible into memory from a
text file. Anyway, I have three questions to ask.

First, is my implementation of malloc () correct in the program to
follow?

Second, have I correctly passed the structure''s pointer to the
functions in this program?

Last, how do I go about initializing the structure variables in the
given function?
Rather than answering the questions directly, allow me to comment on the
code en passant. You''ve made some design decisions here that you may want
to reconsider.

Here''s the program:

*----------------------------------------*

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

struct bibtxt
{
char book[32];
int chapter;
int verse;
char text[500];
Right here, it looks like the text array is supposed to represent a verse.
Rather than having a "worst case" fixed-size, you''re far better off making
this a pointer-to-char and handling the allocation dynamically. The extra
complexity this would require is more than made up for by the overall
increase in memory efficiency. I won''t show the entirety of the changes
this would entail, but I''ll try to hit the highlights. For starters, change
the above to:
char *text;};

typedef struct bibtxt BIBLE;

void fillverse (BIBLE *pverse);

int main (void)
{
BIBLE *pverse;
int x;

pverse = malloc (1000 * sizeof (BIBLE));
This value ''1000'' (along with the hopefully-soon-to-be-retired ''500'')
permeate your code. We disaffectionately refer to this as a "magic number"
that would be better off represented as a symbolic constant. In C, if it is
used as an array dimension, you''re pretty much constrained to using
#define''d symbols, but that''s better than littering the code with ''1000''s.

Another severe flaw in your organization is the fact you''re iterating
across the entire 1000-element range of your verse array regardless of how
much data has actually been loaded (which you don''t seem to actually find
out from any of the code here). What you want to do in cases like this is
check how much you''ve loaded (if any), remember that value, and use it as
the limit for those loops which iterate over the data. Using something like
the version of fillverse() I''ll show you below, you''d manage that sort of
thing in the portion of your code that actually calls fillverse.
if (pverse == NULL)
{
printf ("It didn''t work.\n");
return -1;
EXIT_FAILURE is the kosher thing to return from main() upon failure.
}

printf ("pverse = %d\n", (sizeof (BIBLE) * 1000));
If the malloc didn''t fail, then it returned a pointer to the desired amount
of memory. In any case, what you''re doing above is perhaps not what you
think you''re doing; your text says "pverse = ", but you''re /not/ displaying
the value of pverse. You''re displaying the amount of memory you''ve obtained
from malloc, which pverse is now pointing to. You''re not really learning
anything interesting here, and wouldn''t be even if you /were/ displaying
the value of pverse. BTW, as I''ve recently learned via this group, the
right way to display the value of pverse (if you cared) would be:
printf("pverse = %p\n", (void *) pverse);

for (x = 0; x < 1000; x++)
fillverse (pverse);
Whoa. You''re calling fillverse 1000 times; within fillverse, you''ve got a
1000-iteration loop going with an inner 500 iteration loop. What''s wrong
with this picture? :-)

Now it is time to re-think the data structure and your approach to using
it. Start by having an abstract idea of what "fillverse" is supposed to do.
Is it to "fill a verse", or "fill all verses"? If the former (I think
that''s the better choice here), then think in terms of passing a pointer to
just where the /one/ verse is to go. That may look something like this:
for (x = 0; x < whatever; x++)
fillverse(&pverse[x]); /* pass pointer to THE verse to fill */

Within fillverse, /if/ you decide to make the text data member a
pointer-to-char and perform dynamic allocation (and I suggest you do), then
there will be a malloc performed in each call to fillverse.

for (x = 0; x < 1000; x++)
printverse (pverse);
Same idea (now, you didn''t show us printverse, so I can''t check its
signature for consistency, but the overall approach will shadow whatever
you do with fillverse).

free (pverse); Again, if you go with the dynamic text, that I suggest you use a function
for this, and you''ll have to free each of the text pointers (one within
each element of the dynamic pverse array) before you free the pverse
pointer as the last step.

return 0;
}

void fillverse (BIBLE *pverse)
{
int x, y;

for (x = 0; x < 1000; x++)
for (y = 0; y < 500; y++)
{
printf ("%s\n", pverse.text);
pverse.text[y] = ''\0'';
}
This is severely problematic. You shouldn''t ever really be needing to
iterate over every single character in a string the way your inner loop
seems to be doing; almost always there will be some library function (or
some function of your own devising) that you''d employ to process a "line",
or a "verse", or whatever (whether it be input or output, and this function
seems to be a bit confused as to which it is doing). If this function is
read in "a verse", in fact there ought not be any loops at /all/, but just
something like this:

#include <string.h>
#define MAX_VERSE 500 /* longest verse you expect + 1 */
FILE *fp; /* assume you''ve got this managed somewhere... */

BIBLE *fillverse(BIBLE *pverse)
{
char buffer[MAX_VERSE];
if (fgets(buffer, MAX_VERSE, fp) == NULL)
{
printf("EOF reached.\n");
return NULL;
}
else
if ((pverse->text = malloc(strlen(buffer) + 1)) == NULL)
{
printf("Allocation error. Giving up.\n");
exit(EXIT_FAILURE);
}
return pverse;
}

The way I''ve set it up, the function returns NULL to indicate it has loaded
all available text from the input stream (fp).
}

*----------------------------------------*

I know that in the function fillverse, that I have the pverse.text[y]
wrong. I''ve been playing with this for several hours trying to find the
right way to do what I''m wanting to do with this.

Please give my any advice on style or whatever you think may be
appropriate.
I''m going to stop here and let you digest this. Check back as the project
evolves!

Good luck,
-leor

Thanks!
-M.




-

Leor Zolman --- BD软件--- www.bdsoft.com

C / C ++,Java,Perl和Unix的现场培训

C ++用户:下载BD Software的免费STL错误消息解密器:
www.bdsoft.com/tools/stlfilt.html


Mannequin *< ma ***** **@primary.net>写道:
Mannequin* <ma*******@primary.net> wrote:
我正在制作一个快速程序,将圣经从一个
文本文件中存入记忆中。无论如何,我有三个问题要问。
首先,我的实现malloc()是否在程序中正确跟随?


我看不到任何实施 of malloc(),我想你的意思是

" invocation" ;-)

其次,我是否正确地将结构的指针传递给了
这个程序中的功能?
最后,我如何在
给定函数中初始化结构变量?
这是'程序:
* ---------------------------------- ------ *
#include< stdio.h>
#include< stdlib.h>
struct bibtxt
{
char book [32];
int chapter;
int verse;
char text [500];
} ;


一句话:使用这种魔术通常不是好的风格。数字如

32和500.如果你需要它们,它往往比#define一个sym-

bolic名称更好,然后在你的程序中使用这些名称 - 那将是b / b
使它更容易阅读和修改(只要想想会发生什么

如果你发现一个超过499个字符的经文然后必须

通过你的程序搜索以用新值替换500'。所以我建议使用例如


#define MAX_BOOK_NAME_LENGTH 32

#define MAX_VERSE_LENGTH 500

#define MAX_VERSE_COUNT 1000

(在你的程序开发的后期阶段你可能会发现它会变得更实用同时制作''book''和

''text''结构char指针的成员,并且只为你真正需要的内容分配尽可能多的

内存使用一些固定长度的

数组。)

typedef struct bibtxt BIBLE;
void fillverse(BIBLE * pverse);
int main(无效)
{BIBLE * pverse;
int x;
pverse = malloc(1000 * sizeof(BIBLE));
if(pverse == NULL)
{
printf(它没有工作。\ n ;);
返回-1;


更好地制作


返回EXIT_FAILURE;


所以你可以确定一个值无论你要编译程序的操作系统是什么,都将返回



}


你打电话的方式malloc()以及检查返回值(和

包括必要的头文件)都没问题。我唯一能做的就是使用


pverse = malloc(1000 * sizeof * pverse);


因为如果这样写的话,你不必担心用其他东西替换它们,以防你以后做出颠覆的话。

a指向不同类型对象的指针。

printf(" pverse =%d \ n",(sizeof(BIBLE)* 1000));


我想你知道你在这里打印的东西不是

的位置,而'pverse'指的是指向但是分配的字节数(或者,确切地说是
,字符数)。而且,你从

sizeof()获得的值是''size_t''类型,它不是int。它始终是未签名的

,也可以是例如一个长的int。因此,将printf()的第二个参数

第二个参数转换为机器上可用的最大无符号整数类型

并使用适当的转换说明符
也许是这样的:


printf(" pverse =%lu \ n",(unsigned long)(sizeof * pverse * 1000));

for(x = 0; x <1000; x ++)
fillverse(pverse);


如果我猜对了,你不想填写第一个结构超过了
而且又一次又一次,但所有这些都是一个又一个。在那种情况下(如果

fillverse()实际上意味着一次只能在单个结构上工作)

你需要的是


for(x = 0; x <1000; x ++)

fillverse(pverse + x);





for(x = 0; x <1000; x ++)

fillverse(& pverse [x]);


(pverse + x和& pverse [x]是等价的,都指向你分配的结构数组中的

x-th结构。) />
for(x = 0; x <1000; x ++)
printverse(pverse);


这里可能存在相同的问题...

free(pverse);
返回0;


为了保持安全,你应该使用


返回EXIT_SUCCESS;


这里,返回值0并不一定意味着在所有

操作系统下成功,而EXIT_SUCCESS在任何地方都是正确的

编译程序。

}
void fillverse(BIBLE * pverse)
{
int x,y;
for(x = 0; x< 1000; x ++)


为什么在以下从未使用过的''x'时循环?你只需要加热你的CPU ;-)这样你就可以在相同的结构上重复内部

循环一次。

for(y = 0; y <500; y ++)
{/> printf("%s \ n",pverse.text);
pverse.text [y] =' '\ 0'';
}
}


这没有多大意义。首先,按照

函数的名称,我倾向于认为它的意思是将一些数据放在

结构中。并且因为它在分配内存后直接调用

''bibtxt''结构''pverse''的''text''成员指向

只包含随机数据,没有任何你可以打印的内容,并且,wprse,那里没有任何东西可以保证''''''''''''''''''''''''''''''''''''''''''''''''''' />
所以在printf()的第一次调用中,你甚至可以最终使用

访问超出该数组末尾的内存,除非有''\ 0''

意外地已经在你从malloc()获得的内存中。下一个

的问题是''​​pverse''是一个指针,所以你需要


printf("%s \ n",pverse- >文字);


和,在以下行中,


pverse-> text [y] =''\ 0 '';


既然你会把''\ 0''放到第一个元素中,之后调用

prinf()就可以了(但是它们相当无用,当你只打印空字符串时,没有太多可以看到




所有这些循环(更换后)箭头运算符的点)

的作用是使用''\0''初始化''text''数组的所有元素。我确实没有看到这对你有什么好处,但是如果它真的是你想要做什么

使用memset()可能效率更高。如果你愿意使用calloc()而不是malloc(),你可以得到相同的效果,而不需要

任何额外的代码。


如果fillverse()函数的目的实际上是将你分配的所有''bibtxt''结构的成员数组归零

''text''成员数组那么

你可以把它写成


无效的反向(BIBLE * pverse)

{

int i;
= i; i< 1000; i ++)

memset(pverse [i] .text,0,500);

}


或者,如果你喜欢循环''text'的元素'

void fillverse(BIBLE * pverse )

{

int i,j;


for(i = 0; i< 1000; i ++)

for(j = 0; j <500; j ++)

pverse [i] .text [j] =''\''';

}


请注意,现在你必须使用点而不是箭头

运算符。虽然朴素的''pverse''是一个指针,''pverse [i]''

是结构数组的第i个结构''pverse''是指 -

ting to。


如果你写这样的fillverse()你只需要调用一次,

传递它的地址你分配的内存,而不是一两千美元!


如果你想要在main()中循环,你会重写fillverse()

as


void fillverse(BIBLE * pverse)

{

memset(pverse-> text,0 ,500);

}


并从main()这样调用


for(i = 0; i< 1000; i ++)

fillverse(pverse + i);

请给我任何关于风格或任何你认为合适的建议
I''m working on a quick program to bring the Bible into memory from a
text file. Anyway, I have three questions to ask. First, is my implementation of malloc () correct in the program to
follow?
I can''t see any "implementation" of malloc(), I guess you mean
"invocation";-)
Second, have I correctly passed the structure''s pointer to the
functions in this program? Last, how do I go about initializing the structure variables in the
given function? Here''s the program: *----------------------------------------* #include <stdio.h>
#include <stdlib.h> struct bibtxt
{
char book[32];
int chapter;
int verse;
char text[500];
};
One remark: It''s usually not good style to use such "magic" numbers like
32 and 500. If you need them it tends to be preferable to #define a sym-
bolic name for then and then use that names in your program - that will
make it a lot easier to read and also to modify (just think what happens
if you find a verse with more than 499 characters and then having to
hunt through your program to replace the 500''s by a new value). So I
would recommend to use e.g.

#define MAX_BOOK_NAME_LENGTH 32
#define MAX_VERSE_LENGTH 500
#define MAX_VERSE_COUNT 1000

(In a later stage of the development of your program you probably will
find that it''s going to be more practical to make both that ''book'' and
''text'' members of the structure char pointers and only allocate as much
memory for them as you really need instead of using some fixed-length
arrays.)
typedef struct bibtxt BIBLE; void fillverse (BIBLE *pverse); int main (void)
{
BIBLE *pverse;
int x; pverse = malloc (1000 * sizeof (BIBLE));
if (pverse == NULL)
{
printf ("It didn''t work.\n");
return -1;
Better make that

return EXIT_FAILURE;

so you can be sure that a value meaning falure will be returned on
whatever operating system you are going to compile the program.
}
The way you call malloc() as well as checking the return value (and
including the necessary header files) is fine. The only thing I would
do differently is to use

pverse = malloc( 1000 * sizeof *pverse );

since if written like this you don''t have to worry about replacing
''BIBLE'' by something else in case you decide later to make ''pverse''
a pointer to an object of a different type.
printf ("pverse = %d\n", (sizeof (BIBLE) * 1000));
I guess you know that what you''re printing here isn''t the location to
which ''pverse'' is pointing to but the number of allocated bytes (or,
to be precise, the number of chars). Moreover, the value you get from
sizeof() is of type ''size_t'' which isn''t an int. It is always unsigned
and could also be e.g. a long int. So it might be prudent to cast the
second argument of printf() to the largest unsigned integral type
available on your machine and use the appropriate conversion specifier,
perhaps like this:

printf( "pverse = %lu\n", ( unsigned long ) ( sizeof *pverse * 1000 ) );
for (x = 0; x < 1000; x++)
fillverse (pverse);
If I guess correctly you don''t want to "fill" the first structure over
and over again but all of them one after another. In that case (and if
fillverse() is actually meant to work on a single structure at a time)
what you need here is either

for ( x = 0; x < 1000; x++ )
fillverse( pverse + x );

or

for ( x = 0; x < 1000; x++ )
fillverse( &pverse[ x ] );

("pverse + x" and "&pverse[ x ]" are equivalent, both point to the
x-th structure in the array of structures you allocated).
for (x = 0; x < 1000; x++)
printverse (pverse);
There''s probably the same problem here...
free (pverse); return 0;
To stay on the safe side you should use

return EXIT_SUCCESS;

here, a return value of 0 does not necessarily mean success under all
operating systems while EXIT_SUCCESS will be correct wherever you
compile the program.
} void fillverse (BIBLE *pverse)
{
int x, y; for (x = 0; x < 1000; x++)
Why do you loop over ''x'' when it''s never used in the following? You
are just heating up your CPU;-) That way you just repeat the inner
loop a thousand times on the same structure.
for (y = 0; y < 500; y++)
{
printf ("%s\n", pverse.text);
pverse.text[y] = ''\0'';
}
}
That doesn''t make much sense. First of all, going by the name of the
function I would tend to assume that it''s meant to put some data in
the structure. And since it''s called directly after allocating memory
the ''text'' member of your ''bibtxt'' structure ''pverse'' is pointing to
contains just random data and nothing you could print and, wprse, there
is also nothing that guarantees that there''s a ''\0'' in the ''text'' array,
so in the first invocation of printf() you could even end up with
accessing memory beyond the end of that array unless there''s a ''\0''
accidentally already in the memory you got from malloc(). The next
problem is that ''pverse'' is a pointer so you would need

printf( "%s\n", pverse->text );

and, in the following line,

pverse->text[ y ] = ''\0'';

Since you then would put a ''\0'' into the first element later calls of
prinf() are ok (but they are rather useless, there''s not much to see
when you print just the empty string).

All what that loop (after the replacing the dot by the arrow operator)
does is to initialize all elements of the ''text'' array with ''\0''. I do
not see what this is good for but if it''s really what you want to do
using memset() would be probably a lot more efficient. And if you would
use calloc() instead of malloc() you would get the same effect without
any additional code at all.

If the purpose of the fillverse() function is actually to zero out the
''text'' member arrays of all the ''bibtxt'' structures you allocated then
you could write it as

void fillverse( BIBLE *pverse )
{
int i;

for ( i = 0; i < 1000; i++ )
memset( pverse[ i ].text, 0, 500 );
}

or, if you prefer to loop over the elements of ''text''

void fillverse( BIBLE *pverse )
{
int i, j;

for ( i = 0; i < 1000; i++ )
for ( j = 0; j < 500; j++ )
pverse[ i ].text[ j ] = ''\0'';
}

Please note that now you have to use the dot instead of the arrow
operator. While the unadorned ''pverse'' is a pointer, ''pverse[ i ]''
is the i-th structure of the array of structures ''pverse'' is poin-
ting to.

If you write fillverse() like this you only have to call it once,
passing it the address of the memory you allocated, and not a
thousand times!

If you instead want to loop in main() you would rewrite fillverse()
as

void fillverse( BIBLE *pverse )
{
memset( pverse->text, 0, 500 );
}

and call it from main() like this

for ( i = 0; i < 1000; i++ )
fillverse( pverse + i );
Please give my any advice on style or whatever you think may be
appropriate.




因为有点不清楚fillverse()函数到底是什么意思

应该这样做(我不认为)你真的想要归零出来

你所分配的第一个结构中的''text''成员a

$ bb,不是吗?)很难说是什么相反。

你能更详细一点吗?因为我假设你想要

来初始化该函数中结构的成员,你还需要知道你计划从哪里获取数据等等。 />

问候,Jens

-

\ Jens Thoms Toerring ___ Je *********** @ physik.fu-berlin.de

\ __________________________ http://www.toerring.de


2004年4月10日星期六11:08:29 -0500

Mannequin *< ma ******* @ primary.net>写道:
On Sat, 10 Apr 2004 11:08:29 -0500
Mannequin* <ma*******@primary.net> wrote:
printf(" pverse =%d \ n",(sizeof(BIBLE)* 1000));


这只是为了看到我的数学是正确的。我的目标不是显示pverse的内容,只是显示它所获得的大小。

for(x = 0; x< 1000; x ++)
用于(x = 0; x <1000; x ++)
printverse(pverse);
printf ("pverse = %d\n", (sizeof (BIBLE) * 1000));
This was just to see that my math was right. I wasn''t aiming to display
the contents of pverse, just the size that it got malloc''ed to.
for (x = 0; x < 1000; x++)
fillverse (pverse);

for (x = 0; x < 1000; x++)
printverse (pverse);



只是为了将来的回复,我确实解决了这个问题。我很快就抛出了这个

代码,所以我可以在这里发布相关部分并错误地将

()循环放入。


另一件事是函数fillverse最终会用内容填充

结构。我只是在我给你的代码中使用它

测试如何去做。我认为NULL字符将是一个很好的方法。 :)


感谢你指出这一点。我还要非常感谢

Jens和Leor帮助我完成了我b
$ b所遇到的一些结构问题。 :)


-M。



Just for future replies, I did fix this. I was quickly throwing up this
code so I could post the relevant parts here and mistakenly put the for
() loops in.

One other thing is that the function fillverse will eventually fill the
structure with content. I was just using it in the code I gave you to
test how to go about doing that. I figured that the NULL character would
be a nice way to do that. :)

Thanks for pointing that out. I also want to send a big thank you to
Jens and Leor for helping me through some of the structure problems I
was having. :)

-M.


这篇关于Malloc,结构帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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