question
stringlengths
25
894
answer
stringlengths
4
863
Anyone know if ffmpeg does asynchronous file io? That is, the input file is read in a separate thread as to avoid io blocking the processing thread? Basically what I want to figure out is whether or not i need to do calls to "av_read_frame" inside a separate thread (to avoid blocking) or if ffmpeg alrdy handles this issue? How might I figure this out? I've tried downloading the ffmpeg source but haven't been able to find anything useful.
You need to do it yourself. FFmpeg only has minimal thread awareness, and as icecrime said, the function signature obviously precludes doing it asynchronously.
I have a file saved as UTF-8, and i'm reading it like this: ``` ReadFile(hFile, pContents, pFile->nFileSize, &dwRead, NULL); ``` (pContents is a BYTE* of size nFileSize) its just a small file with 100 bytes or so, contains text which i want to read into memory in wchar_t* format, so i can set the text of edit and static controls with the unicode text. How can i convert the bytes to UTF-8? edit (i don't want to use fstream or wfstream)
MultiByteToWideCharto convert from UTF-8 to UTF-16 (wchar_t).WideCharToMuliByteto convert from UTF-16 to UTF-8.
``` gcc 4.5.1 Fedora 14 Linux ``` I have this static library that was build from a previous programmer. However, he has left the company and we don't have the source code. All we have is the header files*.hand thelibnet.astatic library. When I am try and link this with our application. I get aincompatible linker error. I think the problem is that the static library has been built on a 32 bit machine. And I am trying to link using a 64 bit machine. I could compile my application using the cflag -m32. However, I just want to know if there is any command that will give me if the static library was built in either 32 or 64 bit mode? Many thanks for any suggestions,
An.aarchive is just a collection of objects, so why not: ``` ar x libnet.a file someobj.o ``` That will give you an answer like: ``` someobj.o: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), not stripped ```
I currently have code that looks like ``` while (very_long_loop) { ... y1 = getSomeValue(); ... x1 = y1*cos(PI/2); x2 = y2*cos(SOME_CONSTANT); ... outputValues(x1, x2, ...); } ``` the obvious optimization would be to compute the cosines ahead-of-time. I could do this by filling an array with the values but I was wondering would it be possible to make the compiler compute these at compile-time? Edit: I know that C doesn't have compile-time evaluation but I was hoping there would had been some weird and ugly way to do this with macros.
If you're lucky, you won't have to do anything: Modern compilers do constant propagation for functions in the same translation unit and intrinsic functions (which most likely will include the math functions). Look at the assembly to check if that's the case for your compiler and increase the optimization levels if necessary.
Is it possible to make the checkboxes in a list view control with LVS_EX_CHECKBOXES style tri-state (having BS_3STATE button style)? I'm using WTL but I'm OK manually sending messages around.
Yes, you need an ImageList with 3 images of a unchecked, checked and indeterminate checkbox. Call ListView_SetImageList() to assign the LVSIL_STATE image list. Manipulate LVITEM.state to display the kind of checkbox you want.
Is there any way to query ACLs on Linux programmatically? Given a file or directory, I have to check if an ACL exists for it and then find out the level of access granted to different users. All I could find on the net were thegetfaclandsetfaclcommand line utilities which are of no use to me. Also, what are the best practices I need to follow when working with ACLs?
They are in theacl.hheader. There are links out to each of the functions fromhere. A few sample functions: acl_create_entry- create a new ACL entryacl_delete_entry- delete an ACL entryacl_get_entry- get an ACL entry The functions are in libacl.
Which one do you recommend for a commercial project with developers that need to have access to a particular part of repository only? Development IDE is Eclipse and Programming language is C/C++ Key features of the requirement is: Authoritative and ACL hierarchical access to repository
Git, combined with a "central" server managed withGitolite, can provide all the fine-grained control you need (per user/per group, with access to all or only some part of the repo, even to only some branches). That being said, if your developers are more familiar with a CVCS like SVN, it might be wiser to use that knowledge at least to start the project (and uses Authentication method in your apache server configuration): aCVCS can be quite different from a DVCS.(plus you still can later convert a SVN repo into a Git one)
I'm looking for a way to easily debug C code in an Android NDK application using Eclipse. I've read ways to debug the app using gdb or something similar but what I want is a way to push messages to Eclipse somehow. I'm looking for a solution that's as simple as using a print function in C and seeing it in the DDMS Log or anything similar. Does anyone have any experience doing this?
You can use the Android logging facilities: ``` #include <android/log.h> #define APPNAME "MyApp" __android_log_print(ANDROID_LOG_VERBOSE, APPNAME, "The value of 1 + 1 is %d", 1+1); ``` Make sure you also link against the logging library, in your Android.mk file: ``` LOCAL_LDLIBS := -llog ```
In the following code, is the behaviour undefined ? ``` #include<stdio.h> int main() { printf(7+"%c","sundaram"); } ``` Its printing "aram". Can't understand how.
This is undefined behavior. A string literal in C is a pointer to a a block of pre-initialized memory.By coincidence, your two string literals occupy adjacent blocks of memory.When you add7to the pointer to the first literal, you end up pointing into the middle of the next literal. Your program's data is arranged in memory like this: ``` %c\0sundaram\0 | | "%c" --^ | 7 + "%c" ------^ ``` Therefore, you end up callingprintfwith two pointers into the same string("adam", "sundadam")and no format specifiers.
I'm having trouble using bool as a type compiling with ndk-build: ``` bool test = true; ``` error: 48: error: 'bool' undeclared (first use in this function) Any ideas?
boolis not a built-in type in C. You need to#include <stdbool.h>to get it.
Does anyone know of any C parser library for .NET? (I'm intending to parse C code into some form of object graph, so I can convert it to a different language.)
ANTLR can do what you'd like. It has a C preprocessor and ANSI C grammar. https://github.com/antlr/grammars-v4
I'm looking for sample code on how to use the TMS3705 RFid transponder base station IC to communicate with the TMS37157 RFid device. The TMS3705 datasheet is not very helpful - it only describes the physical interface. Either sample code or a good description of how to construct/send a transmit packet and receive/parse a receive packet would be very helpful.
The TMS3705 is used in thePaLFI Evaluation kit TMS37157. You find the reference to theFAQ.
I am currently looking into writing a plugin for mysql in C. I have been reading and studying MySQL 5.1 Plugin Development (http://www.amazon.com/MySQL-Plugin-Development-Sergei-Golubchik/dp/1849510601) which has been helping me out a lot. However I can't seem to find any examples that execute queries. I tried Googling for one but couldn't find any relevant examples. My goal for the time being is to write just a simple plugin that after some data is entered into a table will just perform some basic select queries. If anyone would be willing to share a link to such an example or provide one, it would be most appreciated.
I haven't used Mysql with C before, however you might want to take a look at these links: http://dev.mysql.com/doc/refman/5.1/en/c-api-function-overview.htmlhttp://www.mysql.com/downloads/connector/c/ If you know MySql I think those links would be a good starting point at least.
Count amount of digits in a given number or input by the user.
Independent of programming language: floor(log10(x))+1 where x is your number (>0). If you want to handle 0 and negative numbers, I'd suggest something like this: x == 0 ? 1 : floor(log10(abs(x)))+1
Can sombody explain how this works? ``` int x, y; .... (some_condition ? x : y) = 100; ``` Is this intended to work or is is just a "blind" translation or the compiler (something likevec[10]equals10[vec])?
This is valid C++ and invalid C. The result of a conditional expression can be (and in this case is) anlvaluein C++ refering to one ofxorydepending on whethersome_conditionevaluates totrue. In C++ eitherxis assigned the value 100 if some_condition istruewhen converted to abool, otherwiseyis assigned 100. In C, the result of a conditional expression is never anlvalueand cannot be assigned to.
Could you please tell me the logic of usingsizeof data / sizeof *datainthis codeline 17? ``` ... unsigned char data[16]; ... size = fread(data, sizeof *data, sizeof data / sizeof *data, file); ... ``` Thanks
That's a common C idiom for "number of elements in an array". Since an arraydecays to a pointerat the slightest provocation,*datais the first element of the array, and therefore it's dividing the total size of the array by the size of its first element, giving a count of elements. There are any number of possible objections to this technique, whether on style grounds, the fact that it only works on variables declared as arrays (not those passed as pointer to the first element -- it relies on the decay-to-pointer not having happened yet), or possible breakage scenarios in C++ code; that said, it remains common in older C code.
Base on the answers i've got, i think this problem is kind of meaningless. Thanks for all your kind replies! i want to get a binary number with its rightmost j bits set to 1 and others set to be 0. basically, there are two methods. i wanna know which of them is more efficient, or is there a more efficient way than these two? ``` 1. ~(~0 << j) 2. (1 << j) - 1 ```
Not sure if it's the answer you're looking for, but I'll bet it won't make more than a nanosecond of difference. :) Or, to put it another way: Don't micro-optimize it unless that one-liner is the bottleneck in your code. If you needotherforms of fast bit manipulation that might actually be slower, try looking at the compiler intrinsic functions, like_BitScanForward. Those might actually make your bit operations faster, when used correctly (butnotin a situation like this).
If I have several sets of numbers (just a 2D array where each row is a set): ``` [ 1, 3, -1, -1] [ 2, 4, -1, -1] [ 7, 8, 9, 10] ``` What would be an algorithm to create a list of sums (ignoring -1's)? the result for the above would be: ``` 1+2+7, 1+2+8, 1+2+9, 1+2+10, 1+4+7, 1+4+8, 1+4+9, 1+4+10, 3+2+7, 3+2+8, 3+2+9, 3+2+10, 3+4+7, 3+4+8, 3+4+9, 3+4+10 ```
For each number in the first list, generate all sums starting with that number and all sums recursively generated by applying the same method to all but the first list. When you have no lists left, that is the base case. Pseudo-code: ``` function find_sums(lists): if lists is empty: return [""] sums = [] for n in lists[0]: if n != -1: for sum in find_sums(lists from index 1 onwards): sums.append(n + "+" + sum) return sums ``` This is called theCartesian product.
This question already has answers here:Closed12 years ago. Possible Duplicate:Container Class / Library for C I expect I'd be forced to use vectors, lists and sets for my C program. Should I invent those entities from scratch, or there is some kind of standard library for C as STL is for C++ ?
C doesn't have templates, so it might be difficult to implement those C++ collections in a generic way. I'm not aware of any libraries that implement those features in C. If I were faced with such a situation, my first thought would be to isolate the parts of my program that would benefit from C++ features, write them in C++, then provide anextern "C"interface to those modules so they could be called from the pure C parts of the program. Is that an option for you?
I'm writing an app in C that requires MySQL interaction, so I downloaded the Connector/C archive from the official website, and it contains bin, lib and include folders, but I don't know where to install them. I could copy the include files into my project folder, but where can I put the lib file so that my compiled binary (and other binaries) can find it? Thanks in advance!
This is confusing, isn't it.. don't know why they don't make this more clear. The lib/ files go in /usr/local/lib The include/ files go in /usr/local/include The bin/ files go in /usr/local/bin The /usr/.. directory isn't visible through finder afaik so you have to go at it via commandline. Best of luck Also, in your Xcode project, make sure you add a Linked Library by going to your Target's settings, General, then adding Linked Library "libmysqlclient.dylib"
Is there any way to query ACLs on Linux programmatically? Given a file or directory, I have to check if an ACL exists for it and then find out the level of access granted to different users. All I could find on the net were thegetfaclandsetfaclcommand line utilities which are of no use to me. Also, what are the best practices I need to follow when working with ACLs?
They are in theacl.hheader. There are links out to each of the functions fromhere. A few sample functions: acl_create_entry- create a new ACL entryacl_delete_entry- delete an ACL entryacl_get_entry- get an ACL entry The functions are in libacl.
Which one do you recommend for a commercial project with developers that need to have access to a particular part of repository only? Development IDE is Eclipse and Programming language is C/C++ Key features of the requirement is: Authoritative and ACL hierarchical access to repository
Git, combined with a "central" server managed withGitolite, can provide all the fine-grained control you need (per user/per group, with access to all or only some part of the repo, even to only some branches). That being said, if your developers are more familiar with a CVCS like SVN, it might be wiser to use that knowledge at least to start the project (and uses Authentication method in your apache server configuration): aCVCS can be quite different from a DVCS.(plus you still can later convert a SVN repo into a Git one)
I'm looking for a way to easily debug C code in an Android NDK application using Eclipse. I've read ways to debug the app using gdb or something similar but what I want is a way to push messages to Eclipse somehow. I'm looking for a solution that's as simple as using a print function in C and seeing it in the DDMS Log or anything similar. Does anyone have any experience doing this?
You can use the Android logging facilities: ``` #include <android/log.h> #define APPNAME "MyApp" __android_log_print(ANDROID_LOG_VERBOSE, APPNAME, "The value of 1 + 1 is %d", 1+1); ``` Make sure you also link against the logging library, in your Android.mk file: ``` LOCAL_LDLIBS := -llog ```
In the following code, is the behaviour undefined ? ``` #include<stdio.h> int main() { printf(7+"%c","sundaram"); } ``` Its printing "aram". Can't understand how.
This is undefined behavior. A string literal in C is a pointer to a a block of pre-initialized memory.By coincidence, your two string literals occupy adjacent blocks of memory.When you add7to the pointer to the first literal, you end up pointing into the middle of the next literal. Your program's data is arranged in memory like this: ``` %c\0sundaram\0 | | "%c" --^ | 7 + "%c" ------^ ``` Therefore, you end up callingprintfwith two pointers into the same string("adam", "sundadam")and no format specifiers.
I'm having trouble using bool as a type compiling with ndk-build: ``` bool test = true; ``` error: 48: error: 'bool' undeclared (first use in this function) Any ideas?
boolis not a built-in type in C. You need to#include <stdbool.h>to get it.
Does anyone know of any C parser library for .NET? (I'm intending to parse C code into some form of object graph, so I can convert it to a different language.)
ANTLR can do what you'd like. It has a C preprocessor and ANSI C grammar. https://github.com/antlr/grammars-v4
I'm looking for sample code on how to use the TMS3705 RFid transponder base station IC to communicate with the TMS37157 RFid device. The TMS3705 datasheet is not very helpful - it only describes the physical interface. Either sample code or a good description of how to construct/send a transmit packet and receive/parse a receive packet would be very helpful.
The TMS3705 is used in thePaLFI Evaluation kit TMS37157. You find the reference to theFAQ.
I am currently looking into writing a plugin for mysql in C. I have been reading and studying MySQL 5.1 Plugin Development (http://www.amazon.com/MySQL-Plugin-Development-Sergei-Golubchik/dp/1849510601) which has been helping me out a lot. However I can't seem to find any examples that execute queries. I tried Googling for one but couldn't find any relevant examples. My goal for the time being is to write just a simple plugin that after some data is entered into a table will just perform some basic select queries. If anyone would be willing to share a link to such an example or provide one, it would be most appreciated.
I haven't used Mysql with C before, however you might want to take a look at these links: http://dev.mysql.com/doc/refman/5.1/en/c-api-function-overview.htmlhttp://www.mysql.com/downloads/connector/c/ If you know MySql I think those links would be a good starting point at least.
Count amount of digits in a given number or input by the user.
Independent of programming language: floor(log10(x))+1 where x is your number (>0). If you want to handle 0 and negative numbers, I'd suggest something like this: x == 0 ? 1 : floor(log10(abs(x)))+1
Can sombody explain how this works? ``` int x, y; .... (some_condition ? x : y) = 100; ``` Is this intended to work or is is just a "blind" translation or the compiler (something likevec[10]equals10[vec])?
This is valid C++ and invalid C. The result of a conditional expression can be (and in this case is) anlvaluein C++ refering to one ofxorydepending on whethersome_conditionevaluates totrue. In C++ eitherxis assigned the value 100 if some_condition istruewhen converted to abool, otherwiseyis assigned 100. In C, the result of a conditional expression is never anlvalueand cannot be assigned to.
Could you please tell me the logic of usingsizeof data / sizeof *datainthis codeline 17? ``` ... unsigned char data[16]; ... size = fread(data, sizeof *data, sizeof data / sizeof *data, file); ... ``` Thanks
That's a common C idiom for "number of elements in an array". Since an arraydecays to a pointerat the slightest provocation,*datais the first element of the array, and therefore it's dividing the total size of the array by the size of its first element, giving a count of elements. There are any number of possible objections to this technique, whether on style grounds, the fact that it only works on variables declared as arrays (not those passed as pointer to the first element -- it relies on the decay-to-pointer not having happened yet), or possible breakage scenarios in C++ code; that said, it remains common in older C code.
Base on the answers i've got, i think this problem is kind of meaningless. Thanks for all your kind replies! i want to get a binary number with its rightmost j bits set to 1 and others set to be 0. basically, there are two methods. i wanna know which of them is more efficient, or is there a more efficient way than these two? ``` 1. ~(~0 << j) 2. (1 << j) - 1 ```
Not sure if it's the answer you're looking for, but I'll bet it won't make more than a nanosecond of difference. :) Or, to put it another way: Don't micro-optimize it unless that one-liner is the bottleneck in your code. If you needotherforms of fast bit manipulation that might actually be slower, try looking at the compiler intrinsic functions, like_BitScanForward. Those might actually make your bit operations faster, when used correctly (butnotin a situation like this).
If I have several sets of numbers (just a 2D array where each row is a set): ``` [ 1, 3, -1, -1] [ 2, 4, -1, -1] [ 7, 8, 9, 10] ``` What would be an algorithm to create a list of sums (ignoring -1's)? the result for the above would be: ``` 1+2+7, 1+2+8, 1+2+9, 1+2+10, 1+4+7, 1+4+8, 1+4+9, 1+4+10, 3+2+7, 3+2+8, 3+2+9, 3+2+10, 3+4+7, 3+4+8, 3+4+9, 3+4+10 ```
For each number in the first list, generate all sums starting with that number and all sums recursively generated by applying the same method to all but the first list. When you have no lists left, that is the base case. Pseudo-code: ``` function find_sums(lists): if lists is empty: return [""] sums = [] for n in lists[0]: if n != -1: for sum in find_sums(lists from index 1 onwards): sums.append(n + "+" + sum) return sums ``` This is called theCartesian product.
This question already has answers here:Closed12 years ago. Possible Duplicate:Container Class / Library for C I expect I'd be forced to use vectors, lists and sets for my C program. Should I invent those entities from scratch, or there is some kind of standard library for C as STL is for C++ ?
C doesn't have templates, so it might be difficult to implement those C++ collections in a generic way. I'm not aware of any libraries that implement those features in C. If I were faced with such a situation, my first thought would be to isolate the parts of my program that would benefit from C++ features, write them in C++, then provide anextern "C"interface to those modules so they could be called from the pure C parts of the program. Is that an option for you?
I'm writing an app in C that requires MySQL interaction, so I downloaded the Connector/C archive from the official website, and it contains bin, lib and include folders, but I don't know where to install them. I could copy the include files into my project folder, but where can I put the lib file so that my compiled binary (and other binaries) can find it? Thanks in advance!
This is confusing, isn't it.. don't know why they don't make this more clear. The lib/ files go in /usr/local/lib The include/ files go in /usr/local/include The bin/ files go in /usr/local/bin The /usr/.. directory isn't visible through finder afaik so you have to go at it via commandline. Best of luck Also, in your Xcode project, make sure you add a Linked Library by going to your Target's settings, General, then adding Linked Library "libmysqlclient.dylib"
This is a tricky C question asked in interview: Write a program that does nothing, not even taking up memory. Is it possible to do so?
All programs use memory. When you run the program, the OS will set up an address space for the program, copy its arguments into its process space, give it a process ID and a thread, give it some file descriptors for I/O, etc. Even if your program immediately terminates you still use up this memory and CPU time.
``` int myvar=100; main() { pid_t (*f) (void ); int *ip; int myvar=10; f = (pid_t(*) (void)) dlsym(RTLD_NEXT, "getpid"); ip = (int *) dlsym(RTLD_NEXT, "errno"); if (ip) printf("%d \r\n", *ip); ip = (int *) dlsym(RTLD_NEXT, "myvar"); if (ip) printf("%d \r\n", *ip); //not work where is i am wrong } ```
Thegetpidanderrnosymbols are exported by the libc.myvvarsymbols is in your executable and is probably not exported. Objdump -T will help you to check if the symbol is exported or not. ``` $ objdump -T /lib/libc.so.6 | grep -w getpid 00c9c570 g DF .text 00000036 GLIBC_2.0 getpid ```
Given ``` char foo[1024] = "bar"; ``` This will initialize foo to contain 'b','a','r',0 . Is the remaining 1020 characters zero initialized, or uninitialized ? I'd think the above is the same as `char foo[1024] = {'b','a','r','\0'} ; and as with initializing of aggregates, any member not mentioned is initialized to zero ?
If an array/aggregate is initialized somehow[edit: by use of a static initializer], the remaining unspecified entries are zeroed, yes.
I'm kind of new to C, but not to programming. I'm trying to create a program that takes an input and replies with a random string that's already saved in an array (for example). I'm not trying to create a random string, I want them to be "fixed", like in Java: ``` String [] sa; sa[0] = "Hello, World"; sa[1] = "Hi dude!"; ```
``` const char *sa[]={"Hello, World","Hi dude!"}; ``` Then you can do ``` return sa[i]; ``` The return value ischar *Just make sureiis within bounds
I want to create a tool like mini task manager. I want to show all the running processes, cpu and memory usage. Can anybody tell me related api's which I can use for this. Any link to related web page will be appreciated. (I want dump of all the statistics of running processes, cpu and memory.) Thanks in advance.
To do that, you will need touse the tool help functions to get snapshotsof the system. Hereis a code example.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed5 years ago.Improve this question I need a memory profiler to know the memory usage for each function. I know valgrind (Massif) but it doesn't give me information about specific functions (at least, I don't know how to do it with massif) Do you know any tool for this purpose in Linux? Thanks!
You may want to take a look atMemProf.
Is it this kind of thing: ``` for(;;) { statements; } ``` Or is it this: ``` for(initialisation;condition;updation) { } ``` I am looking for answers with references to a variety of sources.
Your first case (forwith empty expressions) is aninfiniteloop and the second one (with empty body of theforstatement) is anemptyloop
I was wondering, do most implementations ofcalloctreat the size as an alignment too, and round it up to the next supported granularity? If so, then do they round up to the next power of 2, or do they round to the next multiple of 8 or 16? Ifcallockeeps the parameter the same, then how does that even work? Wouldn't your data then be unaligned? Thank you!
sizeofis defined to yield the size of an object within an array -- in other words, it already accounts for any padding that's needed for proper alignment. So ifsizeof(foo)is 23 for some objectfoo, then your processor must be byte-aligned. (On the other hand, if you're passing 23 because you just think it's a good value to pass in, then good luck to you; you're on your own.)
``` TCHAR finalpath[MAX_PATH]; GetCurrentDirectory(MAX_PATH,finalpath); TCHAR filename[] = TEXT("\\lista.txt"); wcscat(finalpath,filename); wprintf(L"List will be saved to %s", finalpath); ``` So this basically confirms me that finalpath is indeed c:\somepath\lista.txt but_wfreopen(TEXT(finalpath),TEXT("w"),stdout); If i just change it to ``` _wfreopen(TEXT("c:/somepath/lista.txt"),TEXT("w"),stdout); ``` everything then works fine, why and how can i make it accept my finalpath arg? Thanks
You don't use the TEXT macro with variables. I'm surprised that_wfreopen(TEXT(finalpath),TEXT("w"),stdout);even compiles. Try_wfreopen(finalpath,TEXT("w"),stdout);
GCC has__builtin_prefetchto support prefetching. My question is how can I prefetch the data to a specific level of cache. For example, I only would like to prefetch the data toL2 cacheinstead of all the way toL1 cache.
__builtin_prefetchhas three arguments; the third one is the cache level. AFAICT, this has only effect on SSE, where it generates prefetchnta, prefetcht1, prefetcht2, prefetcht3, respectively.
I wrote a touchpad program in C that provide x,y information of the touchpad. Now, I want to transfer that X,Y values to a C# program. I tried to write the information to a file and read using C#. But, as C program blocked the text file, I was getting the following error: The process cannot access the file 'C:\simpletpinfo\data.txt' because it is being used by another process. I don't have much idea about the socket programming and i couldn't run the examples of socket programming that are in the web. (I am using visual studio 2008, may be that doesn't support sys/socket.h and other files). please help me in this regards.
I think what you are looking for is Interprocess Communication, IPC. There are many ways,thispage describes all the different ways on Windows and when to use which. In my opinion I think you should consider usingData Copy.
I build the code, then when I try to run it, it executes and exits quickly . I am pretty sure that there is a way in the project configuration , but I forgot how .
You can always just usegetc()before the return. Enter a character and it will exit.. Or run the VSctrl+f5combination, or add a breakpoint if debugging.
What is the use of padding struct in C?
Some architectures will perform better if only aligned accesses are made, so putting 32-bit objects on 32-bit boundaries, and 64-bit objects on 64-bit boundaries can improve the speed of your application. Some architectures are completely incapable of making unaligned accesses, and on those architectures not padding can be a real disaster.
Consider I have a struct: ``` struct SimpleStruct { int x; int y; int z; } ``` Now if I have 3 separate threads, each which only updates one of the x,y,z fields of the struct respectively, is it safe to let them update concurrently, or should I use a mutex or something to stop that from happening?
It is safe (structs are aligned). However you should be careful about false sharing (seeHerb Sutter's articleabout it): if the fields are in the same cache line the writes will be effectively serialized.
Is there an API to get the number of CPUs available in Linux? I mean, without using /proc/cpuinfo or any other sys-node file... I've found this implementation using sched.h: ``` int GetCPUCount() { cpu_set_t cs; CPU_ZERO(&cs); sched_getaffinity(0, sizeof(cs), &cs); int count = 0; for (int i = 0; i < 64; i++) { if (CPU_ISSET(i, &cs)) count++; else break; } return count; } ``` But, isn't there anything more higher level using common libraries?
``` #include <unistd.h> long number_of_processors = sysconf(_SC_NPROCESSORS_ONLN); ```
This question already has answers here:Closed12 years ago. Possible Duplicate:string to float conversion? how can i convert a string to float in c with only Libc?
You can usestrtodorsscanfto do this.
Is there any other way to execute a program using kernel, other than shell and system calls?
It always used to be the case that there was really only one way to execute a program on Unix and its derivatives, and that was via theexec()system calls. The very first (kernel) process was created by the boot loader; all subsequent processes were created byfork()andexec(). Of course,fork()only created a copy of the original program; it was theexec()system call - in one of a number of forms in the C source code, but eventually equivalent toexecve()- that did the donkey work of replacing the current process with a new image. These days, there are mechanisms likeposix_spawn()which might, or might not, use a separate system call to achieve roughly the same mechanism.
pxandpyare the x and y coordinates of a point on a circle's circumference. Given: ``` the center of the circle as: cx, cy the radius of the circle as: r px ``` How to calculate the value ofpy? Thanks!
Given px there are at most two possible values for py. Look at the pythagorean theorem: (px-cx)^2+(py-cy)^2=r^2. Let d=r^2-(px-cx)^2 If d>0 then you have two solutions. This gives py=sqrt(d)+cy, where the square root is positive or negative. If d=0 then you have one solution py=cy, the left or right of the circle, depending on px If d<0 you have no real points.
Ok: I edited my question:I heard somewhere that php language is written in C. So what happens for example when you run a function in php such asdate("Ymd");orfile_get_contents("file.txt");? Does it translate that code to C and request to server, or does php do it? And if it does translate it and request, that means basically it is C?
That is incorrect. If you mean the language PHP is implemented in, it is C, not C++; see thePHP wikipedia page, under Implementation Language. That does not, however, mean that it "translates" code to C; PHP is an interpreted language. While executing code, it does of course have to use functions written in C, since it is itself using C. However, no "translation" into C occurs; the code is simply parsed by the PHP language and the language then calls, itself, what is appropriate. You might want to readmore on interpreted languages, that should give you a better understanding.
There is a sequence of increasing numbers that have the same number of binary 1s in them. Given n (the number of 1 bits set in each number in the series) write an algorithm or C program to find the n'th number in the series. I found this question on internet and I think the answer is just (((1 << (n+1)) - 1) & ~2). Isn't that right? I found some scary programs to compute the answer.
(1 << n+1) - 3is a more concise way to express the result, but yes, I believe your expression is also correct.
My project right now works with XP and up, WINVER == 0x501 . However, for those using Vista and up, I would like to do: ``` case WM_MOUSEHWHEEL: ``` in my WNDPROC However when I try to build that I get undeclared identifier WM_MOUSEHWHEEL is there a way to maintain compatibility with XP, but to let Vista & 7 users have this capability? Thanks
Use this: ``` #ifndef WM_MOUSEHWHEEL #define WM_MOUSEHWHEEL 0x020E #endif ``` There, that should be correct NOTE: I originally answered WM_MOUSEWHEEL, not WM_MOUSEHWHEEL. Correct. :P
I'm working on a fun project where I need a simple key/value store that uses B+Trees. I studied them some years ago, and to be honest, I don't want to reinvent the wheel, so I'm looking for a simple implementation in C of b+tree that I can just include in my project. I know of sqlite's, dbm's and tokyocabinet's ones but they're a little too "complicated" for my needs. Is there any (even pedagogical) work on this you can refer me to? Do you have some code to share? Thanks a lot!
There's one listed in thewikipediaarticle: Interactive B+ Tree Implementation in C Perhaps you can edit out the "interactive" parts?
Given ``` char foo[1024] = "bar"; ``` This will initialize foo to contain 'b','a','r',0 . Is the remaining 1020 characters zero initialized, or uninitialized ? I'd think the above is the same as `char foo[1024] = {'b','a','r','\0'} ; and as with initializing of aggregates, any member not mentioned is initialized to zero ?
If an array/aggregate is initialized somehow[edit: by use of a static initializer], the remaining unspecified entries are zeroed, yes.
I'm kind of new to C, but not to programming. I'm trying to create a program that takes an input and replies with a random string that's already saved in an array (for example). I'm not trying to create a random string, I want them to be "fixed", like in Java: ``` String [] sa; sa[0] = "Hello, World"; sa[1] = "Hi dude!"; ```
``` const char *sa[]={"Hello, World","Hi dude!"}; ``` Then you can do ``` return sa[i]; ``` The return value ischar *Just make sureiis within bounds
I want to create a tool like mini task manager. I want to show all the running processes, cpu and memory usage. Can anybody tell me related api's which I can use for this. Any link to related web page will be appreciated. (I want dump of all the statistics of running processes, cpu and memory.) Thanks in advance.
To do that, you will need touse the tool help functions to get snapshotsof the system. Hereis a code example.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed5 years ago.Improve this question I need a memory profiler to know the memory usage for each function. I know valgrind (Massif) but it doesn't give me information about specific functions (at least, I don't know how to do it with massif) Do you know any tool for this purpose in Linux? Thanks!
You may want to take a look atMemProf.
Is there an API to get the number of CPUs available in Linux? I mean, without using /proc/cpuinfo or any other sys-node file... I've found this implementation using sched.h: ``` int GetCPUCount() { cpu_set_t cs; CPU_ZERO(&cs); sched_getaffinity(0, sizeof(cs), &cs); int count = 0; for (int i = 0; i < 64; i++) { if (CPU_ISSET(i, &cs)) count++; else break; } return count; } ``` But, isn't there anything more higher level using common libraries?
``` #include <unistd.h> long number_of_processors = sysconf(_SC_NPROCESSORS_ONLN); ```
This question already has answers here:Closed12 years ago. Possible Duplicate:string to float conversion? how can i convert a string to float in c with only Libc?
You can usestrtodorsscanfto do this.
I'm looking for a simple C Wrapper of zlib, to decompress a byte array. Anyone knows one ?
By wrapper function, you probably mean some simpler to use, more self-contained functions? Zlib contains them. Have a look in themanualunder "Utility Functions". You're probably look for: ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen));
I am having trouble getting to grips with the definition and uses of symbolic and literal constants and I was wondering if you anyone could explain them and highlight their differences. Thanks!
A literal constant is a value typed directly into your program wherever it is needed. For example int tempInt = 10; tempInt is a variable of type int; 10 is a literal constant. You can't assign a value to 10, and its value can't be changed. A symbolic constant is a constant that is represented by a name, just as a variable is represented. Unlike a variable, however, after a constant is initialized, its value can't be changed. If your program has one integer variable named students and another named classes, you could compute how many students you have, given a known number of classes, if you knew there were 15 students per class: students = classes * 15;
I'm trying to figure out how to detect whether a binary has been compressed with UPX. I am using a simple CRC to detect whether my app was in any way changed and if the CRC failed on the size due to a packer I would like to detect that as OK. Right now I am starting with UPX. So, is there any marker on the binary? are there any specific JMP or other instructions that I should search?This will mainly be tested in Windows, but in the future I might add it to Linux as well. Any help (and code) is appreciated. ADDED: I found that in the 10 binaries I checked the AddressOfEntryPointImport Directory RVAResouce Directory RVA either point to UPX or have an offset that is set by UPX. Any information on this? Thanks
Downloadupxsource code fromUPX Homepageand opensrc/p_w32pe.cppfile; the function you are looking for is; ``` int PackW32Pe::canUnpack() ``` This function checks if the file is compressed with win32 upx.
How do I send UDP packet from aspecificinterface on Linux using C? Should I use bind? Is it possible to send UDP from the interface not having IP address? Thanks.
Use bind. You cannot send UDP packets via an interface that does not have an IP address, because UDP uses the Internet Protocol and the Internet Protocol requires an IP address.
I have this simple code: ``` int main() { float x = foo(); printf("returned value: %f", x); return 0; } float foo () { return 5; } ``` when i run the code , the output is:"returned value: -858993472.000000" can somebody please explaing to me why does the returned value isnt 5.000000?
At the point at which you call the function there is no prototype in scope. This means that the function is assumed to returnint. Add a prototype before the point where you first call the function. ``` float f(void); ```
When debugging a program which uses (either C or C++),gdbdisplays complex numbers as_M_value = xxx + yyy*I(with a type ofcomplex double). While debugging, I need to print that number multiplied by a factor. The followingdoes notwork: ``` print a * 8.0 ``` I getArgument to arithmetic operation not a number or boolean. Also, I cannot access thereal and imaginary partsso that I can write a gdb macro to do the above. My current solution is to write a C function for manipulating complex values and arrays, and calling that function from gdb. Somehow, this just doesn't feel right.
If you use the standard C++ complex template then complex::real() and complex::imaj() should work. my2c Note : Was a comment ^^
I'm writing a C/CGI web application. Is there a library to parse a query string into something like aGHashTable? I could write my own but it certainly doesn't seem to be worth the effort to reinvent the wheel.
Theuriparserlibrary can parsequery stringsinto key-value pairs.
I have a time stored in a 64 bit int of the form 20110103101419 (i.e. representing 2011-01-03 10:14:19). How do I convert that to seconds since 1970 ?
My C is a bit rusty, but looking at the other two answers I would write a function as follows, returning the number of seconds since epoch or -1 in case of error. ``` #include <stdio.h> #include <time.h> time_t convertDecimalTime(long dt) { struct tm time_str; time_str.tm_isdst = -1; time_str.tm_sec = dt%100; dt/=100; time_str.tm_min = dt%100; dt/=100; time_str.tm_hour = dt%100; dt/=100; time_str.tm_mday = dt%100; dt/=100; time_str.tm_mon = dt%100-1; dt/=100; time_str.tm_year = dt%10000 - 1900; return mktime(&time_str); } ```
I want to learn C/C++ GUI Windows/Linux programming. Which IDE is more suitable? If I go with Visual Studio.NET, what are the pros and cons of it. Any IDE that supports both Windows and Linux?
TheQt Creator IDEworks for both Linux and Windows. If you want a more versatile development environment, Qt can integrate with Eclipse.
I need to store exactly four booleans in my struct in c. Yes I could use four integers or put them into an array but I would like to do it a bit nicer. I was thinking about an int like "0000" where each number would represent the boolean value, but then when editing I cant edit only the one digit, right? That doesnt look perfect either... Thanks for any ideas
You could use a bitfield struct: ``` struct foo { unsigned boolean1 : 1; unsigned boolean2 : 1; unsigned boolean3 : 1; unsigned boolean4 : 1; }; ``` You can then easily edit each boolean value separately, for example: ``` struct foo example; example.boolean1 = 1; example.boolean2 = 0; ```
I wonder if there is a software that can help us determine all possible origins of a function call. For example: ``` /* in file f1.c */ int f1() { x_func(); } /* in file f2.c */ int f2() { x_func(); } ``` If we want to trace the origin of all function calls to x_func(), the output will be: ``` f1.c:f1() f2.c:f2() ``` This is very useful when reading the source code. All answers are appreciated. Thank in advance :D
cscopecan help here
In ruby there's very common idiom to check if current file is "main" file: ``` if __FILE__ == $0 # do something here (usually run unit tests) end ``` I'd like to do something similar inCafter reading gcc documentation I've figured that it should work like this: ``` #if __FILE__ == __BASE_FILE__ // Do stuff #endif ``` the only problem is after I try this: ``` $ gcc src/bitmap_index.c -std=c99 -lm && ./a.out src/bitmap_index.c:173:1: error: token ""src/bitmap_index.c"" is not valid in preprocessor expressions ``` Am I using #if wrong? As summary for future guests: You cannot compare string using #ifBASE_FILEis the name of file that is being compiled (that Is actually what I wanted).Best way to do this is to set flag during compilation with -D
in gcc you can use: #if __INCLUDE_LEVEL__ == 0 or: if(!__INCLUDE_LEVEL__) to check if your inside the __BASE_FILE__
In .NET land, there's the tremendously usefulSystem.Windows.Forms.CheckedListBoxclass. What is the equivalent in Windows Common Controls land? (if any)
Turn a list view into one with checkboxes. If you want it similar to a ListBox, only use 1 column. ``` ListView_SetExtendedListViewStyle (handle, LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT); ```
When you download PHP's source you realize that all the goodies are in theext/directory in their respectivearray.c,string.c, etc. files. Now, I was wondering, it is possible to call these functions from a C program having those PHP C files?
You can do it but that doesn't mean it's a good idea. The PHP library functions deal with PHP's internal data types, memory allocation and management schemes, etc. You'd probably end up wasting a lot of time and effort on marshalling data between PHP and C. Most of the functionality is probably available in C libraries or easily implemented in C (with C style interfaces) anyway. Also, I suspect that you'd end up linking the entirety of PHP into your program just by accessing a couple of PHP's functions. Certainly possible but probably more trouble than it's worth. If you're writing in C then write in C, some unnatural bastardized mix of C and PHP would just get you a lot of funny looks.
Greetings, I'm working on alow levelprogramming project and I want to play a music with the computerspeaker. I'm already capable of using the speaker (withtimer2) and a song is represented in the following way: ``` note_t *music; ``` wherenote_trepresents a note and it's compound by: ``` typedef struct { int freq; /* note frequency */ int dur; /* note duration in miliseconds */ } note_t; ``` Now, what would be the best way to get the frequencies and durations of the notes from a music file? Thanks in advance! EDIT To clarify some doubts, what I want to know is the best format to get the necessary information to create a song with the structure above indicated.
Depending on your exact purpose, you can use one of the ringtone formats or invent your own. An example simple ringtone format isRTTTL.
How many times 'x' value will betestedin the following code snippet ? ``` int x; for(x=0;x < 10; x++) printf("%d",x); ``` To me it seems that the answer is11but my module says it is10?! what am I missing?
Eleven, as the condition is tested at thebeginningof each loop iteration, before printf is called: ``` 0 < 10 == true 1 < 10 == true 2 < 10 == true 3 < 10 == true 4 < 10 == true 5 < 10 == true 6 < 10 == true 7 < 10 == true 8 < 10 == true 9 < 10 == true 10 < 10 == false // exit from loop (printf not executed) ```
Is there a specific reason to use ldiv or div instead of '/' or '%' to divide/modulus two variables?
Yes. C99 §7.20.6.2/2 says: Thediv,ldiv, andlldiv, functions computenumer / denomandnumer % denomin a single operation.
I learnedenumswhen I learned C and from time to time I keep myself reminding about it and most of the time by re-reading from some source,it occurred to me that this is due to the fact I never use it in my programming,my programming interest concentrate around algorithmic problem solving so I am not sure where could I possibly use enums. Could somebody suggest some good example where using enums is makes things much easy? I would appreciate algorithmic examples but both of algorithmic or non-algorithmic examples are welcome.
Imagine that you are programming a depth first search and you want to tag your edges with whether they are tree, back, forward, or cross. You could create an enum EDGE_TYPE with the four possibilities and use it to tag your edges.
I have doubts about many things related with the different C specifications. If I program a library in C99, can I use it from C89 code? (using only the functions with C89 compliant definitions). example, this code would be usable in C89? Header of a shared library: ``` #ifdef C99 void func (double complex a, double complex b); // C99 function #endif /* another C89 compliant function */ void func2 (double a, double b); ``` Thanks in advance :)
The C language does not say anything about binary compatibility of C89 and C99 code. That is entirely up to the compilers you use for the different parts of the executable. If you can make the external headers of your library palatable for a C89 compiler, I don't see any obvious reason why it would not work, except for the usual issue of making sure that two compilers can generate compatible code.
C history question here. Why does the C functionputcrequire a second parameter like ``` putc( 'c', stdout ) ; ``` While puts is oh so more convenient ``` puts( "a string" ) ; ``` There is a function in msvc++ ``` putchar( 'c' ) ; ``` Which works the way one might expectputcto work. I thought the second parameter ofputcwas to be able to directputcto a file, but there is a functionfputcfor that.
``` int putc ( int character, FILE * stream ); ``` Writes a character to the stream and advances the position indicator.So it is a more generic function thanputcharOther functions can be based on this e.g. ``` #define putchar(c) putc((c),stdout) ``` According to Kernighan's bookputcis equivalent withfputcbutputccould be implemented as a macro and putcmay have to evaluate its stream argument more than once.I have read that supposedly that both exist for backward compatibility, but not sure if this is valid
in Linux playing or recording some audio is just read or write /dev/dsp But how to do the same in windows ? (with C)
There is no static device name, you should usewaveOut*functions,hereis a nice example of using those APIs.
I am writing C89, C90, Ansi-C Code. One of my functions requires a struct as a parameter. I want to call the function with the initialization of that struct rather than creating a struct first then passing it to the function. Here are some snippets which work. ``` typedef struct { char* EventName; char* Message; } Event; Event myEvent = { .EventName = "infomessage", .Message = "Testmessage" }; Notify(myEvent); ``` and here is what I would like to write but which doesn't work: ``` Notify({.EventName = "infomessage", .Message = "Testmessage"}); ``` or even better ``` Notify({"infomessage", "Testmessage"}); ``` EDIT: LabCVI is using the ISO 9899:1990 standard.
Use the compound literal(Event){"infomessage", "Testmessage"}, ie ``` Notify((Event){"infomessage", "Testmessage"}); ```
I'm having a trouble in opening FIFOs in C.. first I created them using mkfifo() function with permission : 0777, and when I tried to open them, it succeeded in opening the first FIFO only, then the process will stuck in opening the second FIFO, and this is my code : ``` fd1 = open("FIFO1_PATH", O_WRONLY ); fd2 = open("FIFO2_PATH", O_WRONLY ); ``` This will not be executed, but once I comment the second line, it executes ! Is there a limit for the number of opening FIFOs per process ? I don't know why is this happening.. I just spent 3 Hours trying to figure out what the problem is, but without any results :(
I just got it right :) I have to let the opening process wait until some other process opens the FIFO for reading (and it will be a blocked reading).. by doing sleep on the writing process I will ensure that the other process will opens for reading ..
I'm trying to find all subfolders in a file's path that have 'others exec' permission. I've tried to usestrtok(path_str,"/")to break the path string, but when usingstat()for the sub-directories of the root of the process I run, I get the "not a file or folder" error. Any suggestions on how I can overcome this error?
If the path is"long/path/to/the/file.txt", then you will need to callstat()on"long","long/path","long/path/to"and"long/path/to/the". If you don't care in what order you check these, the easiest way is probably to repeatedly usestrrchr(): ``` char *s; while (s = strrchr(path, '/')) { *s = 0; if (strlen(path) > 0) stat(path, &statbuf); else stat("/", &statbuf); /* Do something with statbuf */ } ``` (The special-casing is for paths beginning with/, to check the root directory itself).
I want to define a function in C language which can take an unlimited number of arguments of any datatype. For example:printf(),scanf(), etc. Any idea on this?
To use variable number of arguments in C you need to include the header ``` #include <stdarg.h> ``` printf()in C is an example of function that takes variable number of arguments. ``` int printf(const char *fmt, ...) ``` More infohere
How can i get the last digit of an integer (or NSInteger) outputted to integer? example: ``` int time = CFAbsoluteGetCurrent(); int lastDigit; ```
Usemodulo: ``` int lastDigit = time % 10; ```
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the help centerfor guidance.Closed10 years ago. So C obviously has a pretty dominant low level programming stronghold.....but is anything coming out that challenges/wants to replace it? Python/C#/etc all seem to be aimed at very high level, but when it comes down to nitty-gritty low level stuff C seems to be king and I haven't seen much "try" to replace that? Is there anything out there, or does learning C for low level stuff seem to be the standard?
If you mean systems level then perhapsD Language.
``` char program[3] = { 0x6a, 0x0a, 0xC3 }; //push 10; ret; char (*p)(void) = program; printf("char = %c \n", p()); ``` This code crashes. Why? The following code works ok: ``` char program[3] = { 0x90, 0x90, 0xC3 }; //nop; nop; ret void (*p)(void) = program; p(); ```
Because you need to cleanup your stack by popping from it. Read more on theretinstruction - it will load cs:ip with values from the stack!
I have a text file and would like to check if it contains a string. The text file is stored in a char array:char buffer[512][128];. Q1: Is it easier if I buffer it in one long array instead of a multidimensional array? Q2: How could I check whether the buffer contains the stringchar *s1 = "Hello world!";? I will need to search for multiple strings.
It will be much easier to use a single 1D array.strstr(buffer, s1)!= null(once you've changedbufferinto a 1D array)
the problem is i dunno how long the string will be, so i dunno how much should i allocate for my data... ``` 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
Many C runtime libraries (for instance, GNU's glibc and FreeBSD's (and NetBSD's and OpenBSD's and OS X's) libc) provideasprintf, which combinesmallocandsprintfinto a single call. ``` char *Data = NULL; asprintf(&data, "%s %s", Data1, Data2); ``` Assuming the return value indicates success, enough space has been dynamically allocated for the string, which you shouldfreewhen no longer used.
Why condition rand() % 3 is true approximatelу EVERY 3 time ? rand is REALY random isn't it ?
You realize, of course, that even a fair coin can give you ten heads in a row. There's a probability that can be assigned to that combination. A fair coin will give half heads and half tails overmanytrials, but it's not guaranteed to be 50/50 over a shorter run. Your own experience of the physical world tells you that your conclusion is incorrect. Same is true for rand().
can any one provide me a link for B-tree code in C,have understood the algorithm but still have problems in coding it
c++http://touc.org/btree.html c (slightly fancier than normal)http://code.google.com/p/high-concurrency-btree/downloads/list
In .NET land, there's the tremendously usefulSystem.Windows.Forms.CheckedListBoxclass. What is the equivalent in Windows Common Controls land? (if any)
Turn a list view into one with checkboxes. If you want it similar to a ListBox, only use 1 column. ``` ListView_SetExtendedListViewStyle (handle, LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT); ```
When you download PHP's source you realize that all the goodies are in theext/directory in their respectivearray.c,string.c, etc. files. Now, I was wondering, it is possible to call these functions from a C program having those PHP C files?
You can do it but that doesn't mean it's a good idea. The PHP library functions deal with PHP's internal data types, memory allocation and management schemes, etc. You'd probably end up wasting a lot of time and effort on marshalling data between PHP and C. Most of the functionality is probably available in C libraries or easily implemented in C (with C style interfaces) anyway. Also, I suspect that you'd end up linking the entirety of PHP into your program just by accessing a couple of PHP's functions. Certainly possible but probably more trouble than it's worth. If you're writing in C then write in C, some unnatural bastardized mix of C and PHP would just get you a lot of funny looks.
Greetings, I'm working on alow levelprogramming project and I want to play a music with the computerspeaker. I'm already capable of using the speaker (withtimer2) and a song is represented in the following way: ``` note_t *music; ``` wherenote_trepresents a note and it's compound by: ``` typedef struct { int freq; /* note frequency */ int dur; /* note duration in miliseconds */ } note_t; ``` Now, what would be the best way to get the frequencies and durations of the notes from a music file? Thanks in advance! EDIT To clarify some doubts, what I want to know is the best format to get the necessary information to create a song with the structure above indicated.
Depending on your exact purpose, you can use one of the ringtone formats or invent your own. An example simple ringtone format isRTTTL.
How many times 'x' value will betestedin the following code snippet ? ``` int x; for(x=0;x < 10; x++) printf("%d",x); ``` To me it seems that the answer is11but my module says it is10?! what am I missing?
Eleven, as the condition is tested at thebeginningof each loop iteration, before printf is called: ``` 0 < 10 == true 1 < 10 == true 2 < 10 == true 3 < 10 == true 4 < 10 == true 5 < 10 == true 6 < 10 == true 7 < 10 == true 8 < 10 == true 9 < 10 == true 10 < 10 == false // exit from loop (printf not executed) ```
Is there a specific reason to use ldiv or div instead of '/' or '%' to divide/modulus two variables?
Yes. C99 §7.20.6.2/2 says: Thediv,ldiv, andlldiv, functions computenumer / denomandnumer % denomin a single operation.