question
stringlengths
24
425
answer
stringlengths
5
405
I am using C. Say I have a pointer to a integer called *myptr int *myptr; What would then be the difference between: ``` *myptr++ ``` and... ``` *(myptr++) ``` Thanks Dan
Since++has higher precedence than*, there isno differencebetween the two.
I am using C. Say I have a pointer to a integer called *myptr int *myptr; What would then be the difference between: ``` *myptr++ ``` and... ``` *(myptr++) ``` Thanks Dan
Since++has higher precedence than*, there isno differencebetween the two.
In windows I can callLogonUserWor on linuxpam_authenticateto check whether a given username/password is correct. How do I do this on OS X (for c/c++)?
Take a look atthis: PAM is a pluggable authentication and authorization library for *nix based systems – think Linux, FreeBSD and evenMac OS X....
This is more just a question of interest - I'm not sure how it would actually be applicable. Anyways - is it possible using bit-checks to see if a number is equal to 1?
I am not sure what exactly the questions is, but you can use either!(x ^ 1)orx == 1or!(x-1)or(x & 1) && !(x & ~1)or one of many other ways.
This is more just a question of interest - I'm not sure how it would actually be applicable. Anyways - is it possible using bit-checks to see if a number is equal to 1?
I am not sure what exactly the questions is, but you can use either!(x ^ 1)orx == 1or!(x-1)or(x & 1) && !(x & ~1)or one of many other ways.
I am creating an alarm clock for my project in C. I am using mgp123 command(in package mpg321) to run the alarm sound. It is only for UBUNTU users.I need the program to check whether mpg321 is installed or not. How can i find using C if the package mpg321 is installed using C program?
you can usesystem() ``` system("mpg321 -h"); ``` if the command return error than thempg321is not installed
I want to translate my GTK+ application written in C++. I don not have any ideas where to start, I heard about gettext(), but I don't know, how should I use it.
Take a look athttps://developer.gnome.org/gtk3/stable/gtk-question-index.htmlpage, in 1.7. paragraph they explain how you can translate your applications usingGNU gettext.
I can't find out why crt0.o or crt1.o are not provided for i386 targets by newlib as it is the case for powerpc, arm, etc. targets. ld requires it (and so do I to call static constructors).
Question directly asked on newlib's mailing list:http://sourceware-org.1504.n7.nabble.com/Question-i386-s-crt0-tp229290p229999.html
``` Display *display; display = XOpenDisplay(NULL); Window window; XGetInputFocus(display, &window, RevertToNone); ``` in XGetInputFocus segmentation fault happen; anything wrong ? (program compile with xlib and don't any problem with compiling)
int revert; XGetInputFocus(display, &window, &revert);should fix it.
``` Display *display; display = XOpenDisplay(NULL); Window window; XGetInputFocus(display, &window, RevertToNone); ``` in XGetInputFocus segmentation fault happen; anything wrong ? (program compile with xlib and don't any problem with compiling)
int revert; XGetInputFocus(display, &window, &revert);should fix it.
I am getting some errors. Any clues where I am going wrong? I think I am applying the right logic. ``` int* adderFunction(int a, int b) { int result; int *pResult; pResult = &result; result = a + b; return (pResult); } ```
No. You are trying to return pointer on local variable, which is destructed after return from function.
What are the equivalent for java byte in C,C++ ``` byte[] itemsArray; itemsArray = new byte[items *no]; itemsArray[x] = (byte) xyz; unsigned char * itemsArray; itemsArray = (unsigned char*) malloc (items*no); ``` How to assign bytes toitemsArray(likeitemsArray[x] = (byte) xyz) in C++ with endianess to ensure the proper byteorder. Are the above things equivalent to byteArray in C ?
Usememcpy()to copy buffers between memories inC.
I am trying to disable sse and sse2 instructions. I am cross compiling for x86 in a x64 system. I am also using -static to statically link with libc. Although I use -mno-sse and -mno-sse2, when I disassemble the binary I still see a call to strcpy_sse2, any solution?
For 64 bit Use -mno-sse gcc option
I am trying to disable sse and sse2 instructions. I am cross compiling for x86 in a x64 system. I am also using -static to statically link with libc. Although I use -mno-sse and -mno-sse2, when I disassemble the binary I still see a call to strcpy_sse2, any solution?
For 64 bit Use -mno-sse gcc option
I have a program that need to read one line from file everytime when it receives a signal SIGUSR2. I made everything except how to read exactly one line. The content of the file: ``` one two three four five ... ten ```
usefgets()function....it will read until newline come...or else u can read one char by one char by using fgetc when u get /n then u can end ur operation of reading
I have a program that need to read one line from file everytime when it receives a signal SIGUSR2. I made everything except how to read exactly one line. The content of the file: ``` one two three four five ... ten ```
usefgets()function....it will read until newline come...or else u can read one char by one char by using fgetc when u get /n then u can end ur operation of reading
How can compare a string for matching a special format in c? I want to check whether a string match to "PCn.Value". ie. It must match PC1.value, PC2.value,...
sscanf()could help ``` char S[32]; if (sscanf(str, "PC%[0-9].Valu%1[e]%c", S, &S[30], &S[30])==2) ```
How can compare a string for matching a special format in c? I want to check whether a string match to "PCn.Value". ie. It must match PC1.value, PC2.value,...
sscanf()could help ``` char S[32]; if (sscanf(str, "PC%[0-9].Valu%1[e]%c", S, &S[30], &S[30])==2) ```
Some apps on the gnome desktop like the image viewer use a dark variation of the theme. What code is required to make my own gtk program use this dark variation of the theme?
Use thegtk-application-prefer-dark-themesetting. This ought to do it: ``` g_object_set(gtk_settings_get_default(), "gtk-application-prefer-dark-theme", TRUE, NULL); ``` You may need to make sure you do it before you create any widgets.
chdir("~/")doesn't seem to work. Am I expected to look at the string and substitute tilde by hand, or is there some better way?
POSIX provideswordexp(3)to perform shell-like expansion, including tilde expansion.
``` #include <stdlib.h> int main(void) { int* x; int* y; x = malloc(sizeof(int)); *x = 42; *y = 13; y = x; return 0; } ``` Where is the Error in which line and why.. ? Can't I assign pointer to another pointer. Yes nothing is being printed out in this .. Actually its my homework question...
You need to allocate memory forybefore assigning value to it. ``` y = malloc(sizeof(int)); *y = 13 ```
Is there any c library that deals with utf8, usingchar*?In particular, for all thechar*, we will use utf8 compatible functions to deal with them:counting length, comparing, find & replace, concatenation, toupper tolower etc.There is no need to deal with conversion.
... then theICU libraryis just what you need.
Can I use the msleep() function to sleep for a specified amount of time in kernel space? If so, which header files do I need to include?#include <linux/time.h>doesn't seem to be the right one. Is there perhaps a better function for this purpose?
I needed to include<linux/delay.h>to use msleep in kernel space.
chdir("~/")doesn't seem to work. Am I expected to look at the string and substitute tilde by hand, or is there some better way?
POSIX provideswordexp(3)to perform shell-like expansion, including tilde expansion.
``` #include <stdlib.h> int main(void) { int* x; int* y; x = malloc(sizeof(int)); *x = 42; *y = 13; y = x; return 0; } ``` Where is the Error in which line and why.. ? Can't I assign pointer to another pointer. Yes nothing is being printed out in this .. Actually its my homework question...
You need to allocate memory forybefore assigning value to it. ``` y = malloc(sizeof(int)); *y = 13 ```
This is purely out of interest. I searched around a bit, knowing that instances ofclassesare calledobjects, but I couldn't find what the correct word is for an instance of astructin C, C++, C#, etc. Do we even have a word for this?
It is perfectly valid to call it an object even in C. C99 Standard §3.15:Para 1: objectregion of data storage in the execution environment, the contents of which can represent values
This is purely out of interest. I searched around a bit, knowing that instances ofclassesare calledobjects, but I couldn't find what the correct word is for an instance of astructin C, C++, C#, etc. Do we even have a word for this?
It is perfectly valid to call it an object even in C. C99 Standard §3.15:Para 1: objectregion of data storage in the execution environment, the contents of which can represent values
Let's say I have achar*called code, and it has"0x41"in it. ``` char *code = "0x41"; ``` How can I convert that into anunsigned int? (To be exact, I need aWORD, but that's just anunsigned int).
``` unsigned int h; sscanf(code, "%x", &h); ``` EDITtaking account of the remark ofExP:%xcould catch the value in the string"0x41"
Let's say I have achar*called code, and it has"0x41"in it. ``` char *code = "0x41"; ``` How can I convert that into anunsigned int? (To be exact, I need aWORD, but that's just anunsigned int).
``` unsigned int h; sscanf(code, "%x", &h); ``` EDITtaking account of the remark ofExP:%xcould catch the value in the string"0x41"
I want to hook the functionAudioUnitInitializeto grab the Audio Unit of an application by injecting a bundle at the application start.I found an example (http://pastie.org/1882125) but it uses the functionMSHookFunctionto replace the function names. The problem is that I want to replace the functions on Mac OS X, not on iOS.Is there another way to hook C functions?
If youlook closely, you can find out that MobileSubstrate runs on OS X as well.
does anyone know how to display the percentage%character in an ncurses-based C++ / C=based program? I have tried using\x25and%, but they do not work.
You should be able to escape the%with an extra%: ``` %% ```
I want to hook the functionAudioUnitInitializeto grab the Audio Unit of an application by injecting a bundle at the application start.I found an example (http://pastie.org/1882125) but it uses the functionMSHookFunctionto replace the function names. The problem is that I want to replace the functions on Mac OS X, not on iOS.Is there another way to hook C functions?
If youlook closely, you can find out that MobileSubstrate runs on OS X as well.
does anyone know how to display the percentage%character in an ncurses-based C++ / C=based program? I have tried using\x25and%, but they do not work.
You should be able to escape the%with an extra%: ``` %% ```
I want to hook the functionAudioUnitInitializeto grab the Audio Unit of an application by injecting a bundle at the application start.I found an example (http://pastie.org/1882125) but it uses the functionMSHookFunctionto replace the function names. The problem is that I want to replace the functions on Mac OS X, not on iOS.Is there another way to hook C functions?
If youlook closely, you can find out that MobileSubstrate runs on OS X as well.
does anyone know how to display the percentage%character in an ncurses-based C++ / C=based program? I have tried using\x25and%, but they do not work.
You should be able to escape the%with an extra%: ``` %% ```
What is the difference between the devices "default" vs "hw:0,0" ? Are they the same ? (Background: I faced some trouble to play audio when I configured hw:0,0 , but "default" worked. Could not find what caused this) Thanks
Thedefaultdevice uses theplugplugin to automatically convert sample formats and rates, and typically alsa uses thedmixplugin to allow multiple applications to access the device at the same time.
What is the difference between the devices "default" vs "hw:0,0" ? Are they the same ? (Background: I faced some trouble to play audio when I configured hw:0,0 , but "default" worked. Could not find what caused this) Thanks
Thedefaultdevice uses theplugplugin to automatically convert sample formats and rates, and typically alsa uses thedmixplugin to allow multiple applications to access the device at the same time.
My project contains c++ files and c files and I want to build my project with autotools. So I create theMakefile.am. and I m wondering if it's possible to put bothcppfiles andcfiles together into the_SOURCEvariable ``` myprogram_SOURCES = \ file1.c \ file2.c \ file3.cpp ```
Yes, you can add C and C++ files to_SOURCES.
As the question said. In Xcode 4.6. Want to print ints, chars, arrays, custom structs etc etc. Possible? With Objective-C I could do something like: int three = 3; po [NSString stringWithFormat:@"%i", three]; Thanks.
postands for Print Object, which essentially calls thedescriptionmethod on the object. Usepto print an integer. For example: ``` p three ```
My project contains c++ files and c files and I want to build my project with autotools. So I create theMakefile.am. and I m wondering if it's possible to put bothcppfiles andcfiles together into the_SOURCEvariable ``` myprogram_SOURCES = \ file1.c \ file2.c \ file3.cpp ```
Yes, you can add C and C++ files to_SOURCES.
I have an old program that I want to read the mesh data from, is there a way I can access all the faces/triangle strips that any program(not just the one doing the reading) is sending to OpenGL's buffer.
Check outglintercept ``` GLIntercept is a OpenGL function call interceptor for Windows that will intercept and log all OpenGL calls. ```
For example, is ``` static int a[1+1]; ``` valid standard C? For some or all versions of the standard? I'm not interested in whether compilers can handle it, but whether it is part of standard C.
C11, §6.6: A constant expression can be evaluated during translation rather than runtime, and accordingly may be used in any place that a constant may be. So yes, simple constant folding is mandatory and this snippet is valid standard C.
I have a C code that I'm analizing and there is something like this: ``` variable = (unsigned long)rx; ``` Ifrxis an array of hex numbers and variable is ofunsigned long, what will variable hold? The first element inunsigned longformat?
Remember that arrays decays to pointers. So what will happen is that the cast will convert the pointer (i.e. memory address) to anunsigned longand assign that tovariable.
I want to know if there is some open source projects (I prefer C projects) that use the cppUnit for the unit tests.
Xnor midi,tadaandnkbaseuse CppUnit. I believegnuradioalso uses CppUnit. A quick search on github goes a long way.
I want to know if there is some open source projects (I prefer C projects) that use the cppUnit for the unit tests.
Xnor midi,tadaandnkbaseuse CppUnit. I believegnuradioalso uses CppUnit. A quick search on github goes a long way.
I want to implement logging functionality in C and log messages to both stdout and some file. I would like to write something like fprintf(logout, "msg"); with somehow declared FILE* logout which will redirect strings to both stdout and some file. Is it possible?
If this is on Linux, you can open a pipe to theteecommand: ``` FILE *logout = popen("tee logfile", "w"); ```
I want to split the string "abc 123 456" into the string ("abc") and 2 numbers (123,456). What is the format should I put in the below code? ``` char *s; int a,b; sscanf("acb 123 456", format, s, &a, &b); ```
You want: ``` "%s%d%d" ``` But you also need to allocate buffer space for the string you extract: ``` char s[100]; int a,b; sscanf("acb 123 456", "%s%d%d", s, &a, &b); ```
I want to split the string "abc 123 456" into the string ("abc") and 2 numbers (123,456). What is the format should I put in the below code? ``` char *s; int a,b; sscanf("acb 123 456", format, s, &a, &b); ```
You want: ``` "%s%d%d" ``` But you also need to allocate buffer space for the string you extract: ``` char s[100]; int a,b; sscanf("acb 123 456", "%s%d%d", s, &a, &b); ```
Is there difference in C if I declare function like this: ``` Type * AK_init_observer(); ``` and like this: ``` Type* *AK_init_observer(); ```
Yes, the return types are different. The first returns a pointer toType, whereas the second returns a pointer to pointer toType.
Is there difference in C if I declare function like this: ``` Type * AK_init_observer(); ``` and like this: ``` Type* *AK_init_observer(); ```
Yes, the return types are different. The first returns a pointer toType, whereas the second returns a pointer to pointer toType.
When you open a file withCreateFileyou can set its sharing mode (the third parameter). Is there a way to set the sharing mode when using_open? Possibly by a call to_setmodeor something equivalent? I need to use theFILE_SHARE_DELETEmode.
_fsopen,_sopenand similar functions can take a share mode parameter however this does not supportFILE_SHARE_DELETE. If you want this share mode useCreateFile
How can I capture packet of applications, including Hotspot Shield and other free proxy applications?
If I understand your question, you're looking for a tool that allows you to capture network packets on your machine and examine them. You can use tools likeWiresharkthat allows you do that.
I wrote a program in which I found the area of cylinder using a functionareawith a return-type and without parameters.answerwas returned tomainfunction. However, I am getting different output inmainand a different output inarea. The decimal places seem to be replaced by 0 in themainfunction. Why is it so?
Change the return type of area from int to float
If I have a condition like this: ``` if (X && Y) {} ``` Will the compiler checkYifXis false? Is it compiler dependent?
In C andmost other languagesshort-circuit evaluation is guaranteed. SoYis only evaluated ifXevaluates to true. The same applies toX || Y- in this caseYis only evaluated ifXevaluates to false. SeeMike's answerfor a reference to the C specification where this behavior is mentioned and guaranteed.
Multiple markers at this line - previous definition of 'type' was here - redefinition of parameter 'type' int parseLine(char* line, int* day, float* amount,char* type, char* type); That's the error I'm getting in a header C file in Eclipse
The error tells you that you definedchar* typetwice
Anybody knows, how to get real value of clock per sec?clock()fromtime.hreturns clocks from start of my process, so it need to be divided byCLOCKS_PER_SEC, but this constant has always value1000000. Is there some POSIX standard for this?
That's how it specified in the C specification. If you want to measure elapsed time, there are other (and better) functions, likegettimeofdayfor example.
How to play a sound file specified by user in an array using the PlaySound()? I'm using Windows7 and VC++ 2010. Suppose I use thegets(song);statement to input the complete path of the song from user.
http://msdn.microsoft.com/en-us/library/windows/desktop/dd743680(v=vs.85).aspx ``` PlaySound( song, NULL, SND_FILENAME ); ```
Everything I've seen says to uselsof -p, but I'm looking for something that doesn't require a fork/exec. For example on Linux one can simply walk/proc/{pid}/fd.
You canuseproc_pidinfowith thePROC_PIDLISTFDSoption to enumerate the files used by a given process. You can then useproc_pidfdinfoon each file in turn with thePROC_PIDFDVNODEPATHINFOoption to get its path.
Everything I've seen says to uselsof -p, but I'm looking for something that doesn't require a fork/exec. For example on Linux one can simply walk/proc/{pid}/fd.
You canuseproc_pidinfowith thePROC_PIDLISTFDSoption to enumerate the files used by a given process. You can then useproc_pidfdinfoon each file in turn with thePROC_PIDFDVNODEPATHINFOoption to get its path.
What is the best way to execute this command: "sudo cat /var/log/auth.log | grep Accepted" inside my C program ? I tried to use: ``` sprintf(command_result,"sudo cat /var/log/auth.log | grep Accepted"); ``` But it didn't work obviously.
You cannot execute the command withsprintf()you needsystem()atleast fix: ``` sprintf(command_result, "sudo cat /var/log/auth.log | grep Accepted"); system(command_result); ```
all: Is there any good open source C library which provides sending email function? I don't want use mailx command in Solaris.Thanks very much in advance!
I just searched on google and found these few link..hope this will help. http://sourceforge.net/projects/jwsmtp/?source=dlp http://www.stafford.uklinux.net/libesmtp/download.html
Does anyone know how to turn an integer array into a float array?
Your question is not worded well; however, assuming you have already declared your integer array, you could try something like this: ``` // instantiate float array float fArray[sizeOfIntArray]; // step through each element of integer array, and copy into float array as float for(int i = 0; i < sizeOfIntArray; ++i) { fArray[i] = (float)iArray[i]; } ```
I was trying to implementgetchar()function usingreadfunction in unistd.h. I knowread(0,buffer,1)is equivalent togetchar(), however, it takes too many system calls. Is there a way to implementgetchar()function using less system calls?
Yes -- read a larger buffer (e.g., at least a few kilobytes) full of data. When the user calls getchar, return a char from the buffer unless it's empty. If it is empty, refill the buffer first, then return a char.
``` #define Map(From, To, val) \ Map__##From__##To(val) Map(TYPEA, TYPEB, 22); ``` In the above code I am wondering whyMap(TYPEA, TYPEB, 22);is getting expanded toMap__From__TYPEB(22);and notMap__TYPEA__TYPEB(22); I used gcc -E for expansion.
BecauseFrom__is not a token inMapand hence, preprocessor does not look it up.. fix is : ``` #define Map(From, To, val) \ Map__##From##__##To(val) ```
I am trying to use a macro in sprintf statement. It is like this : ``` #define MACR 6 .... int Number= 5; char Formatted[30]; sprintf( Formatted, "%06d", Number ); ``` Here I would like to use MACR instead of 6. Can anyone help me please?
Use the*format specifier to pass the width as argument. Something like this should work: ``` sprintf( Formatted, "%0*d", MACR, Number ); ``` But please use a constant not a MACRO.
currently I search achar *withstrstrbut I dont want to search in the complete one, only from the 42. char to the end. How can I achieve this?
Just providestrstr()with a pointer to the first character to include in the seach: ``` if(strstr(the_haystack + 42, "the needle") != NULL) printf("found needle at end of haystack!\n"); ``` Of course, this assumes thatthe_haystackreally is at least 42 characters long.
This question already has answers here:What is the difference between const int*, const int * const, and int const *?(23 answers)Closed10 years ago. ``` char const*const variablename = " "; ``` what does it mean? is it same as pointer declaration? Please anyone explain. Thank you in advance!
It's aconstpointer to aconstC string. This means that neither the contents of the string, nor the pointer itself, can be changed.
``` tempValue = input2[0] << 8; ``` I can't figure out what the<<does in this line of code. What is this used for?
It assignstempValuethe value ininput2[0]shifted to the left by 8 bits. Here is a link about bit shifting in C:http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/bitshift.html
I am using unistd.hsys/stat.h and what is interesting is thatst_sizeis bigger than the value returned afterread()?st.st_sizereturns644-read()returns606, Any thoughts?
Size of file and size of stream may not match. For example, when you open file in text mode, OS can translate multi-byte EOL sequences into single char. This is usually visible on Windows, but if you have a Windows file on Linux, the effect can be the same.
I want to pass Unix file descriptor from one local (same machine processes) process to another process. Which are the IPCs mechanism useful from below? ``` PIPE/FIFO/Message Queue/ Shared Memory/ Socket / TLI / stream/ RPC** ```
The canonical way of passing a file descriptor from one process to the other is using Unix domain sockets, via the ancillary data ofsendmsgandrecvmsg.
I want to pass Unix file descriptor from one local (same machine processes) process to another process. Which are the IPCs mechanism useful from below? ``` PIPE/FIFO/Message Queue/ Shared Memory/ Socket / TLI / stream/ RPC** ```
The canonical way of passing a file descriptor from one process to the other is using Unix domain sockets, via the ancillary data ofsendmsgandrecvmsg.
Usuallylseekdoesn't work onstdin. But, what if I run my program like this: ./a.out < filename Nowstdinis a file and not keyboard. Willlseekwork there? Can I do lseek(0, -1, SEEK_CUR) and get the same effect like ungetc()?
Yes,lseekwill change the seek pointer. No, it is not equivalent toungetc(). fseek(stdin, -1, SEEK_CUR)comes closer toungetc(), but still isn't identical.
When I intuitively try to run such command ``` cc -c source.c header.h -o a_name_different_than_source.o ``` the following error is thrown cc: cannot specify -o with -c, -S or -E with multiple files
Do not putheader.hin your command line: ``` cc -c source.c -o a_name_different_than_source.o ``` will work.
Usuallylseekdoesn't work onstdin. But, what if I run my program like this: ./a.out < filename Nowstdinis a file and not keyboard. Willlseekwork there? Can I do lseek(0, -1, SEEK_CUR) and get the same effect like ungetc()?
Yes,lseekwill change the seek pointer. No, it is not equivalent toungetc(). fseek(stdin, -1, SEEK_CUR)comes closer toungetc(), but still isn't identical.
When I intuitively try to run such command ``` cc -c source.c header.h -o a_name_different_than_source.o ``` the following error is thrown cc: cannot specify -o with -c, -S or -E with multiple files
Do not putheader.hin your command line: ``` cc -c source.c -o a_name_different_than_source.o ``` will work.
When I intuitively try to run such command ``` cc -c source.c header.h -o a_name_different_than_source.o ``` the following error is thrown cc: cannot specify -o with -c, -S or -E with multiple files
Do not putheader.hin your command line: ``` cc -c source.c -o a_name_different_than_source.o ``` will work.
If I was to write a tiny C or C++ application (on Linux) and call "native" Linux functions, such as select() and poll() when profiling, would I be able to see the assembler being used for these functions too, its not just user-written code which can be profiled? I would be interested to see the assembly produced for various "native" Linux functions.
Almost. They are kernel calls, so you would see a bit of code up to kernel level.
In libc's malloc(x), the function is said to return a pointer to a memory region of at least x bytes and the pointer is aligned to 8 bytes. What does this alignment mean? THank you.
It means that the pointed address mod 8 is 0: ``` pointer % 8 == 0 ``` This can be important for low level operations where it may impact correctness or efficiency. See alsothis answer.
I am using gnu gcc and armcc to compile a few C files. How can I get the information about which compiler compiled which file? Ex: test.cpp is being compiled by armcc or gnu gcc. The makefile is very complicated and I am looking out for a command by which I can check which compiler compiled which file. Any ideas?
Sometimes you can look at the file with a hex editor and tell if the compiler wrote its name into the file.
I have quite a big structure which has inside of it other structures, then I want to pass this structure of structures as an argument of a function. Anyone knows how to do it or may give me an example please!
``` struct B { //your struct.. }; struct A { B b; }; void foo(struct A a) { a.b + ???.... //you function } ```
I have quite a big structure which has inside of it other structures, then I want to pass this structure of structures as an argument of a function. Anyone knows how to do it or may give me an example please!
``` struct B { //your struct.. }; struct A { B b; }; void foo(struct A a) { a.b + ???.... //you function } ```
I have quite a big structure which has inside of it other structures, then I want to pass this structure of structures as an argument of a function. Anyone knows how to do it or may give me an example please!
``` struct B { //your struct.. }; struct A { B b; }; void foo(struct A a) { a.b + ???.... //you function } ```
Basically I want to do the following: ``` #define TYPE float int main() { if (TYPE==float)...; } ``` Of course it wont' work, and not sure how to achieve it.
You can use the C preprocessor'sstringificationoperator. ``` #define xstr(s) str(s) #define str(s) #s if (strcmp(xstr(TYPE), "float") == 0) ... ``` For an explanation of this, seehere
I have data for which using cin/in is too slow. There are three integers per line : ``` 1 2 2 3 4 1 5 6 122 6 4 7 ``` How to read-in each line in loop, to achive result (for first iteration) : ``` x==1; y==2; z==2; etc. ``` ? How to to do it using cstdio::scanf ?
Use this: ``` while(scanf("%d %d %d", &a, &b, &c) != EOF) { ... do stuff ... } ```
I have data for which using cin/in is too slow. There are three integers per line : ``` 1 2 2 3 4 1 5 6 122 6 4 7 ``` How to read-in each line in loop, to achive result (for first iteration) : ``` x==1; y==2; z==2; etc. ``` ? How to to do it using cstdio::scanf ?
Use this: ``` while(scanf("%d %d %d", &a, &b, &c) != EOF) { ... do stuff ... } ```
I am currently working in C multi-threading on server having multiple hexa-core cpus. I want to set affinity of some of my threads to respective cores of a single CPU. I have used pthread_setaffinity_np() and also sched_setaffinity() but i guess the set affinity on the cpus not the cores. am I right?
pthread_setaffinity_np()et al operate in terms of logical CPUs (i.e. cores), not physical ones (i.e. CPU sockets).
I have this part of code in C class: ``` int i; for (i=0;i<val;i++) mdl_print ("%u ", rec->payload[i]); mdl_print ("\n"); ``` Variable rec->payload is uint8_t type. I would print it in hexadecimal notation. How can I do? Thanks.
Quick and easy: ``` print("%x", (int)(rec->payload[i])); ``` To display in the format 0x05 then use: ``` print("0x%02x", ...) ``` instead.
I have this part of code in C class: ``` int i; for (i=0;i<val;i++) mdl_print ("%u ", rec->payload[i]); mdl_print ("\n"); ``` Variable rec->payload is uint8_t type. I would print it in hexadecimal notation. How can I do? Thanks.
Quick and easy: ``` print("%x", (int)(rec->payload[i])); ``` To display in the format 0x05 then use: ``` print("0x%02x", ...) ``` instead.
Is it possible to make a data type which can take integer values from 0 to 9 only? If yes, please tell How?
No, it is not possible to make a custom-ranged integer in C. You'll have to maintain such an invariant yourself.
Is there native support for a data type for storing Unicode strings in C. I'm writing a toy compiler and would like to parse Unicode strings.
Is there native support for a data type for storing Unicode strings in C. Yes. Since Unicode strings can bestoredas sequences of bytes using an encoding scheme, one can use arrays ofcharfor this purpose. Note that supporting storage says nothing about the ability to interpret or manipulate the data.
Why is the value of n changing to garbage inside the for-loop? (I'm new to C language, I come from a C++ background) ``` float n = 3.0; printf ("%f\n", n); for (; n <= 99.0; n += 2) printf ("%f\n", &n); ```
You are printing the address of n (&n) inside the for-loop. Get rid of the&
I wrote a small rgrep function and I'll have another text file with words that I am checking a pattern against. My text file will be in the following format. ``` a because cat 7.* ``` How do i write a loop that will call a function for each of those words in the file? Thanks!
Make a state machine for that pattern first, then every char drives that state machine to next state. Check state to check pattern match.
i wanna know what is the difference between ``` void fct1(int *p) ``` and ``` void fct1(int p[]) ``` i know that both are pointers but are there any differences
There is absolutely no difference when used as a function parameter like that. The compiler treats both forms identically.
Using the Mongodb C Driver, how can I issue shell commands like db.mydb.remove()? The API seems pretty limited:http://api.mongodb.org/c/current/api/annotated.html
To drop collection usemongo_cmd_drop_collection(…), to drop DBs usemongo_cmd_drop_db(…). Most commands are insidemongo.h. Edit: To perform the requestedremove(…)usemongo_remove(…).
How can I assign non-ASCII characters to a wide char and print it to the console? This code down doesn't work: ``` #include <stdio.h> int main(void) { wchar_t wc = L'ć'; printf("%lc\n", wc); printf("%ld\n", wc); return 0; } ``` Output: ``` 263 Press [Enter] to close the terminal ... ``` I'm using MinGW GCC on Windows 7.
You should usewprintfto print wide-character strings: ``` wprintf(L"%c\n", wc); ```
Using the Mongodb C Driver, how can I issue shell commands like db.mydb.remove()? The API seems pretty limited:http://api.mongodb.org/c/current/api/annotated.html
To drop collection usemongo_cmd_drop_collection(…), to drop DBs usemongo_cmd_drop_db(…). Most commands are insidemongo.h. Edit: To perform the requestedremove(…)usemongo_remove(…).
What is the value of0x1.921fb82c2bd7fp+1in a human readable presentation? I got this value byprintfusing%a.
The mantissa is hexadecimal and the exponent is a decimal value representing the power of 2 the mantissa is scaled by.
``` #define power(a) #a int main() { printf("%d",*power(432)); return 0; } ``` can anyone explain the o/p??the o/p is 52
It is equivalent to: ``` printf("%d",*"432"); ``` which is equivalent to: ``` printf("%d", '4'); ``` and the ASCII value of'4'is52.
I get this error. ``` error: warning: incompatible implicit declaration of built-in function ‘memcpy’ [enabled by default] ``` This is the code: ``` int arr[ 12] = {1,0,0,0,0,0,0,0,0,0,9370, 0}; void *a = &arr; memcpy(machine->mem, a,12*4); ``` What I am doing wrong?
You likely forgot to include<string.h>. Add#include <string.h>to the top of your file.
I am learning cmocka unit testing framework. I am a bit puzzled at use of mock() function. Can somebody explain it clearly why and how it is used with suitable examples? Also please explain when it should be used.
You should readhttps://lwn.net/Articles/558106/to understand the mock() feature.