Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: How to use a struct with qsort()? Date: Sat, 26 Oct 2019 16:08:37 -0700 Organization: None to speak of Lines: 46 Message-ID: References: <06add10e-1e30-4741-a20c-ff56363733fe@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: reader02.eternal-september.org; posting-host="a81003712e56c2310798229a9d42ce2b"; logging-data="10987"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18yDa7TEf2F0J7BwYxxw0i+" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:GAKDRWBaFKmN98FNzqHrUSMQhzw= sha1:Nk6lxN84xuQtqQ5SiyrUwCwhaCo= Xref: csiph.com comp.lang.c:147271 DFS writes: [...] > So I try it in my code, to replace a small loop: > > int wsvals[26]={0}; (not a char as in previous examples) > memset(wsvals,0,26); > > Doesn't work. The code compiles (tcc Windows) with no warnings, but it > doesn't execute. I presume it does execute. It just doesn't do what you wanted it to do. > Finally on stackoverflow I find this: > "Note that for memset you have to pass the number of bytes, not the > number of elements because this is an old C function: > > So I do: memset(wsvals,0,26 * sizeof(int)); > > And it works. > > Most of the descriptions on the web say memset "is used to fill a block > of memory with given/particular value." No mention of the datatype. > > Why do I need to also use sizeof() for an int but not a char? Because sizeof (char) is 1 by definition. Given: char arr[26]; you could do either memset(arr, 0, 26); or memset(arr, 0, 26*sizeof(char)); Both are equivalent. But given an array of any type that you want to zero-fill, just apply sizeof to the entire object: int wsvals[26]; memset(wsvals, 0, sizeof wsvals); Note also that in your example, you already initialized the array: int wsvals[26]={0}; so there's no need to call memset. -- Keith Thompson (The_Other_Keith) kst-u@mib.org Will write code for food. void Void(void) { Void(); } /* The recursive call of the void */