Path: csiph.com!news.swapon.de!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: Array manipulation techniques Date: Sun, 15 Nov 2015 10:43:51 -0800 Organization: None to speak of Lines: 43 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx02.eternal-september.org; posting-host="945944de09706c9b4e29b53c9d2efdc2"; logging-data="5702"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18Bn3qTtHtPAl3LaPCHfLsQ" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:68hANovPZr0kb31Q0UJ/m1zhg5o= sha1:tDxi83HHpKjhBmQ26gZ2gSimtcc= Xref: csiph.com comp.lang.c:76102 Barry Schwarz writes: > On Sun, 15 Nov 2015 09:44:38 +0100, "Morten W. Petersen" > wrote: >>I have an array of integers, where I need to replace one integer with a >>sequence of integers. >> >>For example, the array containing 1,2,3,1,2,3,1,2,3 needs to be expanded >>to contain 1,2,3,3,3,1,2,3,3,3,1,2,3,3,3, in other words, 3 needs to be >>replaced by 3,3,3. And the array has been dynamically allocated. >> >>Are there any standard functions that would do that, or do I need to >>implement something myself? > > You have to do it yourself: > scan the original contents to determine the number of entries in > the result > realloc the array with enough memory for this quantity > set index_2 to the end of the result > loop index_1 from last original entry to 0 > if the data at index_1 is key > store the desired number of entries, decrementing > index_2 for each > else > store the data from index_1 at index_2 and decrement > index_2 > decrement index_1 and repeat loop > return address of new array It's a bit easier if you just malloc() the new array and then traverse the original array while setting entries in the new one. It means you don't have to worry about clobbering data that you still need -- and there are similar problems where just traversing the array in reverse order isn't enough to avoid that. malloc()ing the new array and then (if you no longer need it) free()ing the original one is likely to do just about the same thing as realloc() anyway. -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"