English 中文(简体)
为印本问题分配记忆?
原标题:allocating memory for sprintf problem?
  • 时间:2010-12-29 17:52:14
  •  标签:
  • c

问题在于说明时间将多长,因此,我无法为我的数据分配多少时间。

char *Data = malloc(1024*1024);  //???????
sprintf(Data, "%s %s", Data1, Data2);

Data1 and Data2 varies in Size from time to time.... from very very long to very small i was wondering if there is away to use sprintf without allocating memory or something, since the allocated memory could be small sometime..

thanks

最佳回答
问题回答

由于数据1和数据2似乎只是使用透镜,只分配实际需要的记忆。

char *data = malloc(sizeof(char) * (strlen(data1) + strlen(data2) + 1));

不可能。 你们总是必须分配印本/印本所用的缓冲。

答案是没有的。

...... 但是,你不需要在管理你的法典时每分配一次。 视贵方案是否具有多面性,该守则的这一部分将如何经常运行,以及你所期望的最大范围是多么大,你可能更不用一次分配“尽可能大的大小”的单一缓冲,并使用像黑印这样的安全版本来填写。 (反对超支) 或者如果你要求的规模超过目前的缓冲规模,你可以有条件地重新定位缓冲。

例如,如果你使用C++和您的代码在某种方法中存在,你可以改变你的代码。 1. 数据分配项目:

static char *Data = malloc(1024*1024);

一种方法中使用的静态关键词保证,只有一度——首次援引这一条线,并且将超出该方法要求的范畴——才开始使用你的当地变量。

如果你使用C,那么你的缓冲区就可以成为全球的(不会成为其中的狂热),或者你可以把一个点推到当地范围的数据缓冲。 我确信真正的C方案制定者会就如何做此类事情提出更好的建议。

我知道,在你几乎永远无法充分利用的情况下,仅仅留下一个巨大的缓冲,似乎效率不高,但是,就大多数申请而言,分配的间接费用是一个比空隙的可能性大得多的问题。

Why not use the strlen functions for the string sizes?

char *buf = malloc(strlen(Data1) + strlen(Data2) + 2); // 2 for space and 
sprintf(buf, "%s %s", Data1, Data2);

这解决了在操作时间需要将数据1和数据2的大小表示出来的问题。





相关问题
Fastest method for running a binary search on a file in C?

For example, let s say I want to find a particular word or number in a file. The contents are in sorted order (obviously). Since I want to run a binary search on the file, it seems like a real waste ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Tips for debugging a made-for-linux application on windows?

I m trying to find the source of a bug I have found in an open-source application. I have managed to get a build up and running on my Windows machine, but I m having trouble finding the spot in the ...

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

Good, free, easy-to-use C graphics libraries? [closed]

I was wondering if there were any good free graphics libraries for C that are easy to use? It s for plotting 2d and 3d graphs and then saving to a file. It s on a Linux system and there s no gnuplot ...

Encoding, decoding an integer to a char array

Please note that this is not homework and i did search before starting this new thread. I got Store an int in a char array? I was looking for an answer but didn t get any satisfactory answer in the ...

热门标签