question
stringlengths
24
425
answer
stringlengths
5
405
Hi I have a question about double pointers. For example in this code: ``` int a, b=2; int *iPtr1, **iPtr2; iPtr1 = &a; iPtr2 = &iPtr1; *iPtr1 = b+3; *iPtr2 = iPtr1; ``` On the last line*iPtr2 = iPtr1;It that just tellingiPtr1to point back to itself since dereferencing a double pointer just once is like usingiPtr1?
It makes*iPtr2point to whateveriPtr1points to. And asiPtr2points toiPtr1it's the same asiPtr1 = iPtr1.
I have the code: ``` #DEFINE NEW = 1; ``` And a Struct: ``` typedef struct PCB { /*Process state:new, ready, running, waiting, terminated*/ int state; }PCB; ``` How can I assign NEW, such that state=1? More info, I get the error: ``` expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token ```
Remove both semicolon and the= #DEFINE NEW 1
What is the practical difference, if any, betweenstdinandSTDIN_FILENOin C?
The interface. Like everyone else has said,stdinis aFILE *as defined by the standard c library. You can use some of the higher level interfaces likefread,fwrite, andfprintf. On the other hand,STDIN_FILENOis just a file descriptor (almost certainly 0). This uses a slight lower level interface through the likes ofreadandwrite.
Is there a difference between ``` const char* name = "name"; ``` and ``` const char *name = "name"; ``` Thank you.
no. But there is a difference between ``` const char* name = "hello", something = "else"; ``` which will not work, while ``` const char *name = "hello", *something = "else"; ``` should
I am doing assignment in which I am using POSIX named semaphore, but it is not showing me list when I enteripcs -scommand. Please help me to get entry of named semaphore. Where will I get that?
ipcsis for System V semaphores, you are using POSIX semaphores. For the differences, seehere.
followed the steps mentioned in the following thread, Attaching a process to a debug session: empty process list Now I am able to get the process list. But Process list is missing "javaw.exe" which is shown in the task manager. any help?
Enter the process id of the process you want to attach to. You can get the process id by looking for the process's image name in the task manager.
What is the practical difference, if any, betweenstdinandSTDIN_FILENOin C?
The interface. Like everyone else has said,stdinis aFILE *as defined by the standard c library. You can use some of the higher level interfaces likefread,fwrite, andfprintf. On the other hand,STDIN_FILENOis just a file descriptor (almost certainly 0). This uses a slight lower level interface through the likes ofreadandwrite.
Is there a difference between ``` const char* name = "name"; ``` and ``` const char *name = "name"; ``` Thank you.
no. But there is a difference between ``` const char* name = "hello", something = "else"; ``` which will not work, while ``` const char *name = "hello", *something = "else"; ``` should
Uncrustify is great, and does an excellent job of tidying code. However, I have some C code within a file that I don't want Uncrustify to change. Is there any way I can prevent Uncrustify from touching this, maybe by putting specific tags in comments around the code or something?
``` /* *INDENT-OFF* */ int i = 0; // No uncrustify action here /* *INDENT-ON* */ ```
Is there a way for abashshell program, that takes a command-line argumentx, that will makex(C program) processes start? .
It's fairly simple: ``` #!/bin/bash $1 ``` If you want to pass the rest of the parameters as parameters to the function, do this: ``` $@ ``` (i.e.foo.sh echo hiexecutesecho hi) If you want to steal some parameters and pass others, useshift: ``` param1=$1 shift echo $@ # contains parameters 2+ ```
I can't find relevant information about this. For lua, if you want to execute a test.lua file from the main() C function, you calllua_dofile("test.lua"). What is the python equivalent?
If you are embedding Python, usePyRun_SimpleFile: ``` FILE *fp = fopen("test.py", "r"); int ret = PyRun_SimpleFile(fp, "test.py"); if(ret < 0) { /* exception occurred */ } ```
I need to do some socket programming on Mac OS X but I'm missing the library for it? This is what happens when I compile: ``` gcc ser.c -o ser -lsocket -lnsl ser.c: In function ‘main’: ser.c:41: warning: format ‘%.24s’ expects type ‘char *’, but argument 6 has type ‘int’ ld: library not found for -lsocket collect2: ld returned 1 exit status ``` How do I get this library?
You don't need-lsocketon OS X.
I wish to change this popup for every program calling ``` public class OpenFileDialog : FileChooserDialog { ``` Ideally it would involve removing desktop and changing search etc. I was just hoping somebody knew where the underlying files are?
The UI layout for the file chooser dialog is in gtk/gtkfilechooserwidget.c http://git.gnome.org/browse/gtk+/tree/gtk/gtkfilechooserwidget.c
``` $arr['key1'] = ""; $arr['key2'] = ""; echo json_encode($arr); ``` I get{"key1":"","key2":""}. How could I add just a key element without a value? So it would be{"key1","key2"}?
Your desired output is notvalid JSON. If you want to create a list, then use: ``` $arr[0] = 'key1'; $arr[1] = 'key2'; echo json_encode($arr); ``` Output: ``` ["key1","key2"] ```
How does one trackKEY_ENTERin ncurses? I have tried tracking\nusinggetch(),KEY_ENTER, andraw(), to no avail.
Seems like to use those key abbreviations like KEY_ENTER, you have to make a call to: ``` keypad(win, true); ``` before using them. Take a look at this:http://osr600doc.sco.com/en/man/html.CURSES/keypad.CURSES.html
How does one trackKEY_ENTERin ncurses? I have tried tracking\nusinggetch(),KEY_ENTER, andraw(), to no avail.
Seems like to use those key abbreviations like KEY_ENTER, you have to make a call to: ``` keypad(win, true); ``` before using them. Take a look at this:http://osr600doc.sco.com/en/man/html.CURSES/keypad.CURSES.html
It completely stops reading in code after it sees a space. How do I change my code so it reads in white space ``` char line[300]; printf("Enter a string to be checked: "); scanf("%s", line); ``` the string I'm trying to input via redirection is: ( ( a a ) < > [ [ [ { [ x ] ]]] <>)
You can use fgets intsead of scanf. For example: ``` fgets(line, 1024, stdin); ```
Where is gethostbyaddr and netdb.h functions implemented? I can only find the header file where it is extern'ed (netdb.h) Thanks
It is implemented in glibc. BTW, use getnameinfo() and getaddrinfo(). gethostbyaddr() is obsolete, mostly because of IPv6.
I have the following code ``` long x; scanf("%ld",&x) if(x==-1) // does this comparison is allowed printf("just test\n"); ``` doeslongparameters need any casting before comparison?
-1is a decimalint. There's an implicit conversion (promotion) frominttolong, so-1is automatically "casted" tolong. Also, both-1andxare signed types. No need from any additional casts.
Hi I am using a C compiler(GCC) where I cannot use a vector like in C++. So how can I create similar kind of data structure/dynamic array with c which will work like a vector? It might be very easy but I don't have any idea how can I do it. thanks
Start with a struct holding a pointer to the correct type the currently used size, and the current allocation size. Allocate space with malloc. If you run out of space, use realloc to increase it.
This question already has answers here:How to check if a string contains spaces/tabs/new lines (anything that's blank)?(5 answers)Closed10 years ago. Lets say we havechar *str = "123 467";Is there something like isdigit() for numbers to return a boolean value?
How about isspace()? This will tell you if a char is a white space character. It is included in ctype.h
This question already has answers here:How to check if a string contains spaces/tabs/new lines (anything that's blank)?(5 answers)Closed10 years ago. Lets say we havechar *str = "123 467";Is there something like isdigit() for numbers to return a boolean value?
How about isspace()? This will tell you if a char is a white space character. It is included in ctype.h
I was wondering if it's possible to determine if a virtual address (pointer) belongs to a previousVirtualAlloccall or not (if possible without writing to the page). SinceVirtualFreecan automatically set thedwSizevalue if you use it withMEM_RELEASE.
Something like this or I don't understand the question? ``` MEMORY_BASIC_INFORMATION mbi; void* p = NULL; VirtualQuery(p, &mbi, sizeof(mbi)); BOOL bWasUsed = (mbi.State==MEM_FREE)? FALSE: TRUE; ```
I want to have my text horizontally aligned to the center in the terminal. How can I do this in C?
To expand on @eyalm's answer: if you got theCOLUMNSvar, you can center strings like this: ``` int columns = strtol(getenv("COLUMNS"), NULL, 10); int fwidth = strlen(s) + (columns - strlen(s)) / 2; printf("%*s\n", fwidth, s); ```
I'm writing a function in C (using Eclipse) which has a integer calledalpha, and its assigned value is077. But when I print it out, it prints63instead of77or077. In fact, it's not just077butanyinteger with a leading0is printing an unexpected value. When I remove0from077, itdoesprint the correct value77. What effect does this leading0have?
A number starting with a0is an octal number. 077is7 x 8 + 7 == 63
I need to calculate an angle in C programm. Here is a method from JAVA that I need to convert to C. ``` private static double calculateDirection(double x, double y) { return Math.toDegrees(Math.atan2(y, x)); } ``` Is there a function like toDegrees in C language so I don't have to write all the code by myself? Thank you
``` #include <math.h> inline double to_degrees(double radians) { return radians * (180.0 / M_PI); } ```
I want to have my text horizontally aligned to the center in the terminal. How can I do this in C?
To expand on @eyalm's answer: if you got theCOLUMNSvar, you can center strings like this: ``` int columns = strtol(getenv("COLUMNS"), NULL, 10); int fwidth = strlen(s) + (columns - strlen(s)) / 2; printf("%*s\n", fwidth, s); ```
I'm writing a function in C (using Eclipse) which has a integer calledalpha, and its assigned value is077. But when I print it out, it prints63instead of77or077. In fact, it's not just077butanyinteger with a leading0is printing an unexpected value. When I remove0from077, itdoesprint the correct value77. What effect does this leading0have?
A number starting with a0is an octal number. 077is7 x 8 + 7 == 63
I need to calculate an angle in C programm. Here is a method from JAVA that I need to convert to C. ``` private static double calculateDirection(double x, double y) { return Math.toDegrees(Math.atan2(y, x)); } ``` Is there a function like toDegrees in C language so I don't have to write all the code by myself? Thank you
``` #include <math.h> inline double to_degrees(double radians) { return radians * (180.0 / M_PI); } ```
In C language code, if I have a bunch of variables that will be used only for logical operations, what is the data type that will yield the fastest execution time? Also, does it depend if I'm using an ARM or Intel processor, 32-bit or 64-bit system?
If the compiler allows, include<stdbool.h>, usebool, and trust the compiler/RTL vendor to do the right thing. Otherwise useint.
Are there any open source libraries or standard functions that allow a C program to interact with other command line programs (that for example may request user input).
expectis a popular library for programmatically interacting with interactive programs (e.g.ssh). There's a port of it to C calledlibexpectwhich may do what you want.expectemulates a terminal, so it is particularly useful for applications that won't talk to simple pipes.
I need to read the text and find if there is more than one space between the words. If there is change it to one. For example if I have a text: ``` My name is Lukas ``` Program should change it to: ``` My name is Lukas ``` Any ideas?
``` while (*str) { if (*str != ' ' || str[1] != ' ') *newstr++ = *str; str++; } *newstr = 0; ```
crypt (const char *key, const char *salt) I saw it in code, but i could not find the implementation of this function. Is it some of the conventions of C?
It's specified byPOSIXbut not by any version of the C standard. Careful though: The crypt() function is a string encoding function.The algorithm is implementation-defined.
Why is there a number added to the name of a local static variable in the symbol table? ``` int main(void) { static stat_var = 20; return 0; } ``` 8: 0000000000000008 4 OBJECT LOCAL DEFAULT 2 stat_var.1604
There can be many local static variables with the same name (across different functions). The compiler is giving them disambiguating suffixes to avoid a potential name collision.
I am creating a public key generator and I do c= p*q; Where p and q are large prime numbers, but I keep getting this for C 11875820813; ``` long unsigned int c= p*q; printf("C is: %d\n", c); ``` I know I has something to do with my numbers, but I don't know how to fix this. I am trying to multiply: 872017*533297
You might be overflowing the value. Remember that on a 32-bit platform anunsigned longcan be at most a little over 4 billion.
I get the error: warning: format argument is not a pointer (arg 2) with this line:printf("%s \n", *(group_list->name)); I don't understand why this is a problem considering thatnameis a pointer to a char. Is it a problem with usings? Do I have to use a different specifier?
Use this instead: ``` printf("%s \n", group_list->name); ``` sconversion specifier expects achar *not achar.
printf("%d, ", packet[i]); How to display variable correctly. It should be from 0 to 255 but if I use%dit prints: -1 as 255 up to the number 128 is displayed correctly, larger are negative. when I use%uit prints 4294967295 instead of 255.
Use%hhuconversion specification: ``` printf("%hhu, ", packet[i]); ```
My simplified code looks like something below: ``` char decrypted[64] = "P@ssw0rd "; int realsize = 8; realloc(decrypted, realsize); char *dec2 = (char *) malloc(realsize+1); // Exe crashes at this point ``` I am guessing it has to do withchar *dec2, but this only crashes Win XP for some reason.
You cannotrealloc()what hasn't been allocated withmalloc()orcalloc()orrealloc().
Withfopen()I read the file line by line withfgets(). Are there a function likefgets()inorder to read stream opened byopen()?
There is no such function. The problem is, unless you do buffering in userspace (likeFILE*routines do), there is no way to implement it efficiently: you'll have toreadcharacters one-by-one. On POSIX systems you can usefdopento wrap aFILE*structure around a file descriptor, and then usefgets.
I've been asked to create this for loop for my C Programming class but I do not know how to alternate the positive and negative values. Thank you in advance! sum2=1-x+x^2-x^3+⋯+/-x^n
Hint: consider the expression as sum of (-1*x)^i, with i = 1, 2, 3, ..., n. If n is even then (-1*x)^i is positive, if odd then negative.
I've to link libcurl to a project compiled on Windows XP with VS 2010 (MSVC 10). The dependencies found at urlhttp://windows.php.net/downloads/php-sdk/deps/are only for VC 2008 (MSVCR 9) and VS 2012 (MSVCR 11). Does anybody know where to find compiled libcurl binaries or its dependencies (for building by its makefiles) with VS 2010 (MSVCR 10)? Thank you very much!
Problem solved : open and convert the root DSW file, then compile with VS!
Linux C program: What function call can check if running in X Window? If not in X Window, then printf.
Do you mean something like this: ``` #include <X11/Xlib.h> // ... char *display_name = NULL; /* connect to X server */ if ( (display=XOpenDisplay(display_name)) == NULL ) { //printf or whatever } ```
I have to read from standard input two numbers as strings, in C. How can I print their sum as a string too? I have: ``` char a[10],b[10]; printf("enter the two numbers"); scanf("%s%s",&a,&b); char sum[20]; sum=? ``` A little tip,please? Thank you!
Just do it like in elementary school Let's say the input was "...69 + ...63" ``` 9 + 3 = 2 and 1 to go 6 + 6 + 1 = 3 and 1 to go ... ```
On SDL 2, there is the functionSDL_GL_MakeCurrent, is there any thing like that for SDL 1.2?
Not in the public API, no. Theprivate video backend interfacehas a function pointer for it though.
On SDL 2, there is the functionSDL_GL_MakeCurrent, is there any thing like that for SDL 1.2?
Not in the public API, no. Theprivate video backend interfacehas a function pointer for it though.
I am trying to build WildMagic 5.9 on Visual Studio 2012 but here are error: ``` Error 3 error C2039: 'greater' : is not a member of 'std' c:\wildmagic5\libmathematics\intersection\wm5intrellipsoid3ellipsoid3.cpp 142 1 LibMathematics_VC100 ``` Why? What to fix to get this to compile?
Need include: ``` include <functional> ```
How do I open an external EXE file from inside C? I'm trying to write a C program that opens Notepad, and some other applications and I am stuck. Thanks for putting up with my noob level of C ;p
Please trysystem("notepad");which will open the notepad executable. Please note that the path to the executable should be part ofPATHvariable or the full path needs to be given to thesystemcall.
How do I open an external EXE file from inside C? I'm trying to write a C program that opens Notepad, and some other applications and I am stuck. Thanks for putting up with my noob level of C ;p
Please trysystem("notepad");which will open the notepad executable. Please note that the path to the executable should be part ofPATHvariable or the full path needs to be given to thesystemcall.
Is there a way to remove the last number from an integer in C? For example, if the user entered the number: "123" is there a way to change that to just "12"? Thanks
Divide that integer number by 10. 123 / 10 == 12.
This question already has answers here:How do you initialise a dynamic array in C++?(10 answers)Closed10 years ago. Is there a way in c++ to fill an array allocated like this ``` int **a = new int[4][2]; ``` so that it's filled with values in one line like this ``` int a [4][2] = {{2,3,4},{5,6,7}}; ```
You can do it in C++11 withuniversal initialization notation: ``` int(*a)[2] = new int[2][2]{{1,2},{3,4}}; ```
I have downloaded both programs, but I see no instructions on google for getting Cilk to work on Cygwin. Is there a Cygwin package that would work? I'm programming in C and have gcc installed.
Build it from source. That will link thecygwin32.dllwith the binaries which are essential for it to work with cygwin. Here is a guide:http://groups.csail.mit.edu/sct/wiki/index.php?title=Cilk_Plus_Installation_Guideto build it from source withgcc.
This question already has answers here:What does 'sizeof (function name)' return?(4 answers)Closed10 years ago. I triedsizeof(printf),sizeof(foobar)etc. where foobar is a user defined function. It returns 1 without any warning or error. Why 1?
The size of functions is not well defined in C, so the value is meaningless.
everytime we write a program we need something like #include or any other #include things... Is there anyway to create alias for this, so that when I type inc in vim and press some key, then inc changes to #include
Read:h abbreviationsor try one ofthe many snippet expansion plugins available. I use the originalSnipMate, but there isa modern forkand a modern alternative calledUltiSnips.
everytime we write a program we need something like #include or any other #include things... Is there anyway to create alias for this, so that when I type inc in vim and press some key, then inc changes to #include
Read:h abbreviationsor try one ofthe many snippet expansion plugins available. I use the originalSnipMate, but there isa modern forkand a modern alternative calledUltiSnips.
I came across a code that looks like this: ``` asm volatile ( # [...] "movl $1200, %%ecx;" # [...] ); ``` I know whatmovl $1200, %ecxdoes in x86. but I was confused by why there are two percent signs.
GCC inline assembly uses %0, %1, %2, etc. to refer to input and output operands. That means you need to use two %% for real registers. Check thishowtofor great information.
There isfilenoto get the file descriptor of a FILE*. How do you get the address for the FILE* given a file descriptor number, e.g. as returned frompipe? filenopipe
You want to use thefdopen()function: ``` FILE * file = fdopen(fd, "r"); ``` so you could use it in combination withpipelike this: ``` FILE * file = fdopen(pipe(..,..), "r"); ```
I have two bytes containing a 14-bit left-justifiedtwo's complementvalue, and I need to convert it to a signed short value (ranging from -8192 to +8191, I guess?) What would be the fastest way to do that?
Simply divide by 4. (Note, right-shift leads to implementation/undefined behaviour.)
There isfilenoto get the file descriptor of a FILE*. How do you get the address for the FILE* given a file descriptor number, e.g. as returned frompipe? filenopipe
You want to use thefdopen()function: ``` FILE * file = fdopen(fd, "r"); ``` so you could use it in combination withpipelike this: ``` FILE * file = fdopen(pipe(..,..), "r"); ```
I have two bytes containing a 14-bit left-justifiedtwo's complementvalue, and I need to convert it to a signed short value (ranging from -8192 to +8191, I guess?) What would be the fastest way to do that?
Simply divide by 4. (Note, right-shift leads to implementation/undefined behaviour.)
I have known this problem is compiler-dependent. So I want a reliable method to determine. For example: ``` const wchar_t str[] = L"飞流直下三千尺"; ``` How should I know whetherstris little-endian or big-endian? Is there a compiler's guarantee that the endianness of a wide string literal is the same one as the target architectures?
There's no compiler guarantee thatwchar_tevenhasan endianness (or that it's Unicode, for that matter).
I am trying to add a null termination to my buffer with the following code. But I don't seem to be able to pass my null terminator in.Is this the correct way to do it? When I strlen my buffer the value is 10 but I only keyed in 9 chars. ``` char buffer[256]; int n; bzero(buffer,256); fgets(buffer,255,stdin); buffer[n-1]="\0"; ```
You are assigning a string not a char withbuffer[n-1] = "\0";.Trybuffer[n-1] = '\0';instead.
How would i find out the length of a string without using loop and String class function like strlen() ?
``` int length (const char* p) { return *p == 0 ? 0 : 1 + length(p+1); } ``` Any iterative function can theoretically be implemented recursively and vice versa.
I'd like to do something likeprintf("?", count, char)to repeat a charactercounttimes. What is the right format-string to accomplish this? EDIT: Yes, it is obvious that I could callprintf()in a loop, but that is just what I wanted to avoid.
You can use the following technique: ``` printf("%.*s", 5, "================="); ``` This will print"====="It works for me on Visual Studio, no reason it shouldn't work on all C compilers.
This question is pure teoretical, and not about the right way of doing it, but do we need to convert char 'x' to network format? I'm intressted in all cases: always / sometimes / never I personally think I should but i need to be sure, than you.
No, char is a single byte value so endianess doesn't matter
In CMakeLists.txt, I would like to check that bzlib.h exists: ``` include(CheckIncludeFiles) check_include_file(bzlib.h HAVE_BZLIB_H) if(NOT HAVE_BZLIB_H) # How can I exit cmake with an error message if bzlib.h does not exists? endif() ```
It's quite easy:message( FATAL_ERROR "Your message" )
I have a unix time_t , is there any easy way to convert this to a time_t so it: Represents midnight of the day of the time_t ?Represents the start of the hour of the time_t ?
Something like this: ``` time_t t = time(NULL); t -= (t % 86400); ``` The constant 86400 = 24 * 60 * 60 - a useful number to remember, I think... ;)
I was wondering how does autility like this oneredirects a folder to a driver letter? PS. I need this done with C/C++/MFC.
It probably usesDefineDosDevice, as an ordinarysubstcommand does.
I have a unix time_t , is there any easy way to convert this to a time_t so it: Represents midnight of the day of the time_t ?Represents the start of the hour of the time_t ?
Something like this: ``` time_t t = time(NULL); t -= (t % 86400); ``` The constant 86400 = 24 * 60 * 60 - a useful number to remember, I think... ;)
Consider a functionfoo()that might never exit: ``` int foo(int n) { if(n != 0) return n; else for(;;); /* intentional infinite loop */ return 0; /* (*) */ } ``` Is it valid C to omit the final return-statement? Will it evoke undefined behavior if I leave out that final statement?
Even if it does return without a return statement there is no UB unless you use the return value.
In this piece of code, why in my testing the result is always1,2, and3? ``` #include <stdio.h> void test() { int a; a++; printf("%d",a); } int main(int argc, char *argv[]) { test(); test(); test(); } ``` I think the variable intest()is static, isn't it? And Why?
The variable is not static. You're accessing an uninitialized variable. The behavior is undefined.
In this piece of code, why in my testing the result is always1,2, and3? ``` #include <stdio.h> void test() { int a; a++; printf("%d",a); } int main(int argc, char *argv[]) { test(); test(); test(); } ``` I think the variable intest()is static, isn't it? And Why?
The variable is not static. You're accessing an uninitialized variable. The behavior is undefined.
I find myself always appending the name of the enum, to its values, because else I often have conflicts with other enums, for example: ``` typedef enum { A_ONE, A_TWO, } A; typedef enum { B_ONE, B_TWO, } B; ``` Is there a nicer way to do this in C?
No, there is not. C++ has namespaces, or enums existing in classes (IIRC), but C is extremely primitive in this regard.
When I call: ``` write_byte((uint8_t*)0); ``` It passes a null-pointer. How can I modify it to pass a pointer to the literal value 0?
It passes a NULL pointer. You cannot take the address of a constant (&0). If you want to pass a pointer to the value0, you must assign0to a variable first. ``` uint8_t i = 0; write_byte(&i); ```
Let ``` const char cstring[] = "cstringline"; ``` How can the above code be altered, to append CRLF in compile time aka declaration?
Unix line ending: ``` const char str[] = "foobarbaz\n"; ``` Legacy Mac line ending: ``` const char str[] = "foobarbaz\r"; ``` Windows line ending: ``` const char str[] = "foobarbaz\r\n"; ``` (But really, google...)
``` int main(void){ float f=0,ff=0; if (scanf("%f %f",&f,&ff) == 2){ printf("True\n%f %f",f,ff);fflush(stdout); } else{ printf("False\n%f %f",f,ff);fflush(stdout); } getchar(); return 0; } ``` If my input is "6.81 7.kj" it returns true!!
7.is a valid float. The fact that there's more input left is irrelevant to the success of the call.
I wanted to know like where does the stderr dumps its content. I have a question like whether it dumps to syslog? Please explain.
stderris just another output stream, just likestdout. Where it's hooked up depends on how the application is called. For example if I runfoo.exe 2> errors.txtthenstderrwill write to the specified file.
I need to get file type without using file extensions on linux. There is "file" utility, which can do this. How can I do the same using C/C++? Not 'system(const char *)', of course... Thanks)
AFAIKfileis implemented overlibmagic. For more reference see: filesourcesand maybe this link:http://linux.die.net/man/3/libmagic.
Good day, I set up Eclipse with MinGW and my project compiles fine: However when I try to run it via creating aRun ConfigurationI have the problem that there is noC/C++ Local Applicationlike here: Mine looks like this: What is missed? What do I need to do?
Select Help → Install New SoftwareType this url:http://download.eclipse.org/tools/cdt/releases/indigoTick the CDT Main Features witch includes c++ sdkRestart eclipse done!
Good day, I set up Eclipse with MinGW and my project compiles fine: However when I try to run it via creating aRun ConfigurationI have the problem that there is noC/C++ Local Applicationlike here: Mine looks like this: What is missed? What do I need to do?
Select Help → Install New SoftwareType this url:http://download.eclipse.org/tools/cdt/releases/indigoTick the CDT Main Features witch includes c++ sdkRestart eclipse done!
Suppose defined:int a[100]Typeprint athen gdb will automatically display it as an array:1, 2, 3, 4.... However, ifais passed to a function as a parameter, then gdb will treat it as a normal int pointer, typeprint awill display:(int *)0x7fffffffdaa0. What should I do if I want to viewaas an array?
Seehere.In short you should do: ``` p *array@len ```
There must be some logic behind this calculation. But I am not able to get it. The normal mathematics does not result in such behavior. Can anyone help me out in explaining why printf ("float %f \n", 2/7 * 100.0);results in printing 1.000000 Why so? I am not understanding the reason
Integer division.2/7 = 0as an integer,0 * 100.0 = 0.0as a float. Do2.0/7 * 100.0to get the answer you're looking for.
I was just curious by default does Microsoft's C/C++ Optimizing Compiler compile down to machine language or byte code?
It compiles down to machine language (microprocessor opcodes) by default, orCIL, using the/clrswitch. For comparison, C# and Visual Basic compile toCIL, and Visual Basic 6 can compile to either P-code (a form of byte code) or native code (machine language).
I have been using msgsend and receive from ``` #include <sys/ipc.h> #include <sys/msg.h> ``` for quite a while now. I just came up with the question whether it is possible to join the communication from a python program. Thank you
sysv_ipcmodule provides API for using System V IPC message queues as well as other IPC primitives (semaphores and shared memory).
I have a flac file and I need to analize its waveform, so I need to have the pcm data in an array. Is there some library which does this for me without converting the file with commandline tools? I can use both Python and C.
I suggest you use libFLAC to decode.http://flac.sourceforge.net/
I'm trying to ping6 an address. If there's a response it's fine. If there's no response, the ping takes anywhere between 100-300ms to return. Is there a way to set the no response time? What's the default no response time?
If there is no response, ping6 will time out, i.e. it will wait for a response for a duration t and then report "destination unreachable". To change the default duration, use the -W option: -W timeout http://man.he.net/man8/ping6
I have a flac file and I need to analize its waveform, so I need to have the pcm data in an array. Is there some library which does this for me without converting the file with commandline tools? I can use both Python and C.
I suggest you use libFLAC to decode.http://flac.sourceforge.net/
``` CvMat* nextimg = 0; int firstframe; firstframe=nextimg==0; ``` if I don't put "==0" returns the following warning: ``` [Warning] assignment makes integer from pointer without a cast ```
Its a shortened equivalent of ``` int firstframe; if (nextimg == 0) { firstframe = 1; } else { firstframe = 0; } ```
I would like to return+INFbut instead, I am only returning "inf": ``` int main(void) { double dubb = HUGE_VAL; printf("%f \n", dubb); } ``` Am I overlooking something here? Or it is just compiler semantics?
Useprintf("%+F\n", dubb);instead '+' makes printf display the sign 'F' makes inf/nan uppercase
I would like to return+INFbut instead, I am only returning "inf": ``` int main(void) { double dubb = HUGE_VAL; printf("%f \n", dubb); } ``` Am I overlooking something here? Or it is just compiler semantics?
Useprintf("%+F\n", dubb);instead '+' makes printf display the sign 'F' makes inf/nan uppercase
Consider the following code. ``` char message[]="foo"; void main(void){ message[] = "bar"; } ``` Why is there a syntax error in MPLAB IDE v8.63? I am just trying to change the value of character array.
You cannot use character array like that after declaration. If you want to assign new value to your character array, you can do it like this: - ``` strcpy(message, "bar"); ```
Whenever NaN is returned, I would like for the value returned to instead be 0. What is the best way to go about achieving this end?
You can use this function ``` float zero_nan(float n) { return n == n ? n : 0; } ``` you can inline the function and wrap any return values you think may be nans.
I haveuint8_t orig[ETH_ALEN]; How can I print it using__printf(3, 4) which is defined as#define __printf(a, b) __attribute__((format(printf, a, b))) the Orig should be ethernet hardware address.
Use C99 format specifiers: ``` #include <inttypes.h> printf("%" PRIu8 "\n", orig[0]); ```
``` #include<stdio.h> #include<stdlib.h> #define d 10+10 int main() { printf("%d",d*d); return 0; } ``` I am new to the concept of macros.I found the output for the above program to be 120.What is the logic behind it? Thanks.
``` 10+10*10+10 == 10 + 100 + 10 ``` Is that clear?
I wan to define enum with non constant step. I want that the step between 2 enum variables looks like that: ``` enum test { a1 = 1, a2 = 1<<2, a3 = 1<<3, a4, // a4 deduced automatically as 1<<4 a5 // a5 deduced automatically as 1<<5 } ``` Are there a way to define it as indicated in the above example?
You must do this manually, or possibly with macro chicanery.
I wan to define enum with non constant step. I want that the step between 2 enum variables looks like that: ``` enum test { a1 = 1, a2 = 1<<2, a3 = 1<<3, a4, // a4 deduced automatically as 1<<4 a5 // a5 deduced automatically as 1<<5 } ``` Are there a way to define it as indicated in the above example?
You must do this manually, or possibly with macro chicanery.
In my C program, I am printing a string to the command terminal usingprintf("%d %s %s\n", node->id, node->date, node->input);but I need to now use the write functionwrite(STDOUT_FILENO, cmdline, strlen(cmdline));... How can I format the string like I did using printf?
Usesprintf/snprintfto format the string into a character buffer, and thenwritethat.
How do I run an executable file likea.outusing the standard C library functionsexec(). Thanks in advance.
Whatever isexec, it is not C standard. If you are speaking aboutexecve(POSIX), look at the documentation. ``` int execve(const char *filename, char *const argv[], char *const envp[]); ``` So: ``` #include <unistd.h> char *args[] = { "./a.out", /* other arguments */, NULL }; execve("a.out", args, NULL); ```
I am trying to set flag tcp_nodelay on a unix domain socket. Can we set it or does it even make sense to set tcp_nodelay for UNIX domain sockets, specifically on Linux? please advise. thanks
Unix domain sockets don't use Nagle (and obviously don't use TCP either). Also, the fact that it's calledtcp_nodelayindicates it's a TCP-only thing.
In my C program, I am printing a string to the command terminal usingprintf("%d %s %s\n", node->id, node->date, node->input);but I need to now use the write functionwrite(STDOUT_FILENO, cmdline, strlen(cmdline));... How can I format the string like I did using printf?
Usesprintf/snprintfto format the string into a character buffer, and thenwritethat.
``` #include<stdio.h> int main() { int a=5,*b,*c; b=&a; c=b; *b++=*c++; printf(" %d %d %d\n",&a,b,c); } ``` Here if adress of a is x, then value of b and c is both becoming x+4. But shouldn't two ++ operator increase atleast one value by 8
No. Don't confuse the value of a pointer with the value that it pointsto. The expression*b++means: retrieve the value that b pointsto, and then increment the value of b.