question
stringlengths
24
425
answer
stringlengths
5
405
Is there any way to decompile Linux .so?
There aredecompilers, but a decompiler might not emit code in the same language that the original program was written in. There are alsodisassemblers, which will reassemble the machine code into assembly. The Decompilation Wikimay be a good source of additional information.
I already know that I can trace memory leaks in my code withmtraceandvalgrindon Linux, both of which are unavailable for Windows. Which Windows program would you recommend to trace memory leaks? I'm an Eclipse user and I've been working with C for a month or two now, so I prefer a user-friendly solution over something more advanced.
Application Verifier will do this quite well,http://msdn.microsoft.com/en-us/library/ms220948.aspx
My friend said he thinks i may have made a mistake in my programme and wanted to see if i really did. He asked me to send him the binary opposed to the source. As i am new to this i am paranoid that he is doing someting to it? What can you do with the binary that would mean you wouldnt want the source? thank
Black-box testing. Having the source may skew your view on how the program may be behaving.
If Python was so fast as C, the latter would be present in python apps/libraries? Example: if Python was fast as C would PIL be written completely in Python?
To access "legacy" C libraries and OS facilities.
Consider a float value like1.82set by the user. How do I find the next highest .05 value? For the given example the next highest value is 1.85. Is there a simple way or does it take a complex algorithm? I tried to usefloorandceilingfunctions to come up with the distance from the float to the next highest and lowest Integers. But I'm not sure how to proceed once I have that info. Thanks.
Multiply by 20, use ceiling, divide by 20.
In the execve() man page it is said that argv is a list of string arguments which is ended by a null pointer. But what is the NP for? I mean, the number of arguments is stored in argc, so what's the point of the null pointer?
execvedoes not takeargcas a parameter, it manually counts the arguments you give asargvto determineargcitself. This is for compatibility withexeclwhich takes a variable number of arguments instead of anargvarray.
I get a segmentation fault afterfreeing a certain pointer: ``` free(studentDB->name); ``` I can get its value without any errors or warnings: ``` printf("[DBG] studentDB->name: %s\n", studentDB->name); ``` However, as I said, the program crashes when I try to free it. What are the most common causes for afreecommand leading to a segmentation fault?
If you didn'tmalloc()it, you can'tfree()it. Where doesstudentDB->namecome from?
Is there any way to decompile Linux .so?
There aredecompilers, but a decompiler might not emit code in the same language that the original program was written in. There are alsodisassemblers, which will reassemble the machine code into assembly. The Decompilation Wikimay be a good source of additional information.
I already know that I can trace memory leaks in my code withmtraceandvalgrindon Linux, both of which are unavailable for Windows. Which Windows program would you recommend to trace memory leaks? I'm an Eclipse user and I've been working with C for a month or two now, so I prefer a user-friendly solution over something more advanced.
Application Verifier will do this quite well,http://msdn.microsoft.com/en-us/library/ms220948.aspx
My friend said he thinks i may have made a mistake in my programme and wanted to see if i really did. He asked me to send him the binary opposed to the source. As i am new to this i am paranoid that he is doing someting to it? What can you do with the binary that would mean you wouldnt want the source? thank
Black-box testing. Having the source may skew your view on how the program may be behaving.
If Python was so fast as C, the latter would be present in python apps/libraries? Example: if Python was fast as C would PIL be written completely in Python?
To access "legacy" C libraries and OS facilities.
just a sanity check please: in VB.NET: dim myarray(5) as integer gives six elements 0 to 5 but in c? int myarray[5]; gives five elements 0 to 4 ? is this correct?
Yes that's correct! Hope I saved your sanity.
In a C program I get "passing argument ... from incompatible pointer type" warnings, however I want to get error and terminate compilation instead of warning. What flag shall I set in makefile?
If using gcc, I think the option combination you need is-fstrict-aliasing -Wstrict-aliasing=3 -Werror=strict-aliasing. Seethis textfor documentation of thestrict-aliasingoption.
just a sanity check please: in VB.NET: dim myarray(5) as integer gives six elements 0 to 5 but in c? int myarray[5]; gives five elements 0 to 4 ? is this correct?
Yes that's correct! Hope I saved your sanity.
In a C program I get "passing argument ... from incompatible pointer type" warnings, however I want to get error and terminate compilation instead of warning. What flag shall I set in makefile?
If using gcc, I think the option combination you need is-fstrict-aliasing -Wstrict-aliasing=3 -Werror=strict-aliasing. Seethis textfor documentation of thestrict-aliasingoption.
How would you set a variable to equal infinity (or any guaranteed largest number value) in C?
``` #include <limits.h> int x = INT_MAX; ``` EDIT: answered before the questioner clarified, I was just guessing what type they wanted.
If I have a C file like below, what is the difference betweeniandj? ``` #include <stdio.h> #include <stdlib.h> static int i; int j; int main () { //Some implementation } ```
ihas internal linkage so you can't use the nameiin other source files (strictly translation units) to refer to the same object. jhas external linkage so you can usejto refer to this object if you declare itexternin another translation unit.
In my C++ program, I want to make sure i can write info to a file. How can I perform this check?
The only sure way to find if you can write to a file is to try to write to a file. It is possible, and even likely in some circumstances, that a file will have its permissions changed between calls to function such as stat and the actual write. Your code must deal with write failures anyway, so it makes sense to centralise the testing code there.
Is it possible to specify per-thread in Linux?
Yes, you kinda can do that. However not per-thead, but only per-call, using locale_t structures. Read more about that at POSIX: http://www.opengroup.org/onlinepubs/9699919799/functions/newlocale.html And Ulrich Dreppper's dedsgin documents of what whent into glibc 2.1: http://people.redhat.com/drepper/tllocale.ps.gz
What is the difference between a re-entrant function and a thread safe function?
Re-entrant means no global state (local only). Thread safe means it is not possible for 2 (or more) threads to conflict with each other (by writing conflicting values).
I am using fprintf command for writing on the text file, but every time when the function called its remove the previous data, I actually want to update the file so that the previous data remain. Kindly guide me how I can make it possible?
when you open the file use "a" for append. ``` FILE * file = fopen("filename", "a"); ``` http://www.cplusplus.com/reference/clibrary/cstdio/fopen/
How would you set a variable to equal infinity (or any guaranteed largest number value) in C?
``` #include <limits.h> int x = INT_MAX; ``` EDIT: answered before the questioner clarified, I was just guessing what type they wanted.
If I have a C file like below, what is the difference betweeniandj? ``` #include <stdio.h> #include <stdlib.h> static int i; int j; int main () { //Some implementation } ```
ihas internal linkage so you can't use the nameiin other source files (strictly translation units) to refer to the same object. jhas external linkage so you can usejto refer to this object if you declare itexternin another translation unit.
When I do#include <stat.h>in Linux, I get a compiler error. I need this library for theS_IWRITEflag, which in its turn is used in the context of system-level IO. Is stat.h unavailable in Linux?
stat.h is available under the "sys" folder, try to #include it from there or add it to the list of include directories.
I noticed that the boost library uses header files of (.hpp).I am curious since most source files I see use normal.hheader files.Could there be any special instances which warrant use of.hppinstead of.h? Thanks
Just convention, nothing special. You can use any extension on include files, actually.
I am working with audio data. I'd like to play the sample file in reverse. The data is stored as unsigned ints and packed nice and tight. Is there a way to callmemcpythat will copy in reverse order. i.e. if I had 1,2,3,4 stored in an array, could I callmemcpyandmagicallyreverse them so I get 4,3,2,1.
No, memcpy won't do that backwards. If you're working in C, write a function to do it. If you're really working in C++ use std::reverse or std::reverse_copy.
I noticed that the boost library uses header files of (.hpp).I am curious since most source files I see use normal.hheader files.Could there be any special instances which warrant use of.hppinstead of.h? Thanks
Just convention, nothing special. You can use any extension on include files, actually.
I am working with audio data. I'd like to play the sample file in reverse. The data is stored as unsigned ints and packed nice and tight. Is there a way to callmemcpythat will copy in reverse order. i.e. if I had 1,2,3,4 stored in an array, could I callmemcpyandmagicallyreverse them so I get 4,3,2,1.
No, memcpy won't do that backwards. If you're working in C, write a function to do it. If you're really working in C++ use std::reverse or std::reverse_copy.
I have a situation here i am taking input from user using scanf can I terminate the scanf as soon as user presses the # key please enlighten me on this
No,scanf()(or rather stdin, by default) is line-oriented so it needs to read a full line. Look intoncursesor similar libraries for "raw" key-by-key input.
How can I take a string (in this case it'll be loaded from a file) then remove certain characters and store them in an array. Ex: f.e.d.r.t.g.f remove "." to get f e d r t g f in an array where I can manipulate each individually
Just iterate through the string and only copy the characters you're interested in, maintaining an index of the current position in the new array.
If C does not support passing a variable by reference, why does this work? ``` #include <stdio.h> void f(int *j) { (*j)++; } int main() { int i = 20; int *p = &i; f(p); printf("i = %d\n", i); return 0; } ``` Output: ``` $ gcc -std=c99 test.c $ a.exe i = 21 ```
Because you're passingthe valueof the pointer to the method and then dereferencing it to get the integer that is pointed to.
It's not possible to do something likefputs(4, fptOut);because fputs doesn't like integers. How can I work around this? Doingfputs("4", fptOut);is not an option because I'm working with a counter value.
What about ``` fprintf(fptOut, "%d", yourCounter); // yourCounter of type int in this case ``` Documentation offprintfcan be foundhere.
How can I read from the stdout of my program? One of my threads needs to access the stdout to read what the other threads are logging. I'm using the dear old plain C.
Make stdout use a pipe by replacing the stdout fd with the write side fd of apipeusingdup.
I want to archive my database of mysql. Kindly give me some guide lines how I can make it possible, I am using mysql c library for insertion and selection etc. I dont know how to use dump command.
UseSHOW TABLESandDESCRIBE tbl_namequeries to obtain structure of database and tables. Then, use SELECT to fetch data and proceed it to your output according to the structure.
I hear of a need to call assembly functions/calls when programming embedded systems in C. Is this necessary in C++ or not?
C++ does not provide any more low-level constructs than C does. Hence, if you need to fiddle around with control registers and ISRs in C, you will need to do it in C++.
Is there a way to replace any keyword in a text file using POSIX calls, without re creating the file.. If yes Please tell me how to do it.. Thanks in advance..
If the text and the replacement are the same size then you can open it with moder+, seek, and then write. If their sizes are different then there is no way to replace without recreating.
Hi I'm working in a Linux environment and I have to link to a object file already compiled which offers me some services (services.o) and I know some of them, but I'd like to know which are all of the exported symbols of it. Is there any way to accomplish this not having the sources? If so, how? Thanks you very much.
Trynm-- this tool is there for just this purpose.
Text is disappearing from the bottom of aRichEditcontrol window and I'd like to ensure the bottom character is always visible. Obviously, I could manually scroll to the bottom, but I'd like to do it under software control.
Send the EM_SCROLLCARET message. Position the caret first, GetWindowTextLength() and EM_SETSEL.
I'm programming in Windows right now, but portable code would be welcomed too. What I'm using right now isfwrite(4), but this function needs a maximum number of elements to be written to the file. I can usestrlen(1)here but I'd like to know if there is any better way to do this.
Usefputsinstead: ``` FILE * f = fopen( "myfile.txt", "w" ); fputs( "Hello world\n", f ); ```
Is there a way to replace any keyword in a text file using POSIX calls, without re creating the file.. If yes Please tell me how to do it.. Thanks in advance..
If the text and the replacement are the same size then you can open it with moder+, seek, and then write. If their sizes are different then there is no way to replace without recreating.
Hi I'm working in a Linux environment and I have to link to a object file already compiled which offers me some services (services.o) and I know some of them, but I'd like to know which are all of the exported symbols of it. Is there any way to accomplish this not having the sources? If so, how? Thanks you very much.
Trynm-- this tool is there for just this purpose.
I have an array of data that represents PNG: ``` unsigned short systemFontTexture[] = { ... 0x5089,0x474E,0x0A0D,0x5089,0x474E,0x0A0D,0x5089, 0x474E,0x0A0D,0x5089,0x474E,0x474E,0x0A0D,0x5089, 0x474E,0x0A0D,0x5089,0x474E,0x474E,0x0A0D,0x5089, ... } ``` Can I create PNG file using this data? If yes, then HOW?
Create a data providerto serve up the data, and thencreate an image with the data provider.
How can I detect when a removable disk drive is (dis)connected to the system? How to get the mount path (for Linux) and the drive letter (for windows)? EDIT: Is there a way to detect the currently connected devices?
For Windows, the APIRegisterDeviceNotificationwill let you know when a USB device is added. The information about the volume is given in theDEV_BROADCAST_VOLUME structure. Thedbcv_unitmaskgives the drive letter.
I have an array of data that represents PNG: ``` unsigned short systemFontTexture[] = { ... 0x5089,0x474E,0x0A0D,0x5089,0x474E,0x0A0D,0x5089, 0x474E,0x0A0D,0x5089,0x474E,0x474E,0x0A0D,0x5089, 0x474E,0x0A0D,0x5089,0x474E,0x474E,0x0A0D,0x5089, ... } ``` Can I create PNG file using this data? If yes, then HOW?
Create a data providerto serve up the data, and thencreate an image with the data provider.
``` int x[10],y[10]; x = y; ``` I am thinking of a simple hack, which would enable me to get this effect.
You can wrap them instructs to use simple assignment: ``` struct foo { int a[10]; } x, y; x = y; ``` But really, just usememcpy.
I've compiled my C program usinggcc 4.4.1using the flag-g, but when I try to step through one of my functions ingdb version 7.0, I get the message: ``` "Single stepping until exit from function _DictionaryTree_getNodeList, which has no line number information." ``` Can someone tell me why this is happening?
Just guessing, but is _DictionaryTree_getNodeList in another file that wasn't compiled with -g?
I'm trying to learn how to use Lua with C, so by now I want to try running a script without loading it from a file, since I don't want to be bothered with messing up with files. Can anybody tell me which functions do I need to call for executing a simple string or what ever?
You can useluaL_dostringto execute a script from a string. If you need help with the basics (creating a Lua state, etc.), read part IV ofProgramming in Lua.
I have the simplest of makefiles: ``` threads: gcc threads.c -o threads ``` but I get the error: 'make: Fatal error: Don't know how to make target' Any ideas what I am doing wrong? It's probably something simple - I made the makefile in emacs on the system which is trying to run it (Unix)
Do you have spaces instead of a tab on the second line there? Most common basic make mistake, I'd say.
Why sometimes C code gets wrapped with curly braces without declaring a variable in them? e.g. (from FreeRTOS source code, file 'tasks.c'):portENTER_CRITICAL(); { xTicks = xTickCount; } portEXIT_CRITICAL();
This is just an inner scope. The benefit is that code shows your intent in that case. e.g. This scopeisthe critical section.
How can I print the source of a webpage, specified in curl_easy_setopt, without html tags? So, printing only the text in the source?
Curl/libcurl is just for fetching the HTML page. To extract information from it, you need other tools. The most general solution is to use a HTML parser. A good one in C isHTMLparser from libxml.
I want to see implementation of java.util.zip.CRC32. But within this class its using native c library functions for core implementation.How can I get the native source code. I can see the java.util.zip.CRC32 source code, but this doesn't have the actual implementation.
You must ask SUN, I mean Oracle about having the source code... :-/ You can try the source code for Java 6 at thisdownload page. CRC32 should not have changed much between Java 1.4 and 6.
Interesting little bug here: ``` if (host != NULL) { printf("hi"); } else { printf("FAIL"); } return 0; ``` doesn't print anything at all, but: ``` if (host != NULL) { printf("hi"); } else { printf("FAIL"); } fprintf(stdout, "\n%s\n", (char *)&additionalargs); return 0; ``` prints hiabc Does anyone know why this is?
printf output to stdout is buffered. You might want to look atfflush
I have a function that runs in C. I would like for it to timeout, or at least be non blocking. Is there a way to do that without running it as a thread?
select()(or one of its platform-specific equivalents) is what should be used if you don't know that there is input available from a blocking file or socket, and want to continue if there isn't.
Is it possible to skin the GTK+ progress bar widget such that it shows a custom image (an AJAX style animated gif maybe)? If so how and if not, is there any other option/control which can achieve this effect?
Something likeGtkSpinner?
Are there solutions in C or Objective-C to receive and play back SHOUTcast audio streams on the mac or iphone?
Implement an M3U/PLS parser (which is just a text list of MP3 streams) and use the code here to play the MP3's http://cocoawithlove.com/2008/09/streaming-and-playing-live-mp3-stream.html
Python hasctypesto access libraries. In PHP you write extensions for everything. Popular extensions like the one for libgd are available almost everywhere. Is there any extension which works like Python's ctypes, letting you access libraries without the need to write an PHP extension?
You're looking forffi.
In general i see the process'spidwhich is running in the background and start dbx on that process using the commanddbx -a <pid> similarly how could i do it using gdb?
In addition to the previous you can directly use ``` gdb -p <pid> ```
I have a function that runs in C. I would like for it to timeout, or at least be non blocking. Is there a way to do that without running it as a thread?
select()(or one of its platform-specific equivalents) is what should be used if you don't know that there is input available from a blocking file or socket, and want to continue if there isn't.
Is it possible to skin the GTK+ progress bar widget such that it shows a custom image (an AJAX style animated gif maybe)? If so how and if not, is there any other option/control which can achieve this effect?
Something likeGtkSpinner?
Are there solutions in C or Objective-C to receive and play back SHOUTcast audio streams on the mac or iphone?
Implement an M3U/PLS parser (which is just a text list of MP3 streams) and use the code here to play the MP3's http://cocoawithlove.com/2008/09/streaming-and-playing-live-mp3-stream.html
Is there an option I can change in Eclipse to make sure that my code has got to be ANSI C-compliant before it can be compiled?
Project > Properties > C/C++ Build > Tool Settings > Miscellaneous > "Support ANSI programs"
What is the name of the runtime library which implements Linux network interfaces, like sockets, tuntaps, netlink, etc...? For example when I create an UDP socket and make an ioctl call to fetch network interface info, which library actually implements that call? What are the corresponding *.so files on most linux dstirbutions?
These are c library calls, and as such are in the libc library.
I perform some checks in my Window class constructor, and if they fail I want to display an error message and close the window. I'm getting crashes when calling Close() from the constructor or from Window_Loaded. Does that sounds normal or am I doing something wrong? If this is normal, when should I call Close()?
It turns out you can call Close() in the constructor or on Window_Loaded - I was just doing something wrong later on in the destructor.
For example, say we have a union ``` typedef union { unsigned long U32; float f; }U_U32_F; ``` When a variable of this union type is declared, is there a way to set an initial value? ``` U_U32_F u = 0xffffffff; // Does not work...is there a correct syntax for this? ```
Use an initializer list: ``` U_U32_F u = { 0xffffffff }; ``` You can set other members than the first one via ``` U_U32_F u = { .f = 42.0 }; ```
Is there an option I can change in Eclipse to make sure that my code has got to be ANSI C-compliant before it can be compiled?
Project > Properties > C/C++ Build > Tool Settings > Miscellaneous > "Support ANSI programs"
What is the name of the runtime library which implements Linux network interfaces, like sockets, tuntaps, netlink, etc...? For example when I create an UDP socket and make an ioctl call to fetch network interface info, which library actually implements that call? What are the corresponding *.so files on most linux dstirbutions?
These are c library calls, and as such are in the libc library.
I am working in Ansi C, windows platform. I want to attach mysql database to my c program. Kindly guide me how I can make it possible.
Hereis a working example which sets up a connection and performs a query.
Is the following code valid ``` int main(){ int * a = 0; if ( !a ) { int b[500]; a = b; } //do something with a, //has the array a is //pointing too gone out //of scope and garbage //or is it still fine? } ```
No it is not, b has gone out of scope, accessing it (through the pointer) is undefined behavior.
This does work ``` LLIST *mylist[10] = {NULL}; ``` But would if I wanted to do this I get errors: ``` int x=10; LLIST *mylist[x] = {NULL}; ``` xcan be any value I'm setting it to 10 for the time being.xis going to be used as a counter.
Support for variable length arrays (which your second example uses) came in the C99 standard, which your compiler may not support. For gcc, you should pass the-std=c99option when compiling.
Can I somehow tell GStreamer to look for plugins in a specified directory?
Use theGST_PLUGIN_PATHenvironment variable to point at the directory you want, or programatically just call: ``` GstRegistry *registry; registry = gst_registry_get(); gst_registry_scan_path(registry, directory); ```
I'm new to using C programming I was wondering if there is a function call that can be used to quickly determine the amount of rows in a text file.
``` #include <stdio.h> #include <stdint.h> uint32_t CountRows(FILE* fp, uint8_t line_delimiter){ uint32_t num_rows = 0; uint16_t chr = fgetc(fp); while(chr != EOF){ if(chr == line_delimiter){ num_rows++; } chr = fgetc(fp); } return num_rows; } ```
What are the various mechanisms using which we can detect if a process execution is leading to memory fragmentation? Are there any tools available for the same? Suggestion for tools which work with 'C' code and can run on Windows, Linux and VxWorks will be helpful.
Just as a suggestion, you may want to try Valgrind. I'm not certain it's what you're looking for, but it may come in handy. http://valgrind.org/
I've got a menu in curses that I'd like to put multi-line descriptions onto. My code puts the description fields on but they don't display if they don't fit on the line. Curses is happy enough printing multi-line text as strings (not as menu descriptions) Any ideas how to get multi-line descriptions working ?
I've given up on this and render my own scrollable list of items instead.
What is the difference between CreateThread and beginthread APIs in Windows? Which one is preferrable for thread creation?
_beginthread()and_beginthreadex()was required by earlier versions of the Microsoft CRT to initialize thread-local state. Thestrtok()function would be an example. That's been fixed, that state now gets dynamically initialized, at least since VS2005. UsingCreateThread()no longer causes problems.
I have an array that contains pointers. How can I swap two pointers - say array[1] and array[4] - correctly?
You need a temporary variable: ``` void*temp = array[4]; array[4]=array[1]; array[1] = temp; ``` Edit Fixed first line.
I've got a menu in curses that I'd like to put multi-line descriptions onto. My code puts the description fields on but they don't display if they don't fit on the line. Curses is happy enough printing multi-line text as strings (not as menu descriptions) Any ideas how to get multi-line descriptions working ?
I've given up on this and render my own scrollable list of items instead.
What is the difference between CreateThread and beginthread APIs in Windows? Which one is preferrable for thread creation?
_beginthread()and_beginthreadex()was required by earlier versions of the Microsoft CRT to initialize thread-local state. Thestrtok()function would be an example. That's been fixed, that state now gets dynamically initialized, at least since VS2005. UsingCreateThread()no longer causes problems.
I have an array that contains pointers. How can I swap two pointers - say array[1] and array[4] - correctly?
You need a temporary variable: ``` void*temp = array[4]; array[4]=array[1]; array[1] = temp; ``` Edit Fixed first line.
I want to send a file in C++ over network (for a chat program) what should I do?
Take a look athttp://www.boost.org/doc/libs/1_38_0/doc/html/boost_asio/examples.html. The Iostreams example should give you the first good step. Asio is a portable network library of the boost project. Boost is available for most platforms available today. You can stream in the file and stream out it into the TCP stream.
How to split a string into tokens by'&'in C?
strtok / strtok_r ``` char *token; char *state; for (token = strtok_r(input, "&", &state); token != NULL; token = strtok_r(NULL, "&", &state)) { ... } ```
Any good alternative written in C to replace Boost.Program_options? Given it's able to parse: Short options like -hLong options like --help --input-fileParse repeated keys/optionsAccepts key-value pairs: --mysql=/usr/libParsing environmental variables and XML/INI files is optional.
If you are okay with the GPL license, you wantGNU getopt.
Any good alternative written in C to replace Boost.Program_options? Given it's able to parse: Short options like -hLong options like --help --input-fileParse repeated keys/optionsAccepts key-value pairs: --mysql=/usr/libParsing environmental variables and XML/INI files is optional.
If you are okay with the GPL license, you wantGNU getopt.
How would I go about taking a number like123456and having it print as1 2 3 4 5 6?
The simplest way of doing this (though not the fastest) would probably be to firstsprintfthe number to a string buffer, and then loop through the bufferprintf-ing one character and one space at a time. There's no built-in way of doing this within the standardprintfformatting.
I know in C++, you're able to peek at the next character by using:in.peek();. How would I go about this when trying to "peek" at the next character of a file in C?
fgetc+ungetc. Maybe something like this: ``` int fpeek(FILE *stream) { int c; c = fgetc(stream); ungetc(c, stream); return c; } ```
Are there any portable open source libraries that support sample-based synthesis and encapsulate producing and mixing simple PCMs? I really need something minimalistic and decoupled from operating system audio output mechanisms.
csoundhas aC apiand can handle PCM.ffmpegcan also convert lots of popular formats in PCM.
here is a code sample ``` void something() { char c[100]; scanf("%s",c); char c2[100]=c; } ``` my problem is when i do this assignment an error says that i can't assign ``` char * "c" to char[] "c2"; ``` how can i achieve this assignment?
You'll have to usestrcpy()(or similar): ``` ... char c2[100]; strcpy(c2, c); ``` You can't assign arrays using the=operator.
Does anyone know how to save gdb settings (like "set print pretty on" or "set print elements 0", both fromhere)? I don't want to set my configuration every time that I will use gdb :/ I searched in google and SO, but I found nothing.
Add any commands you want to auto run in the.gdbinitfile in your home directory.
How can I lock a file for a specified period of time (10 seconds) using the C language in Ubuntu Linux ?
It works like this: ``` #include <io.h> #include <sys/file.h> ... int f = open ("filename", O_RDONLY); if (f < 0) error(); if (flock (f, LOCK_EX)) error(); sleep (10); if (flock (f, LOCK_UN)) error(); ... ```
I am trying to add a new IP address to a local network adapter in Windows using the Windows API. Are there functions to do this in the Windows API, and if so, what are they? I am not trying to create virtual network adapters, but simply trying to assign multiple IP addresses to the same adapter.
Take a look atAddIPAddressandDeleteIPAddress.
A function returns an aray of integers and I want it to pass to another function which searches for some pattern. But the second function expects a string. Example: ``` int IArray = {1, 2, 3}; // should be coverted into "123" ``` Is there a direct function available? If not, how do I convert the array of integers into a string?
There is no direct function to do that. You'll have to usesprintf.
In C language, how to get struct's start address from its member's address? ``` struct type1 { //... int member1; //... }; struct type1 obj1; ``` Andptr1is the address of membermember1inobj1, how to definemacro#define start_add(ptr1, type1, member1)to get obj1'sstart address?
You can do this usingoffsetof: ``` #define start_add(ptr1, type1, member1) ((type1 *)((char *)(ptr1) - offsetof(type1, member1))) ```
I'm currently trying to patch theTotem Youtube plug-inand I'd like to determine the best quality available for the current played video (&fmt parameter). It's possible inJavaScriptbut the plug-in is developped in C. Is that possible?
Are you playing the videos in the YouTube video player? If so, you can query the quality levels through theActionScriptor JavaScript API, seehttp://code.google.com/apis/youtube/js_api_reference.html#Playback_quality.
Why does the following code compile? ``` #include <stdio.h> int main(void) { getchar; } ```
Because function names are aliases to function pointers to those functions, which are themselves values much like integers.. This is semantically very similar to ``` #include <stdio.h> int main(void) { 42; } ``` It is valid but pointless.
``` short sho1, sho2; printf("Enter two shorts.\n"); scanf("%hd %hd", &sho1, &sho2); printf("%hd^%hd is %hd.\n", sho1, sho2, sho1^sho2); ``` When I enter '2 2', I get this output: 2^2 is 0. How come? I'm using the MinGW GCC compiler in Eclipse, in case that's of any importance.
^is not the mathematical power operator in C, it's thebitwise exclusive-OR operator. You probably want thepow function, which takes two doubles.
Why does each .h file starts with #ifndef #define #endif? We can certainly compile the program without those directives.
It's a so-called "include guard". The purpose is to prevent the file from having to be parsed multiple times if it is included multiple times.
I recently came across this line in a code - ``` fprintf(logfile," |-IP Version : %dn",(unsigned int)iph->version); ``` Is "%dn" here a format string ? If so , what does it signify ?
It sounds a bit like someone wanted to write%d\nto terminate the line with a linefeed, but the backslash got lost somewhere. The format code, in any case, ends with the "d".
In C language, how to get struct's start address from its member's address? ``` struct type1 { //... int member1; //... }; struct type1 obj1; ``` Andptr1is the address of membermember1inobj1, how to definemacro#define start_add(ptr1, type1, member1)to get obj1'sstart address?
You can do this usingoffsetof: ``` #define start_add(ptr1, type1, member1) ((type1 *)((char *)(ptr1) - offsetof(type1, member1))) ```
I'm currently trying to patch theTotem Youtube plug-inand I'd like to determine the best quality available for the current played video (&fmt parameter). It's possible inJavaScriptbut the plug-in is developped in C. Is that possible?
Are you playing the videos in the YouTube video player? If so, you can query the quality levels through theActionScriptor JavaScript API, seehttp://code.google.com/apis/youtube/js_api_reference.html#Playback_quality.
When reading/writing a file in my application, I want to exit(1) if the file is not closed correctly. On Windows it works well, but on Linux this error appears: ``` ‘exit’ was not declared in this scope ``` How can I solve that? Thanks.
If this is in C, did you#include <stdlib.h>?
I can't figure out how to display something (like hello world) in every 3 seconds. I'm writing in only C programming with gcc compiler in linux. We can stop it by Ctrl+c. I just want simplest and easiest way to manipulate thet code with my project. Thank you so much in advance!
``` while(1) { printf("something\n"); Sleep(3000); //this function counts in milliseconds, so this is what 3 seconds looks like. } ```