question
stringlengths
24
425
answer
stringlengths
5
405
I have the following code to open a buffer in the memory and write some data to it: ``` int main() { char buf[1000] = {0}; FILE * os = fmemopen(buf, 1000, "w"); fprintf(os, "%d", 100); fclose(os); printf("%d\n", buf); return 0; } ``` The output is some random numbers such as :895734416or a negative number... why is this happening?
printf("%d\n", buf);output the address ofbufinstead of the return value.
this is a part of my little 'C' program... ``` printf("Time to sleep for the end of process: %d sec\n", getpid() % 10); ``` I would like to come down the seconds, without the line on the terminal changes. Like an animation. How can i do this in 'C'? Thanks everyone!
Replace your\nwith a\r, and as long as your numbers are all the same length (number of digits), I believe that should work.
I tried finding it but could not find the solution to this. I just want to know what does this mean in terms of return value. Does it mean that return value can be any of the 5 values present. Or the return value is all of these 5 numbers ``` static int is_navmsg(int msg) { return msg==1019||msg==1020||msg==1044||msg==1045||msg==1046; } ```
It will return1if the value ofmsgis1019or1020or1044and so on. Otherwise0.
I wrote a script for downloading a hdf5 file using libcurl, but I cannot find way to open it in c, I don't want to store it in disk and H5Fopen it. Is there a way to do the H5Fopen work on the downloaded memory buffer? Thanks:)
It is called File Image and you need recent HDF5 to do that: http://www.hdfgroup.org/HDF5/doc/Advanced/FileImageOperations/HDF5FileImageOperations.pdf
I wrote a script for downloading a hdf5 file using libcurl, but I cannot find way to open it in c, I don't want to store it in disk and H5Fopen it. Is there a way to do the H5Fopen work on the downloaded memory buffer? Thanks:)
It is called File Image and you need recent HDF5 to do that: http://www.hdfgroup.org/HDF5/doc/Advanced/FileImageOperations/HDF5FileImageOperations.pdf
I am trying to execute the following clearcase command through a c program. ``` system("ct pwv"); ``` But I'm getting this error. :permission denied. would you please suggest some solution to this problem. Thanks.
Try withcleartool: ``` system("cleartool pwv"); ```
I am trying to do this inc: ``` scanf("%d",a+i); ``` whereais an array of size10. Andiis counter for loop. So is this possible?
Absolutely: ifais anint*or an arrayint a[10], andiis between 0 and 9, this expression is valid. Thea+iexpression is the pointer arithmetic equivalent of&a[i], which is also a valid expression to pass toscanf.
Does OMP ensure that the contents of an dynamic array is up-to-date and is visible to all threads after an OMP barrier?
Yes. A barrier causes all threads' view of all accessible memory to be made consistent; that is, it implicitly flushes the entire state of the program.
How can i compile the contents of the clipboard, i tried piping the contentspbpaste | gccbut it did not work it gave the errori686-apple-darwin11-llvm-gcc-4.2: no input filesI have heard that i can use temporary file with the commandmktempbut I could not get it to work.
Using-xc -will allow you to processstdin: ``` gcc -xc - ``` You can see a live examplehere.
I'm currently writing a little program but I keep getting this error when compiling error: empty character constant I realize it's because I'm trying to replace a valid char with empty spacec[i]=''but I have not been able to find another way to represent it.
You can usec[i]= '\0'or simplyc[i] = (char) 0. The null/empty char is simply a value of zero, but can also be represented as a character with an escaped zero.
Can I use Goto to jump into other functions? for example ``` void x(){ printf("hello"); } void y(){ printf("hi"); } int main(){ /*assume that all var are declared */ scanf("%d",&input); if(input == 1) goto y(); else(input == 2) goto x(); } ```
You cannot usegototo branch into a different function; agotomay only branch within the current function. You would simplycallthe functionsx()andy().
I would like to check if I have openssl installed using C/C++ code. Is it even possible? I mean, is there a macro, or something which will be a portable way of doing this? Thanks
The following will work on Windows and Linux: ``` #ifdef WIN32 libHandle = LoadLibrary( libraryName ); #else libHandle = dlopen( libraryName, RTLD_LOCAL | RTLD_NOW ); #endif ```
In Java, it is required by the compiler to name your files<Classname>.java. In C, does it matter what the file name is?
No, the source files can in principle be called anything. However, the name should reflect the contents of the file for readability. Header files also don'thaveto be called the same as the corresponding source files; they justshould.
I would like to check if I have openssl installed using C/C++ code. Is it even possible? I mean, is there a macro, or something which will be a portable way of doing this? Thanks
The following will work on Windows and Linux: ``` #ifdef WIN32 libHandle = LoadLibrary( libraryName ); #else libHandle = dlopen( libraryName, RTLD_LOCAL | RTLD_NOW ); #endif ```
In Java, it is required by the compiler to name your files<Classname>.java. In C, does it matter what the file name is?
No, the source files can in principle be called anything. However, the name should reflect the contents of the file for readability. Header files also don'thaveto be called the same as the corresponding source files; they justshould.
This question already has answers here:C++ difference between 0 and 0.0(4 answers)C++: difference between 0. and 0.0?(5 answers)Closed10 years ago. I just saw this for the first time. The source code I'm looking at is in C ``` if( rate < 0.){ ... } else{ ... } ``` What happens ifrate=0?
0.is a literal of typedouble(and value zero). By contrast,0is a literal of typeint.
This question already has answers here:C++ difference between 0 and 0.0(4 answers)C++: difference between 0. and 0.0?(5 answers)Closed10 years ago. I just saw this for the first time. The source code I'm looking at is in C ``` if( rate < 0.){ ... } else{ ... } ``` What happens ifrate=0?
0.is a literal of typedouble(and value zero). By contrast,0is a literal of typeint.
This question already has answers here:How to achieve function overloading in C?(16 answers)Closed9 years ago. I need to develop a function in C that will be called with the same definition with or without parameters like this: ``` char *fnc(???) { char *str; .... return str; } char *c1 = fnc(); char *c2 = fnc(param); ``` How to do it?
This is calledFunction OverloadingYou can't do it in C
I have a webpage, say atwww.mypage.com, which uses$_GETto fetch data and then saves the fetched data into theMySQLdatabase. I need to send thisHTTP Requestfrom a Cpp File. How can I send aHTTP Requestfrom Cpp file?
Yes, libcurl should be helpful. You can send some data by GET parameters or by POST and read responses. (Maybe necessary to verify a successful transmission) Here are some examples:http://curl.haxx.se/libcurl/c/example.html
I have a webpage, say atwww.mypage.com, which uses$_GETto fetch data and then saves the fetched data into theMySQLdatabase. I need to send thisHTTP Requestfrom a Cpp File. How can I send aHTTP Requestfrom Cpp file?
Yes, libcurl should be helpful. You can send some data by GET parameters or by POST and read responses. (Maybe necessary to verify a successful transmission) Here are some examples:http://curl.haxx.se/libcurl/c/example.html
A short example excerpted from wdm.h ``` typedef struct _KMUTANT { DISPATCHER_HEADER Header; LIST_ENTRY MutantListEntry; struct _KTHREAD *OwnerThread; BOOLEAN Abandoned; UCHAR ApcDisable; } KMUTANT, *PKMUTANT, *PRKMUTANT, KMUTEX, *PKMUTEX, *PRKMUTEX; ``` I know 'P' means 'Pointer', but I don't know what 'R' means. Any interpretation?
TheRidentifies the pointer as arestricted pointer.
A short example excerpted from wdm.h ``` typedef struct _KMUTANT { DISPATCHER_HEADER Header; LIST_ENTRY MutantListEntry; struct _KTHREAD *OwnerThread; BOOLEAN Abandoned; UCHAR ApcDisable; } KMUTANT, *PKMUTANT, *PRKMUTANT, KMUTEX, *PKMUTEX, *PRKMUTEX; ``` I know 'P' means 'Pointer', but I don't know what 'R' means. Any interpretation?
TheRidentifies the pointer as arestricted pointer.
A short example excerpted from wdm.h ``` typedef struct _KMUTANT { DISPATCHER_HEADER Header; LIST_ENTRY MutantListEntry; struct _KTHREAD *OwnerThread; BOOLEAN Abandoned; UCHAR ApcDisable; } KMUTANT, *PKMUTANT, *PRKMUTANT, KMUTEX, *PKMUTEX, *PRKMUTEX; ``` I know 'P' means 'Pointer', but I don't know what 'R' means. Any interpretation?
TheRidentifies the pointer as arestricted pointer.
I have a daemon process namedmydaemon. Now I want to have an other process to send something for me , and when I fork a child process , it has the same name with the parent process. How can I have a different process name withoutexecfunction?
Under Linux you can use theprctl()function to set the process name: ``` #include <sys/prctl.h> prctl(PR_SET_NAME, "foobar"); ```
I am a beginner C coder and I want to know how the make it so the program will do this. ``` printf("which direction would you like to go?\n"); /*they type an arrow key*/ printf ("you went left/right/up/down\n"); ``` I have a Mac
Try these suggestions. You can get the ASCII codes by getch()
I'm trying to understand what's wrong with: ``` typedef *void (*pfun)(**int, *float); ``` as far as I understand the problem is that I can't pass the function the pointers as ``` typedef *void (*pfun)(int, float); ``` doesn't generate an error but I have no idea why that is the case.
Did you meanvoid*,int**andfloat*?
I need to print aULONGLONGvalue (unsigned __int64). What format should i use inprintf? I found%lluin another question but they say it is for linux only. Thanks for your help.
Using Google to search for “Visual Studio printf unsigned __int64” producesthis pageas the first result, which says you can use the prefixI64, so the format specifier would be%I64u.
After you have opened a file using: ``` const char *fMode = "r"; FILE *filePointer = fopen(location,fMode); ``` What's the fastest cross platform (Windows and Linux) way to get its size so you can allocate the right amount of memory usingmalloc? I've seen thatftellonly works if you open the file in binary mode.
You can find the size usingstatorfstatbefore you open the file.
Is it possible to stop an io buffer from flushing itself in C/C++? To get maximum performance, I'm trying to save data and then flush after an operation is complete. I can just write to an array and then print that out later, I was just wondering if this is possible.
You can increase the size of the buffer by using a call tosetvbuf.
When I simply pass the int I get the warning: WARNING: Incompatible integer to pointer conversion passing int to parameter of type int * In another words what isint *
This requires theaddressof an integer variable, not the integer variable itself. You can get the address of a variable with the&operator. So the following code would work: ``` int i = 10; wait( &i ); ```
When I simply pass the int I get the warning: WARNING: Incompatible integer to pointer conversion passing int to parameter of type int * In another words what isint *
This requires theaddressof an integer variable, not the integer variable itself. You can get the address of a variable with the&operator. So the following code would work: ``` int i = 10; wait( &i ); ```
This question already has answers here:Declaring a C function to return an array(5 answers)Closed10 years ago. How can one have a function returning a pointer to an array and what are the general things that one needs to keep in mind while doing that?
``` int (*foo(void))[4]; ``` declaresfooas a function with no parameters that returns a pointer to an array 4 ofint. For example: ``` int (*p)[4]; p = foo(); ```
Why doesn't the following line of code produce an error? ``` double x = 4.2, y; ``` Also, x seems to be assigned to 4.2, and not the value of y (which seems to be 1e-39, or very close to 0).
It does the same as: ``` double x = 4.2; double y; ``` The "y" variable contains some junk value (since its value is unspecified) until you give it a value. It acts this way because the comma operator has lower precedence than assignment in C/C++.
I have written an openssl program, and now I want to know, if the openssl library calls its own cleanup functions, or if I have to call myself the cleanup functions like SSL_CTX_free and SSL_free?
You have to explicitly call the cleanup functions. I recommend using Valgrind in order to track memory leaks in your program.
I have written an openssl program, and now I want to know, if the openssl library calls its own cleanup functions, or if I have to call myself the cleanup functions like SSL_CTX_free and SSL_free?
You have to explicitly call the cleanup functions. I recommend using Valgrind in order to track memory leaks in your program.
My machine is a Windows 8 machine. I want to read the "UpperFilters" key fromHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{36fc9e60-c465-11cf-8056-444553540000}from my custom driver to get the presence of filter drivers over USB devices.
I haven't written a driver since the days of XP, but assuming you're talking about a kernel mode driver I belive you wantZwOpenKey,ZwQueryValueKeyandZwClose. General guidancehere.
I need to create a C compatible (friendly) return type so that my C++ functions can be used to work with C-based functions. How I can convert a vector ofwstringto awchar_t**array?
You can iterate through the wstring vector and add eachwstring::c_str()to yourwchart_t**array.
I need to create a C compatible (friendly) return type so that my C++ functions can be used to work with C-based functions. How I can convert a vector ofwstringto awchar_t**array?
You can iterate through the wstring vector and add eachwstring::c_str()to yourwchart_t**array.
What is the height of a complete binary tree with N nodes? I'm looking for an exact answer, and either a floor or ceiling value.
It'sCEIL(log2(n+1))-1 1 node gives log2(2) = 13 nodes gives log2(4) = 27 nodes gives log2(8) = 315 nodes gives log2(16) = 4... EDIT: According to wikipedia, the root node (rather un-intuitively?) does not count in the height, so the formula would beCEIL(log2(n+1))-1.
In a gcc makefile, you can use the -D flag to specify a define in the compiled program. For example, instead of putting #define SOMETHING, you can specify -DSOMETHING in the makefile. What is the equivalent of this in SCons?
I believe you want theCPPDEFINESconstruction variable. Seethe SCons documentation pagefor some more details, underCPPDEFINES.
I am running the below code but getting no output on console screen. Please Explain: ``` #include <stdio.h> void main() { enum days {sun,mon,tue,wed,thru,fri,sat}; } ```
``` #include <stdio.h> int main() { printf("sun, mon, tue, wed, thru, fri, sat\n"); return 0; } ``` Is that what you were trying to do?
I am running the below code but getting no output on console screen. Please Explain: ``` #include <stdio.h> void main() { enum days {sun,mon,tue,wed,thru,fri,sat}; } ```
``` #include <stdio.h> int main() { printf("sun, mon, tue, wed, thru, fri, sat\n"); return 0; } ``` Is that what you were trying to do?
This question already has answers here:How to escape the % (percent) sign in C's printf(13 answers)Closed7 years ago. Why doesn't this program print the%sign? ``` #include <stdio.h> main() { printf("%"); getch(); } ```
Your problem is that you have to change: ``` printf("%"); ``` to ``` printf("%%"); ``` Or you could use ASCII code and write: ``` printf("%c", 37); ``` :)
``` #include<stdio.h> void main() { float a = 5, b = 2; int c; c = a % b; printf("%d", c); } ``` I am getting floating point error n this program-me..someone please explain this..
You can only use%operator with integer operands. Usefmodfunction (declared inmath.h) for floating point operands.
Is there a way to typedef a 2 dimensional array in C? Something like: ``` typedef char[10][10] board; ``` This example doesn't compile. Is there any way to do it? Or any other solution?
Try this: ``` typedef char board[10][10]; ``` Then you can define new array as this: ``` board double_array = {"hello", "world"}; ``` It's the same with: ``` char double_array[10][10] = {"hello", "world"}; ```
Why do GTK+ and several other frameworks provideTRUEandFALSEmacros? Is there any advantage to usingTRUEandFALSEinstead of the built-in C valuestrueandfalse? You can see their implementation here:http://www.gtk.org/api/2.6/glib/glib-Standard-Macros.html#TRUE:CAPS
C99 hastrueandfalse, earlier versions do not. That is why you often seeTRUEandFALSE#defined. As you can readhere,trueandfalseare1and0respectively, same asTRUEandFALSE.
I compiled a C program (which has some assembly language instructions) like this. ``` TCC -Emasm.exe protect.c ``` It gives an errorUnable to execute masm.exe. What should I do or where can I findmasm.exe?
You need to get microsoft assembly compiler, which is called masm.
I have variable that must be 16 bit long. How should I define it to be exactly 16 bit independently on the platform? I can define it asshort, but depending on the platform it can be 16 bits or more.
Assuming you're using C99, then useuint16_t(orint16_t) from<stdint.h>. These are guaranteed to exist so long as the compiler has an underlying 16-bit type available.
I've two functions: ``` void foo0(int bar); void foo1(int bar); ``` I wan't to be able create a macroQUXthat will expand to these function names based on another macroBAZ. I tried the following: ``` #define BAZ 0 #define QUX(x) foo##BAZ(x) ``` But it did not work since the generated function wasfooBAZ(). How can I get it to generatefoo0()?
``` #define CAT_I(a,b) a##b #define CAT(a,b) CAT_I(a, b) #define QUX(x) CAT(foo, BAZ) ## (x) ```
While I examine the source code of ffmpeg, I see this line: ``` enum AVDurationEstimationMethod av_fmt_ctx_get_duration_estimation_method (const AVFormatContext* ctx); ``` What is the functionality ofenumhere?
av_fmt_ctx_get_duration_estimation_methodis a function which returns an object of enum typeAVDurationEstimationMethod.
I have read about usingsampler2DRectandtexture2DRectto use rectangular textures. My question is whether its use is recommended for creating sprites 2D using GLSL, or if there is another alternative to using images that are not necessarily a power of two.
If all you need arenon-power-of-two textures, that's something OpenGL has supported foralltexture types since GL 2.0. So you don't need rectangle textures if NPOTs are all you want.
This question already has answers here:Is a += b more efficient than a = a + b in C?(7 answers)Closed10 years ago. what is the difference betweeni = i + j; andi += j; in C? Are they equivalent? Is there any side effect ofi? I was trying to check the assignment mechanism in C using the GCC compiler.
They're almost the same. The only difference is thatiis only evaluated once in the+=case versus twice in the other case.
I have read about usingsampler2DRectandtexture2DRectto use rectangular textures. My question is whether its use is recommended for creating sprites 2D using GLSL, or if there is another alternative to using images that are not necessarily a power of two.
If all you need arenon-power-of-two textures, that's something OpenGL has supported foralltexture types since GL 2.0. So you don't need rectangle textures if NPOTs are all you want.
This question already has answers here:Is a += b more efficient than a = a + b in C?(7 answers)Closed10 years ago. what is the difference betweeni = i + j; andi += j; in C? Are they equivalent? Is there any side effect ofi? I was trying to check the assignment mechanism in C using the GCC compiler.
They're almost the same. The only difference is thatiis only evaluated once in the+=case versus twice in the other case.
Can someone explain how we calculate the value of Hexadecimal Floating point constant. I was reading a book and found 0x0.3p10 represents the value 192.
The exponent is still expressed in decimal, but the base is two, and the mantissa is in hex. So 0.3P10 is (3 × 16−1) × 210, which is 3/16 × 210, which is 3 × 26= 192. Each hex digit of the mantissa gobbles up four units of exponent, since 16 = 24.
I have a long list of variable for private and share. How do I write in multiple lines? I am repeating the question here, just because stackoverflow wouldn't let me submit the question otherwise.
Pragmas are interpreted by the compiler after preprocessing, so you can just use the normal line-continuation mechanism: ``` #pragma omp parallel ``` can become: ``` #pragma \ omp \ parallel ```
``` #include<stdio.h> #include<stdlib.h> void main(){ exit(0); } ``` This is my code in c how could I make the console exit??I have tried to use the exit function but it seems like it doesn't work
exitcausesyour programto exit, not the shell that you ran it from. Your program is equivalent to: ``` int main(void) { return 0; } ``` You might want to look intokill(2). Editorial note:mainshould returnint, notvoid.
I have a function that returns me a string asconst char *: ``` const char* get_text(); ``` I need to call a functionAfxMessageBox(LPCTSTR text). How can I convert the string that I got byget_text()?
As you're using MFC and assuming a UNICODE build (or you wouldn't have this error!), probably the simplest way is to instantiate awchar_tcompatibleCStringdirectly: ``` CStringW szWide(getText()); AfxMessageBox(szWide); ```
I have a long list of variable for private and share. How do I write in multiple lines? I am repeating the question here, just because stackoverflow wouldn't let me submit the question otherwise.
Pragmas are interpreted by the compiler after preprocessing, so you can just use the normal line-continuation mechanism: ``` #pragma omp parallel ``` can become: ``` #pragma \ omp \ parallel ```
I want to type "man time" and info about thetime.htime function, but instead I am getting the linux time system command. man time 2orman time 3doesn't do any different. How can I find the right man page?
How aboutman man? Then you would find out thatman 3 timeworks.
can anyone tell me how to install opencv2.4.6 using cmake, I found several tutorials but I can't find the common folder inc:\opencv\build_common_ ** to past the **tbb41_20130613ossfolder any idea can I do that. thanks in advance
You need to build the library, and then execute targetinstall. When usingmakeit will be ``` make make install ``` On visual studio You need to select the targets manually (I think).
All is in the title. How to check a possible overflow when using the two functions exp() and log()?
``` #include <errno.h> ``` When an oferflow occurs, thenerrnois set toERANGE. Next time, do your homework before asking. Googling: "c++ exp" returned this as the first resulthttp://www.cplusplus.com/reference/cmath/exp/In the middle of the page, there is EXACTLY what you're looking for.
All is in the title. How to check a possible overflow when using the two functions exp() and log()?
``` #include <errno.h> ``` When an oferflow occurs, thenerrnois set toERANGE. Next time, do your homework before asking. Googling: "c++ exp" returned this as the first resulthttp://www.cplusplus.com/reference/cmath/exp/In the middle of the page, there is EXACTLY what you're looking for.
I've got an array of sixuint16_twhich is actually threeuint32_t, with the bits in the right order and all. How can I cast the former to the latter as effectively as possible? The number of elements in the array is known at compile-time.
Like this perhaps: ``` uint16_t arr16[6]; uint32_t *parr32 = (uint32_t*)(&arr16); ``` And now you can useparr32[i]to refer to elements of the overlayedarr16array.
This question already has answers here:What is the difference between NULL, '\0' and 0?(11 answers)Closed10 years ago. As far as i know, the NULL is actually not 0. So is there any difference in comparing a pointer with 0 or with NULL? Further what should be the correct usage. Thanks!
The correct usage is to useNULL: It's more readable (p == NULL-> you know thatpis a pointer)
In a boot loader code i found that, they are using volatile keyword when accessing physical address. Is it necessary to use volatile keyword even we are accessing physical memory address?
You need to use "volatile" whenever the data can change, without the compiler being able to know about it.
I am having some problem with Coderunner. It was running with out any problem but now it is not.As you see in image below. Please, can you help me to resolve this problem. Thanks!http://yadi.sk/d/tDkp1K8v6aeby
Did you uninstall Xcode, or upgrade your OS recently ? Because Coderunner need Command Line Tool to work properly. How to install Command Line Tool for Lion and above.
This question already has answers here:What is the difference between NULL, '\0' and 0?(11 answers)Closed10 years ago. As far as i know, the NULL is actually not 0. So is there any difference in comparing a pointer with 0 or with NULL? Further what should be the correct usage. Thanks!
The correct usage is to useNULL: It's more readable (p == NULL-> you know thatpis a pointer)
In a boot loader code i found that, they are using volatile keyword when accessing physical address. Is it necessary to use volatile keyword even we are accessing physical memory address?
You need to use "volatile" whenever the data can change, without the compiler being able to know about it.
I am having some problem with Coderunner. It was running with out any problem but now it is not.As you see in image below. Please, can you help me to resolve this problem. Thanks!http://yadi.sk/d/tDkp1K8v6aeby
Did you uninstall Xcode, or upgrade your OS recently ? Because Coderunner need Command Line Tool to work properly. How to install Command Line Tool for Lion and above.
Suppose I have dynamically allocated variables in the program run by the debugger, is it safe to press the stop button of the IDE or stop the debugger? I mean safe...will the variables get deleted/deallocated?
Yes. It is safe. When a program exits, all the allocated resources returned to the operating system.
So I'm writing a Unix shell in C, and have been encountering a race condition. I've determined that I can resolve it if, after one of my Fork() calls, I can ensure the parent runs before the child. Is there any way that I can do that using signaling or any other type of inter-process communication?
You could set up a signal handler and let the child wait for it, e.g. SIGUSR1.
Using plain C, (not C++ / C# / Objective-C) how do I get the screen resolution in Windows? My compiler is MingW (not sure if relevant). All solutions I have found online are for C++ or some other C variant.
UseGetSystemMetrics() ``` DWORD dwWidth = GetSystemMetrics(SM_CXSCREEN); DWORD dwHeight = GetSystemMetrics(SM_CYSCREEN); ```
Suppose I have dynamically allocated variables in the program run by the debugger, is it safe to press the stop button of the IDE or stop the debugger? I mean safe...will the variables get deleted/deallocated?
Yes. It is safe. When a program exits, all the allocated resources returned to the operating system.
I was trying this code: ``` int main() { char *ch="hello"; printf("%u",&ch); return 0; } ``` From the aboveprintf()statement I have address of ch i.e65524My question is Can i find value if any address is given like*(65524)rather than*(&ch)?
Yes, you can: ``` printf("%d\n", *(unsigned char *) 65524); ``` If the address does not point to a valid object, you are invoking undefined behavior.
I'm having to do the following a lot in a USB (libusb) C based command line utility I am writing: ``` char pid[20]; sprintf(pid, "Product ID : %#06x", anInteger); puts(pid); ``` Is there a shorter, one-liner way to do this?
Instead of usingsprintf&puts, just change toprintf: ``` printf("Product ID : %#06x", descriptor.idVendor); ```
why do i get a kernel crash ofcpuacct_chargewhen i try to allocate 600 blocks of 2 MB memory using -pci_alloc_consistent, is there a better way to do it ?
You are probably running out of 32-bit-addressable memory. If your PCIe chip actually supports larger addresses, your driver should usedma_set_maskanddma_set_consistent_maskto tell the kernel about this. (SeeDocumentation/DMA-API-HOWTO.txt.)
I have this byte:10111011and i want to split into 2 nibble (msb and lsb).After that i want to take the last 2 bits from the lsb (so i want11from1011).I know that:With10011011 >> 4i get the msb (1001)With10011011 & 0xfi get the lsb (1011)Now what can i do to take the11from lsb1011?
Just the same:bits = lsb & 0x03
I'm having to do the following a lot in a USB (libusb) C based command line utility I am writing: ``` char pid[20]; sprintf(pid, "Product ID : %#06x", anInteger); puts(pid); ``` Is there a shorter, one-liner way to do this?
Instead of usingsprintf&puts, just change toprintf: ``` printf("Product ID : %#06x", descriptor.idVendor); ```
why do i get a kernel crash ofcpuacct_chargewhen i try to allocate 600 blocks of 2 MB memory using -pci_alloc_consistent, is there a better way to do it ?
You are probably running out of 32-bit-addressable memory. If your PCIe chip actually supports larger addresses, your driver should usedma_set_maskanddma_set_consistent_maskto tell the kernel about this. (SeeDocumentation/DMA-API-HOWTO.txt.)
I have this byte:10111011and i want to split into 2 nibble (msb and lsb).After that i want to take the last 2 bits from the lsb (so i want11from1011).I know that:With10011011 >> 4i get the msb (1001)With10011011 & 0xfi get the lsb (1011)Now what can i do to take the11from lsb1011?
Just the same:bits = lsb & 0x03
Is there any specific function or any way by which the number of lines in aGDBMfile can be counted?Otherwise, I want to retrieve all the lines in aGDBMfile at once(Iam able to retrieve the key value pairs usinggdbm_fetch()but only one at a time.
I got the solution to the above problem. Now I am able to retrieve all the key value pairs. Solution :here
Is there any specific function or any way by which the number of lines in aGDBMfile can be counted?Otherwise, I want to retrieve all the lines in aGDBMfile at once(Iam able to retrieve the key value pairs usinggdbm_fetch()but only one at a time.
I got the solution to the above problem. Now I am able to retrieve all the key value pairs. Solution :here
Is ``` *(ary[3]+8) ``` and ``` ary[3][8] ``` are the same ? If yes, please explain how ? ary[3] returns the address of first element or the value in ary[3][0] ? ary is a two dimensional array. Thanks in advance.
Yes a[i]is same as*(a+i) ary[i][j]is same as*( *(ary+i)+j))
I am trying to show user a text file after an operation completed in a c program using winapi but I want the file to be opened using notepad (or the default text processor application). how do I do this (opening a text file using window's default application) using winapi?
ShellExecute()is what you are looking for, eg: ``` #include <shellapi.h> ShellExecute(NULL, NULL, "C:\\path\\to\\myfile.txt", NULL, NULL, SW_SHOWNORMAL); ```
Where are the options forcurl_easy_setoptdefined? I'm trying to look for the integer values of CURLOPT_VERBOSE and some others, but these don't seem to be explicitly defined incurl.h
Line 792: ``` #ifdef CURL_ISOCPP #define CINIT(na,t,nu) CURLOPT_ ## na = CURLOPTTYPE_ ## t + nu ``` line 953: ``` CINIT(VERBOSE, LONG, 41), /* talk a lot */ ``` There it is.
Is ``` *(ary[3]+8) ``` and ``` ary[3][8] ``` are the same ? If yes, please explain how ? ary[3] returns the address of first element or the value in ary[3][0] ? ary is a two dimensional array. Thanks in advance.
Yes a[i]is same as*(a+i) ary[i][j]is same as*( *(ary+i)+j))
I am trying to show user a text file after an operation completed in a c program using winapi but I want the file to be opened using notepad (or the default text processor application). how do I do this (opening a text file using window's default application) using winapi?
ShellExecute()is what you are looking for, eg: ``` #include <shellapi.h> ShellExecute(NULL, NULL, "C:\\path\\to\\myfile.txt", NULL, NULL, SW_SHOWNORMAL); ```
Was there any site that compares the current C11 standard conformance/support between implementation/compilers? (gcc, clang, intel, open64, pelles)
To my knowledge there is no general site (this is a good time to start one :). However, most projects maintain their own list: http://clang.llvm.org/cxx_status.html(clang)http://clang.llvm.org/compatibility.html#c http://gcc.gnu.org/wiki/C11Status(gcc)
Was there any site that compares the current C11 standard conformance/support between implementation/compilers? (gcc, clang, intel, open64, pelles)
To my knowledge there is no general site (this is a good time to start one :). However, most projects maintain their own list: http://clang.llvm.org/cxx_status.html(clang)http://clang.llvm.org/compatibility.html#c http://gcc.gnu.org/wiki/C11Status(gcc)
Is it possible to form a two way link between structs? I tried to achieve it like this: ``` typedef struct { int foo; b *b; } a; typedef struct { int bar; a *a; } b; ``` But the struct a does not know what b is because it's declared afterwards.
Try this, ``` typedef struct a a; typedef struct b b; struct a { int foo; b *b; } ; struct b { int bar; a *a; } ; ```
Would some please tell me why this code leads to such an error? ``` unsigned char buffer; fread(&buffer,1,1,image_ptr); printf("%s ",buffer); ``` The image is 8-bit grayscale. Thank you.
%sis the format specifier to print a string, butbufferis not a string. That causes undefined behaviour. You want%cor maybe%uor%xdepending on what you want as output.
I can use display list + glsl? something like using vbo + glsl. if this can be, you can write an example.
Well in terms of OpenGL-2, yes you can use GLSL shaders on geometry drawn through a display list that was compiled from immediate mode calls. The question is: Why would you want to do this? OpenGL-3 removed display lists (good riddance). So don't expect it to work for any GLSL version beyond 1.2x.x
I have two functions: ``` void a(int * p); int b(); ``` Is it possible to pass the address of the return value of functionbto functionasomething like this:a(&b())?
A compound literal seems to do the trick (requires a C99 compiler): ``` int a() { return 5; } void b(int *a) { // do something with a printf("%d\n", *a); } int main(void) { b(&(int){ a() }); } ``` Output is5.
``` ( s1[i] = s2[i] ) != '\0' ``` Does the inequality checks2[i]with'\0'ors1[i]?
s2[ i ]will be assigned tos1[ i ]and then value ofs1[ i ]will be compared against ZERO. Pleaserefer herefor more info.
I have two functions: ``` void a(int * p); int b(); ``` Is it possible to pass the address of the return value of functionbto functionasomething like this:a(&b())?
A compound literal seems to do the trick (requires a C99 compiler): ``` int a() { return 5; } void b(int *a) { // do something with a printf("%d\n", *a); } int main(void) { b(&(int){ a() }); } ``` Output is5.
``` ( s1[i] = s2[i] ) != '\0' ``` Does the inequality checks2[i]with'\0'ors1[i]?
s2[ i ]will be assigned tos1[ i ]and then value ofs1[ i ]will be compared against ZERO. Pleaserefer herefor more info.
I have a Python code calling some C code (.so file). Is there a way, from within the C code, go get the line number it has been called from at the Python side?
I eventually found thePyFrame_GetLineNumber(PyFrameObject *f)C function, whose source is located inframeobject.c.
I'm creating a camera driver for Android. I've got my mydriver.c file. Apparently I need to compile it into a .ko, is that right ? And then to load it I should do a#insmod ./mymodule.ko, will it work ? Do I need to be root ? And how I put the .ko file on my Android tablet ?
Yes, you need to be root. And, insmod ./yourmodule.ko should work fine.
I would like to ask if there is any fast way(using memset for example) to clear a char table like ``` char mytable[2][10]; ``` For example as I know using memset ``` memset(mytable, 0, sizeof(mytable)); ``` is used for 1D tables.
They're calledarrays,not "tables". And thevery same code worksfor any array with arbitrary number of dimensions.