question
stringlengths
25
894
answer
stringlengths
4
863
I have printer HP LaserJet P2015 Series configured in the lan and i have enabled the snmp access in the printer. Need a way to get output for snmp-mib's ? via c , c++ or java
For Java, take a look at thesnmp4jproject. For C, take a look at theNet-SNMPproject. Both projects are open source and provide SNMP client APIs.
My program needs Process 0 to keep incrementing a counter and send messages until it receives a message from the last process in the program, which then have Process 0 decrement the same counter and send messages. I don't know how to "Listen"/Poll whether a message has been received My Case: (i is counter) While Pro...
Generally, you would useMPI_Isend,MPI_Irecv, andMPI_Testfor polling. Read your book's chapters on nonblocking communication.
I think the title is self explanatory. I am making a program and I was wondering what I should use of the two and why.
argpmay be more flexible / powerful / etc, butgetoptis part of the POSIX standard. Thats a choice you've to make based on whether you expect your program to be portable.
Is there a way in gcc or clang (or any other compiler) to spit information about whether a struct has holes (memory alignment - wise) in it ? Thank you. ps: If there is another way to do it, please do inform me.
You can usepaholeto output information about holes in structures and optionally attempt packing them. You may want to read"Poke-a-hole and friends"andthe pahole announcementfor more information
I want to use GCOV to make code coverage but the tests will run on another machine. So the hard wired path to .gcda files in the executable won't work. In order to change this default directory I can use the GCOV_PREFIX and GCOV_PREFIX_STRIP env vars, as it's saidhere. Here my commands I used: ``` $ export GCOV_PRE...
The environment variables are taken into account when you run the code. Set them to the appropriate values on the target machine before you run your tests, and the.gcdafiles will be generated where you want them.
I am learning C with "The C Programming Language", 2nd edition, and also doing each exercise. Do I need to know assembly in order to debug C programs that I wrote as solutions to the books exercises? Also, which debugger do you recommend?
You do notneedto know assembly to program in C, including debugging. However, if you know assembly, C begins to make a lot of sense; it really helps to have some notions of assembly (preferably, some notions on several distinct architectures, such as x86 and ARM), and not only for debugging.
So, for example, I want to link a boost::thread library, I have to type -lboost_thread in the command line. However, how do I know the name of other libraries, so I don't have to guess the name to put in the command line. For example, to link thread library, I put -lboost_thread as a random guess from another linking ...
Read themanual that comes with the library.
am developing one dictionary for mac os 10.6. Am not able to locate glib.h. can i get this as a library or framework. am confused very much. please give me your valuable solution. Note: i want to use GSList from glib
Install it usingMacPortsor download the source code and install manually. Or if you're developing a cocoa aplication I'm sure the framework has it's own list structures, it would be better to use the native ones.
I was wondering what is the best way to convert a 24-bit RGB color (8 bits per color) into an 8-bit color (2bits Blue, 3 Green, 3 Red). I'd like C code for doing this.
8 bit RGB is normally an indexed (palettized) color format, seePalette (computing). The way you described it though, getting 8 bpp out of 24 bpp is pretty straightforward - you would need to strip least significant bits and merge the bits into single byte value, per pixel. AFAIK it is not a standard or well-known pix...
This question already has answers here:What is the type of variable?(2 answers)Closed9 years ago. Im working with Ruby c extension, I have following sample code, ``` const char varP[] = "exceptionString"; VALUE reValue = rb_funcall(*Ptr, rb_intern("exception"), 1, rb_str_new2(varP)); ``` rb_funcall() function retur...
you can find this all just by googling...this function is defined in ruby.h see thishttp://svn.joyent.com/opensource/dtrace/ruby/ruby-1.8.5/ruby.h
Should the function prototype in C be in main or before main. I was taught before main, but my friends class book shows it in main. Which is the correct way? His book shows it: ``` int main() { void numberTable(); numberTable(); } void numberTable() { int num; ...rest of the code... } ```
Both are correct.If you add the function declaration inside main, its scope is inside the main{}.If you add it outside main, its scope is the entire source file.
This question already has answers here:How does strcmp() work?(9 answers)Closed6 years ago. I am learning aboutstrcmp()in C. I understand that when two strings are equal,strcmpreturns 0. However, when the man pages state thatstrcmpreturns less than 0 when the first string is less than the second string, is it referr...
In this sense, "less than" for strings means lexicographic (alphabetical) order. Socatis less thandogbecausecatis alphabetically beforedog. Lexicographic order is, in some sense, an extension of alphabetical order to all ASCII (and UNICODE) characters.
I'm trying to output and C++ Array (int inverse[3]) usingNSLog, but If I try this way: ``` NSLog([NSString stringWithFormat:@"%d", inverse]); ``` It just dont work, But if I try like this: ``` NSLog([NSString stringWithFormat:@"%d", inverse[0]]); ``` I get the right output. My objective is to get the whole array o...
Use a for loop to print all the values. ``` for (int i=0; i<3; i++) { NSLog(@"%i", inverse[i]); } ``` or: ``` NSLog(@"%i, %i, %i", inverse[0], inverse[1], inverse[2]); ```
In the Haskell FFI, what is the essential difference between arrays allocated withwithArrayandnewArray? I have function in c that works withnewArraybut segfaults withwithArray. The working code looks bit like this: ``` a <- newArray items fficall a free a ``` The code that segfaults looks like this: ``` withArray i...
From what I can see,newArrayends up callingmallocto do the allocation, whilewithArraycallsallocaArray, which ends up innewAlignedPinnedByteArray#. Perhaps your function is relying on the memory being allocated bymalloc, for example by attempting toreallocorfreeit?
What is the difference between Type** name, and Type* name[]? Why would someone use one over the other? Thanks
Well that depends, is it in a variable declaration or in a function argument? If in a variable declaration: ``` Type** name = &pointer_to_type; Type* name[] = { &pointer_to_type, 0, &pointer_to_type }; ``` The first one is a pointer to pointer to type, while the second one is an array of pointers to type of length 3...
I have a struct like this: ``` typedef struct stringd{ char **x; }s; ``` and a two dimensional char array declared as ``` char *c[32]; ``` I am filling up the char array inside a loop and at the end passing it to the struct *s. What would be the right way of doing this? ``` s->x = &c; or s->x = c; ``` both do ...
cis an array of 32 pointers to char, that is, of typechar *[32], and as any array, it can decay automatically and trivially into a pointer to the first element of the array, which is of typechar **. That seems to be what you need. &c, however is of type pointer to an array of 32 pointers to char, that is,char *(*)[32...
I am using "TerminateProcess (procHandle, 0)" to kill threads. It works for most, but some threads it can't kill. WHY? Also the task manager can't kill those threads either. Is there a way to force kill any thread? What else can I do? thx
Normally you cannot kill processes of other users if you don't have required rights. For example it is not possible to kill processes running as SYSTEM user, processes of other users on a terminal server, etc. Citation from MSDN: "The handle must have the PROCESS_TERMINATE access right. For more information, see Proc...
I'm writing in C, I'm using libcurl+openSSL to send POST request. In case of Amazon S3, I have to makesignature in my request, that is formed as RFC 2104 HMAC-SHA1 from AWS Secret Access Key. Advise, please, where can I get the implementation of that algorithm, that will suit Amazon? IsopenSSL function SHA1the one?
HMAC is a way to combine a message and a key securely using a hash function (in this case SHA1). Fortunately, OpenSSL includes an implementation of both, so you shouldn't need to touch the SHA1 function directly. See thedocumentation for HMACin OpenSSL.
I am a java programmer and currently learning antlr3. I have to use antlr in a C project.It is a little difficult for a java programmer to write C code use antlr. So, I want to look some C project that use antlr I find a lot of java project that use antlr, eg. hive, esperbut I could not find a C project. anyone kn...
Here's some BSD-licensed C++ code which uses an ANTLR3-generated C parser:AST traversal,error handling.
Im working on Ruby c extension, I have following code from c program, ``` VALUE var = myFunction(arg1, arg2); int varType = TYPE(var); printf("Type of the var is :: %d", varType); ``` Above printf gives output as follow: ``` Type of the var is :: 34 ``` As myFunction is inbuild function i dont know the return type...
TheTYPEmacro returns values enumerated inruby.h. From there, it follows 34 is T_DATA, which is awrapped C structure.
I'm playing with pointers and a can't get why this declaration is fine ``` char *ptr = "Hey" ``` but this is wrong ``` int *ptr = 10; ``` Can any one explain ?
The correct analogy would be that the following two arebothwrong: ``` char * p = 'a'; // error int * q = 123; // error ``` Here you are trying to assign a value of some type to a variable that is apointerto a variable of that type. By contrast, the following are correct: ``` int tmp_a[] = { 10, 20, 30 }; char ...
Here I wrote a little app which is able to read command line arguments ``` int main (int argc, const char * argv[]) { int c; while ((c = getopt (argc, argv, "Il:o:vh?")) != -1) { switch(c) { case 'I': printf("I"); break; } } re...
Theargvargument tomainshould have typechar *[], notconst char *[]so that it can be converted to thechar *const []thatgetoptexpects. In fact,char *[]or equivalent is mandated by the C standard for hosted implementations.
I wrote a little program which prints help information if argument is not passed. If I run the app without arguments ``` ./myApp ``` it prints ``` ./myApp --filename=file ``` I know that argv[1] holds the first parameter, but I can't figure out how to fetch the text after "=" ie the name of file.
Instead of parsing the string manually, you should rather usegetopt()orgetopt_long(). They do the dirty work for you and behave in the way people expect it (while self-written parsers are sometimes confusing - some use--arg value, others--arg=value, some even use-arg value)
Is there some Linux analog of windows functionGetAsyncKeyState()? Or maybe there exists some asynchronous function which returns - Does keyboard buffer empty or not ? Thanks.
The key question here is: For which abstraction? X windows, ncurses or stdio? Linux isn't as simple and monolithic as Windows is. For stdio (plain old stdin/stdout text program)fgetc_unlockeddoes the trick.
When you write#include "foo.h"I would expect the compiler to check the directory of the file doing the including (as opposed to the current directory) first, and if not found there then fall back on a search of the list of paths as in the case of#include <foo.h>. Unless an absolute path was specified,#include "/foo.h...
Kernighan & Ritchie write: [#include "foo"] searches first in association with the original source file (a deliberately implementation-dependent phrase), and if that search fails, then as in the first form. Which means, make no assumption on the search strategy for quotes. However, all compilers I have run into shar...
I recently came accross some C++ code like the following: ``` if(test_1) if(test_2) { // Do stuff } else exit(0); ``` This is ambiguous, since the compiler could see this as: ``` if(test_1) { if(test_2) { } else { } } ``` or as: ``` if(test_1) { if(test_...
Is the behaviour of this code defined according to any standard (C, C++)? Yes, it is defined. In C (and all similar languages as I know), the "dangling else" binds to the last free if, therefore this interpretation ``` if(test_1) { if(test_2) { } else { } } ``` is correct.
This question already has answers here:Closed11 years ago. Possible Duplicate:Good STL-like library for CAre there any open source C libraries with common data structures? The Apache Commons project has always struck me as being the library of all things that were forgotten in the Java language. Nowadays I almost al...
Check out the Gnome project'sGLib.
How can I find the current locale's charset in C? setlocale(LC_ALL, NULL) returns "en_US.UTF8", but is there a way to get the charset? In /etc/locale.gen on my system it lists the locales and the charsets, so it's not in the name.
You can query various parameters of the current locale using thenl_langinfo(3)function. The charset is obtained by callingnl_langinfo(CODESET). Note, that you have to callsetlocalebefore usingnl_langinfoto make your program locale-aware.
How do I do the following: ``` int A[2][2]; int B[2]; A[1][0]=2; B=A[1]; printf("%d",B[0]); //prints out 2 ``` must I use malloc? I know that in higher level languages the above method works, but I'm a little confused about what to do in C
You cannot assign to arrays (though you caninitializethem, which is very different). You can do what you want, by assigning toBelement-by-element ``` B[0] = A[1][0]; B[1] = A[1][1]; ``` or, with a loop ``` for (k=0; k<2; k++) B[k] = A[1][k]; ```
I am trying to record a video in OpenCV from a stream such as a webcam with audio. I am currently writing the application to use DirectShow to grab data from the stream and to pass that data into anIplImage*. This is great for creating the video file, but what if I would like to include audio? Do I have to use another...
No, it is not a purpose of OpenCV library.
I'm writing in C, I'm using libcurl+openSSL to send POST request. In case of Amazon S3, I have to makesignature in my request, that is formed as RFC 2104 HMAC-SHA1 from AWS Secret Access Key. Advise, please, where can I get the implementation of that algorithm, that will suit Amazon? IsopenSSL function SHA1the one?
HMAC is a way to combine a message and a key securely using a hash function (in this case SHA1). Fortunately, OpenSSL includes an implementation of both, so you shouldn't need to touch the SHA1 function directly. See thedocumentation for HMACin OpenSSL.
I am a java programmer and currently learning antlr3. I have to use antlr in a C project.It is a little difficult for a java programmer to write C code use antlr. So, I want to look some C project that use antlr I find a lot of java project that use antlr, eg. hive, esperbut I could not find a C project. anyone kn...
Here's some BSD-licensed C++ code which uses an ANTLR3-generated C parser:AST traversal,error handling.
Im working on Ruby c extension, I have following code from c program, ``` VALUE var = myFunction(arg1, arg2); int varType = TYPE(var); printf("Type of the var is :: %d", varType); ``` Above printf gives output as follow: ``` Type of the var is :: 34 ``` As myFunction is inbuild function i dont know the return type...
TheTYPEmacro returns values enumerated inruby.h. From there, it follows 34 is T_DATA, which is awrapped C structure.
I'm playing with pointers and a can't get why this declaration is fine ``` char *ptr = "Hey" ``` but this is wrong ``` int *ptr = 10; ``` Can any one explain ?
The correct analogy would be that the following two arebothwrong: ``` char * p = 'a'; // error int * q = 123; // error ``` Here you are trying to assign a value of some type to a variable that is apointerto a variable of that type. By contrast, the following are correct: ``` int tmp_a[] = { 10, 20, 30 }; char ...
Here I wrote a little app which is able to read command line arguments ``` int main (int argc, const char * argv[]) { int c; while ((c = getopt (argc, argv, "Il:o:vh?")) != -1) { switch(c) { case 'I': printf("I"); break; } } re...
Theargvargument tomainshould have typechar *[], notconst char *[]so that it can be converted to thechar *const []thatgetoptexpects. In fact,char *[]or equivalent is mandated by the C standard for hosted implementations.
I wrote a little program which prints help information if argument is not passed. If I run the app without arguments ``` ./myApp ``` it prints ``` ./myApp --filename=file ``` I know that argv[1] holds the first parameter, but I can't figure out how to fetch the text after "=" ie the name of file.
Instead of parsing the string manually, you should rather usegetopt()orgetopt_long(). They do the dirty work for you and behave in the way people expect it (while self-written parsers are sometimes confusing - some use--arg value, others--arg=value, some even use-arg value)
Is there some Linux analog of windows functionGetAsyncKeyState()? Or maybe there exists some asynchronous function which returns - Does keyboard buffer empty or not ? Thanks.
The key question here is: For which abstraction? X windows, ncurses or stdio? Linux isn't as simple and monolithic as Windows is. For stdio (plain old stdin/stdout text program)fgetc_unlockeddoes the trick.
When you write#include "foo.h"I would expect the compiler to check the directory of the file doing the including (as opposed to the current directory) first, and if not found there then fall back on a search of the list of paths as in the case of#include <foo.h>. Unless an absolute path was specified,#include "/foo.h...
Kernighan & Ritchie write: [#include "foo"] searches first in association with the original source file (a deliberately implementation-dependent phrase), and if that search fails, then as in the first form. Which means, make no assumption on the search strategy for quotes. However, all compilers I have run into shar...
I recently came accross some C++ code like the following: ``` if(test_1) if(test_2) { // Do stuff } else exit(0); ``` This is ambiguous, since the compiler could see this as: ``` if(test_1) { if(test_2) { } else { } } ``` or as: ``` if(test_1) { if(test_...
Is the behaviour of this code defined according to any standard (C, C++)? Yes, it is defined. In C (and all similar languages as I know), the "dangling else" binds to the last free if, therefore this interpretation ``` if(test_1) { if(test_2) { } else { } } ``` is correct.
This question already has answers here:Closed11 years ago. Possible Duplicate:Good STL-like library for CAre there any open source C libraries with common data structures? The Apache Commons project has always struck me as being the library of all things that were forgotten in the Java language. Nowadays I almost al...
Check out the Gnome project'sGLib.
How can I find the current locale's charset in C? setlocale(LC_ALL, NULL) returns "en_US.UTF8", but is there a way to get the charset? In /etc/locale.gen on my system it lists the locales and the charsets, so it's not in the name.
You can query various parameters of the current locale using thenl_langinfo(3)function. The charset is obtained by callingnl_langinfo(CODESET). Note, that you have to callsetlocalebefore usingnl_langinfoto make your program locale-aware.
How do I do the following: ``` int A[2][2]; int B[2]; A[1][0]=2; B=A[1]; printf("%d",B[0]); //prints out 2 ``` must I use malloc? I know that in higher level languages the above method works, but I'm a little confused about what to do in C
You cannot assign to arrays (though you caninitializethem, which is very different). You can do what you want, by assigning toBelement-by-element ``` B[0] = A[1][0]; B[1] = A[1][1]; ``` or, with a loop ``` for (k=0; k<2; k++) B[k] = A[1][k]; ```
I am trying to record a video in OpenCV from a stream such as a webcam with audio. I am currently writing the application to use DirectShow to grab data from the stream and to pass that data into anIplImage*. This is great for creating the video file, but what if I would like to include audio? Do I have to use another...
No, it is not a purpose of OpenCV library.
For any Linux BlueZ/BT experts here: I'm looking for a way to "ping" known BT devices (known BDADDR) and if they are in range I'd like to know the approximate signal strength. I know that I could first run l2ping, then establish a connection to the device and finally check the rssi or link quality if the connection ...
You can obtain RSSI during inquiry scan, without connecting to devices. Here's an example using pybluez. You could also do the same thing directly from C using Bluez on linux. inquiry-with-rssi.py
I'm looking for an IDE that supports a (Visual Studio's) Edit and continue -like feature. I know Netbeans has it for Java (called hotswapping, Fix and continue), but can not find anything about an implementation for C/C++ for Linux systems. Any help would be very much appreciated.
To the best of my knowledge, this feature is not available in the GCC toolchain. The closest you'll get is the gdb's rewind, but that's not the same.
I have the following piece of code in C: ``` char a[55] = "hello"; size_t length = strlen(a); char b[length]; strncpy(b,a,length); size_t length2 = strlen(b); printf("%d\n", length); // output = 5 printf("%d\n", length2); // output = 8 ``` Why is this the case?
it has to be 'b [length +1]' strlen does not include the null character in the end of c strings.
In C why is it legal to do ``` char * str = "Hello"; ``` but illegal to do ``` int * arr = {0,1,2,3}; ```
I guess that's just how initializers work in C. However, you can do: ``` int *v = (int[]){1, 2, 3}; /* C99. */ ```
I'm trying to write a quick function to remove underscore characters ``` char yytext[25] = {"IDEN_T3FY_ER"}; char removeUnderscore[9]; int i, j = 0; printf("Before: %s\n", yytext); for (i = 0; i < strlen(yytext); i++){ if (j == 8) break; if (yytext[i] != '_') removeUnderscore[j++] = yytext[...
You are incrementing your index variable j before writing the null character to terminate the string. Try: ``` removeUnderscore[j] = '\0'; ``` instead. You also say there should be a newline character at the end but you've never written a newline character to the output string.
I need to traverse a directory depth first without using boost but I have not been able to find a good tutorial how to do this. I know how to list the files of the directory, but not sure how to about this one. This list the files of a directory:
Use theftwornftwfunctions if your system has them. Or, grab thefts_*functions from, e.g., theOpenBSD source treeand study those, or use them directly. This problem is harder than you might think, because you can run out of file descriptors when recursing through deep filesystem hierarchies.
usually the practice is not to include binaries in source control repositories, i am using mercurial, and would like to know if anyone has experience with embedding version (minor + major) in a C Binary, so that when its distributed if i use a command line argument like mybinaryApp --version, i will get a unique versi...
The way that I embed version numbers in the code is to#define _VERSION_MAJORin a separate header file, include them in files that need the version number, and then use that macro where needed. Then, you are free to control the version number in a different source file, without having to continually modify the origina...
I am learning C programming, I wrote the sample code to accept parameters from terminal and print out the arguments. I invoke the program like this: ./myprogram 1 I expected 1 to be printed out for the argument length instead of 2. why it is so? There was no spacing after the argument "1" ``` #include <stdio.h> #in...
The first argument,argv[0]is the name with which the program was invoked. So there are two arguments and the second,argv[1]is "1". EDIT Editing to make clear:argcshould always be checked. However uncommon, it is perfectly legal forargcto be 0.For example on Unix,execvp("./try", (char **){NULL});is legal.
Are distributed systems a completely independent concept compared to symmetric multiprocessing (since in distributed, we have individual memory/disk storage per CPU whereas in symmetric we have many CPU's utilizing the same memory/disk storage)?
I wouldn't say they are completely different concepts, because you can get a shared memory in distributed systems (usingDistributed shared memory), and multiple processes running on the same machine don't share their address space. So both environments can exists on both architectures, but with a cost. In general, sha...
I'm trying to plug a hole in my knowledge. Why variadic functions require at least two arguments? Mostly from C'smainfunction havingargcas argument count and thenargvas array of arrays of chars? Also Objective-C's Cocoa hasNSStringmethods that require format as first argument and afterwards an array of arguments ([NSS...
argc/argv stuff is not really variadic. Variadic functions (such asprintf()) use arguments put on the stack, and don't require at least 2 arguments, but 1. You havevoid foo(char const * fmt, ...)and usuallyfmtgives a clue about the number of arguments. That's minimum 1 argument (fmt).
the following code can be compiled correctly on both VC or gcc: ``` char *str = "I am a const!"; str[2] = 'n'; ``` however, obviously there is a run-time-error. Since "I am a const!" is aconst char*, why the compiler doesn't give an error or even a warning ?? Besides, if I definechar a[] = "I am const!", all the ...
As far as C is concerned, that string literal is not const, it's achar[14]which you assign to a char*, which is perfectly fine. However, C does say that changing a string literal is undefined behavior.
I am trying to get a C string of the owner and group of a file, After I do astat()I get the user ID and group ID, but how do I get the name?
You can usegetgrgid()to get the group name andgetpwuid()to get the user name: ``` #include <pwd.h> #include <grp.h> /* ... */ struct group *grp; struct passwd *pwd; grp = getgrgid(gid); printf("group: %s\n", grp->gr_name); pwd = getpwuid(uid); printf("username: %s\n", pwd->pw_name); ```
I am having trouble with my code, and I can not solve .... the code snippet where the error is reported: ``` static FILE *debugOut = stderr; static FILE *infoOut = stdout; ``` The error that the gcc return is: ``` initializer element is not constant ```
try doing it in main for example: ``` static FILE *debugOut; static FILE *infoOut; main(){ debugOut = stderr; infoOut = stdout; } ```
Given a struct definition that contains one double and three int variables (4 variables in all), if p is a pointer to this struct with a value 0x1000, what value does p++ have? This is not a homework problem, so don't worry. I'm just trying to prepare for a test and I can't figure out this practice problem. Thanks ...
``` struct foobar *p; p = 0x1000; p++; ``` is the same as ``` struct foobar *p; p = 0x1000 + sizeof(struct foobar); ```
I have a function in C++ that takes a char array thingArray[6] and places ' ' onto each place. like: ``` for (int i =0; i<5; i++) { thingArray[i] = ' '; } ``` now I have another function that sticks a character if it finds an empty space in the array. please say the array now looks like: 'w',' ','R',...
IfthingArrayis a string literal, then it's actually constant and you can't change the value of its elements.
In my School my project is to make a simple program that controls the LED lights my professor said that outp() is in the conio.h, and I know that conio.h is not a standard one. example of outp() ``` //assume that port to be used is 0x378 outp(0x378,1); //making the first LED light ``` thanks in advance
You can do this from user space in Linux by writing to/dev/portas long as you have write permissions to/dev/port(root or some user with write permissions). You can do it in the shell with: ``` echo -en '\001' | dd of=/dev/port bs=1 count=1 skip=888 ``` (note that 888 decimal is 378 hex). I once wrote a working par...
I have been asked in an interview how do you pass an array to a function without using any pointers but it seems to be impossible or there is way to do this?
Put the array into a structure: ``` #include <stdio.h> typedef struct { int Array[10]; } ArrayStruct; void printArray(ArrayStruct a) { int i; for (i = 0; i < 10; i++) printf("%d\n", a.Array[i]); } int main(void) { ArrayStruct a; int i; for (i = 0; i < 10; i++) a.Array[i] = i * i; printArray(a)...
How do you define constant array of constant objects in C (not C++)? I can define ``` int const Array [] = { /* init data here */ }; ``` but that is a non-constant array of constant objects. I could use ``` int const * const Array = { /* init data here */ }; ``` and it would probably work. But is it poss...
An array cannot be "constant" -- what is that even supposed to mean? The array size is already a compile-time constant in any case, and if all the members are constants, then what else do you want? What sort of mutation are you trying to rule out that is possible for aconst int[]?
A few days back I had an interview, and I was asked to write a program in C which crashes the system/which shuts down the system. Needless to say I felt pretty dumb having no clue on how to even approach :( Still I gave it a try, writing programs which use a lot of memory. But my interviewer was not satisfied with an...
It's easy to write a program that invokes undefined or implementation-defined behavior. Some of those programs could potentially crash the system. But by definition, this is inconsistent. And modern OSes take pains (though not 100% successfully) to prevent a rogue app from crashing the system.
I have a unsigned char pointer which contains a structure.Now I want to do the following ``` unsigned char *buffer ; //code to fill the buffer with the relavent information. int len = ntohs((record_t*)buffer->len); ``` where record_t structure contains a field called len.I am not able to do so and am getting the e...
inCyou can't just takebuffer->len, because it's being parsed as if the final resultbuffer->lenis being cast to arecord_t *. Try ``` ((record_t *)buffer)->len ```
This question already has an answer here:Closed11 years ago. Possible Duplicate:Preventing SQL Injection in C I know PHP has some built in functions that help to sanitize queries, but does C have anything like that? ``` snprintf(&buff[0],1023,"UPDATE grades SET grade='%c' WHERE username='%s'",choice,&uname[0]); if...
TheMySQL C APIhas amysql_real_escape_string()function.
I'm trying to call ``` sys_readlink(const char __user *path, char __user *buf, int bufsiz) ``` directly, but get EFAULT error code. This error appears becausebufpoints to memory from kernel-space. So, is there possible way to allocate user-space memory from kernel ? kmalloc(size, GFP_USER)is similar tokmalloc(size...
You can temporarily disable memory address validity checking by usingset_fs ``` mm_segment_t old_fs; old_fs = get_fs(); set_fs(KERNEL_DS); /* Your syscall here */ set_fs(old_fs); ```
For any Linux BlueZ/BT experts here: I'm looking for a way to "ping" known BT devices (known BDADDR) and if they are in range I'd like to know the approximate signal strength. I know that I could first run l2ping, then establish a connection to the device and finally check the rssi or link quality if the connection ...
You can obtain RSSI during inquiry scan, without connecting to devices. Here's an example using pybluez. You could also do the same thing directly from C using Bluez on linux. inquiry-with-rssi.py
I'm looking for an IDE that supports a (Visual Studio's) Edit and continue -like feature. I know Netbeans has it for Java (called hotswapping, Fix and continue), but can not find anything about an implementation for C/C++ for Linux systems. Any help would be very much appreciated.
To the best of my knowledge, this feature is not available in the GCC toolchain. The closest you'll get is the gdb's rewind, but that's not the same.
I have the following piece of code in C: ``` char a[55] = "hello"; size_t length = strlen(a); char b[length]; strncpy(b,a,length); size_t length2 = strlen(b); printf("%d\n", length); // output = 5 printf("%d\n", length2); // output = 8 ``` Why is this the case?
it has to be 'b [length +1]' strlen does not include the null character in the end of c strings.
In C why is it legal to do ``` char * str = "Hello"; ``` but illegal to do ``` int * arr = {0,1,2,3}; ```
I guess that's just how initializers work in C. However, you can do: ``` int *v = (int[]){1, 2, 3}; /* C99. */ ```
I'm trying to write a quick function to remove underscore characters ``` char yytext[25] = {"IDEN_T3FY_ER"}; char removeUnderscore[9]; int i, j = 0; printf("Before: %s\n", yytext); for (i = 0; i < strlen(yytext); i++){ if (j == 8) break; if (yytext[i] != '_') removeUnderscore[j++] = yytext[...
You are incrementing your index variable j before writing the null character to terminate the string. Try: ``` removeUnderscore[j] = '\0'; ``` instead. You also say there should be a newline character at the end but you've never written a newline character to the output string.
I need to traverse a directory depth first without using boost but I have not been able to find a good tutorial how to do this. I know how to list the files of the directory, but not sure how to about this one. This list the files of a directory:
Use theftwornftwfunctions if your system has them. Or, grab thefts_*functions from, e.g., theOpenBSD source treeand study those, or use them directly. This problem is harder than you might think, because you can run out of file descriptors when recursing through deep filesystem hierarchies.
usually the practice is not to include binaries in source control repositories, i am using mercurial, and would like to know if anyone has experience with embedding version (minor + major) in a C Binary, so that when its distributed if i use a command line argument like mybinaryApp --version, i will get a unique versi...
The way that I embed version numbers in the code is to#define _VERSION_MAJORin a separate header file, include them in files that need the version number, and then use that macro where needed. Then, you are free to control the version number in a different source file, without having to continually modify the origina...
I am learning C programming, I wrote the sample code to accept parameters from terminal and print out the arguments. I invoke the program like this: ./myprogram 1 I expected 1 to be printed out for the argument length instead of 2. why it is so? There was no spacing after the argument "1" ``` #include <stdio.h> #in...
The first argument,argv[0]is the name with which the program was invoked. So there are two arguments and the second,argv[1]is "1". EDIT Editing to make clear:argcshould always be checked. However uncommon, it is perfectly legal forargcto be 0.For example on Unix,execvp("./try", (char **){NULL});is legal.
Are distributed systems a completely independent concept compared to symmetric multiprocessing (since in distributed, we have individual memory/disk storage per CPU whereas in symmetric we have many CPU's utilizing the same memory/disk storage)?
I wouldn't say they are completely different concepts, because you can get a shared memory in distributed systems (usingDistributed shared memory), and multiple processes running on the same machine don't share their address space. So both environments can exists on both architectures, but with a cost. In general, sha...
I'm trying to plug a hole in my knowledge. Why variadic functions require at least two arguments? Mostly from C'smainfunction havingargcas argument count and thenargvas array of arrays of chars? Also Objective-C's Cocoa hasNSStringmethods that require format as first argument and afterwards an array of arguments ([NSS...
argc/argv stuff is not really variadic. Variadic functions (such asprintf()) use arguments put on the stack, and don't require at least 2 arguments, but 1. You havevoid foo(char const * fmt, ...)and usuallyfmtgives a clue about the number of arguments. That's minimum 1 argument (fmt).
the following code can be compiled correctly on both VC or gcc: ``` char *str = "I am a const!"; str[2] = 'n'; ``` however, obviously there is a run-time-error. Since "I am a const!" is aconst char*, why the compiler doesn't give an error or even a warning ?? Besides, if I definechar a[] = "I am const!", all the ...
As far as C is concerned, that string literal is not const, it's achar[14]which you assign to a char*, which is perfectly fine. However, C does say that changing a string literal is undefined behavior.
I am trying to get a C string of the owner and group of a file, After I do astat()I get the user ID and group ID, but how do I get the name?
You can usegetgrgid()to get the group name andgetpwuid()to get the user name: ``` #include <pwd.h> #include <grp.h> /* ... */ struct group *grp; struct passwd *pwd; grp = getgrgid(gid); printf("group: %s\n", grp->gr_name); pwd = getpwuid(uid); printf("username: %s\n", pwd->pw_name); ```
I am having trouble with my code, and I can not solve .... the code snippet where the error is reported: ``` static FILE *debugOut = stderr; static FILE *infoOut = stdout; ``` The error that the gcc return is: ``` initializer element is not constant ```
try doing it in main for example: ``` static FILE *debugOut; static FILE *infoOut; main(){ debugOut = stderr; infoOut = stdout; } ```
Given a struct definition that contains one double and three int variables (4 variables in all), if p is a pointer to this struct with a value 0x1000, what value does p++ have? This is not a homework problem, so don't worry. I'm just trying to prepare for a test and I can't figure out this practice problem. Thanks ...
``` struct foobar *p; p = 0x1000; p++; ``` is the same as ``` struct foobar *p; p = 0x1000 + sizeof(struct foobar); ```
I have a function in C++ that takes a char array thingArray[6] and places ' ' onto each place. like: ``` for (int i =0; i<5; i++) { thingArray[i] = ' '; } ``` now I have another function that sticks a character if it finds an empty space in the array. please say the array now looks like: 'w',' ','R',...
IfthingArrayis a string literal, then it's actually constant and you can't change the value of its elements.
This question already has answers here:Closed11 years ago. Possible Duplicate:C equivalent to fstream's peek Say I have a file with characters in it. I want to look at what the next character is without moving the pointer, just to "peak" at it. how would I go about doing that? ``` FILE *fp; char c, d; fp = fopen (...
You can simply usegetc()to get the next character, followed by a call toungetc(). Update: see @Jonathan's comment for a wrapper that allows for peeking past the end of the file (returningEOFin that event). Update 2: A slightly more compact version: ``` int fpeek(FILE * const fp) { const int c = getc(fp); return...
I am trying to have a program that uses multiple forks.I used this example to get myself startedMultiple fork() Concurrency it works perfectly as is. However, when I try to add a print statement in the child like this: ``` if ((p = fork()) == 0) { // Child process: do your work here printf("child ...
In your example code ``` if (waitpid(childPids[ii], NULL, WNOHANG) == 0) { ``` should be ``` if (waitpid(childPids[ii], NULL, WNOHANG) == childPids[ii]) { ``` because of waitpid(): on success, returns the process ID of the child whose state has changed; on error, -1 is returned; if WNOHANG was specified and no ch...
I have already readTiny C Compiler (TCC) and winsock?, but I still can't compile sockets with TCC, because when I try ``` tiny_impdef winsock.dll -o winsock.def ``` tiny_impdef responds: ``` Not a PE file: C:\WINDOWS\system32\winsock.dll ``` So how can I do to compile properly a program that use sockets? Any help ...
I'm guessing that you have a 64 bit machine andTCCis 32 bit. In that situationC:\WINDOWS\system32\winsock.dllis the 64 bit version of winsock. Try it this way: ``` tiny_impdef C:\WINDOWS\SysWOW64\winsock.dll -o winsock.def ``` to pick up winsock from the 32 bit system directory.
``` #include <stdio.h> void littledot(){}//must use C, not C++ int main() { littledot(568,76,105,84,116,76,101,68,111,84); printf("%c%c%c%c%c%c%c%c%c\n"); getchar(); return 0; } ``` The above code yields the result "LiTtLeDoT". Why does it do that? Why is 568 crucial?
This differs per platform and is UB (the implementation can do anything it wants*), but probably the arguments to littledot() are still on the stack after littledot() returns and printf prints those arguments from the stack. NEVER RELY ON THIS! *really anything. Afaik an ancient version of GCC started a videogame ...
I need to read a file and store each number (int) in a variable, when it sees \n or a "-" (the minus sign means that it should store the numbers from 1 to 5 (1-5)) it needs to store it into the next variable. How should I proceed? I was thinking of using fgets() but I can't find a way to do what I want. The input lo...
I'd usefscanfto read oneintat a time, and when it's negative, it is obviously the second part of a range. Or is-4--2a valid input?
After seeingthisanswer I have this doubt. In my project, I have seen some extern variables declared and defined like below: file1.h ``` extern int a; ``` file1.c ``` extern int a=10; ``` But in the link I mentioned it says that in the c file it should be defined like: ``` int a = 10; ``` Does addingexternkey wo...
It does not change the meaning.externonly makes sense when youdeclarea variable.Defininga variable withexternis the same because all global variables that are not markedstaticare symbols visible to the linker by default. Note that if you didn't want to initialise the variable, that is, not having the part= 10, the co...
How to define local static variables (that keeps its value between function calls) that are not shared among different threads? I am looking for an answer both in C and C++
on Windows using Windows API:TlsAlloc()/TlsSetValue()/TlsGetValue() on Windows using compiler intrinsic: use_declspec(thread) on Linux (other POSIX???) :get_thread_area()and related
I am having a problem scanning chars into an array. Every time I do it will skip the next scan and go to the next. I know what is happening because the input also adds '\n' to the input but I do not know how to remedy the cause of it. Here is some sample code: ``` char charray [MAX], ffs; int inarray [MAX], i; for ...
You can do like this. ``` while((c = getchar()) != '\n') { putchar(c); } ``` this may solve your problem. or you can go till EOF also.
I'm using therecvfunction in a loop to receive network data, but let's say I want to stop receiving data mid-loop. I could just break the loop, but this doesn't seem like a very clean way to stop receiving data. So is there any way to cleanly stop receiving data, or is just breaking the loop ok? It's HTTP GET/POST re...
Breaking out of the recv loop won't close the connection. All that happens is that you stop calling recv and therefore stop reading data from the socket. Data from the peer will still be arriving on your socket. If you want to cleanly shutdown then callcloseon the socket file descriptor.
I want to run a C program that draws a circle. The program is compiling with no error and it is running. After getting the values like radius from the user, I get the error like this : BGI error: Graphics not initialized ( use "initgraph") Even though in my source code I have added this line : ``` int gmode,gdrive=...
Your path ininitgraphis wrong. Use"c:\\tc\bgi"instead.
I have this code in linux kernel: ``` #define task_cred_xxx(task, xxx) ({ __typeof__(((struct cred *)NULL)->xxx) ___val; rcu_read_lock(); ___val = __task_cred((task))->xxx; rcu_...
Correct. It will return___val. However, block expressions like these are a GNU extension and isn't actually part of the C standard. http://www.toofishes.net/blog/gcc-compound-statement-expressions/
I have a client/server program in c. While the server runs, I can send it command via telnet and it works fine. In addition, nmap reports the port to be open. Similarly, I can successfully use(connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr))if my IP is the address of google. However, If I try and use1...
You either have a local firewall that is preventing your client program from connecting (you may need to whitelist the client program if this is on Windows) or you're filling in the IP address you pass toconnectincorrectly. Depending on the OS you're using you should either checkerrnoorGetLastError()to see what went w...
I want to generate (pseudo) random numbers between 0 and some integer. I don't mind if they aren't too random. I have access to the current time of the day but not the rand function. Can anyone think of a sufficiently robust way to generate these? Perhaps, discarding some bits from time of day and taking modulo my int...
If you're after an ultra-simple pseudo-random generator, you can just use aLinear Feedback shift Register. The wikipedia article has some code snippets for you to look at, but basically the code for a 16-bit generator will look something like this (lightly massaged from that page...) ``` unsigned short lfsr = 0xACE1...
I am trying to build config file parser (c++ application)from scratch using tools like lex and yacc. The parser will be able to parse files like ``` # Sub group example petName = Tommy Owner = { pet = "%petName%" } ``` Is there any step by step guide/link to articles on how to achieve this using tools like lex an...
Boost Property Tree It was designed for configuration files. It does reading, writing in the following formats: INIINFOXMLJSON Here is the five minute tutorial page which should give you a good idea: http://www.boost.org/doc/libs/1_47_0/doc/html/boost_propertytree/tutorial.html
I have a requirement where I want to associate anindexwith a file(in a certain format). I was wondering if I can do any ELF manipulation and still ensure that, consistency is maintained so, the file works fine on linux. The idea here is to create a file format which can be queried by a certain API[self-defined] to get...
You can add a new ELF section with whatever data you want to an existing executable. e.g. ``` $ echo 42 > /tmp/index $ objcopy --add-section .my_index=/tmp/index /bin/ls myls $ objdump -s myls | tail . . . Contents of section .my_index: 0000 34320a 42. ``` You can then figure out whe...
I tried usesizeof(array)/sizeof(int), but it seems this doesn't work if I passed the array into another function. So is there any other way to know the size of the array? By the way: I know achar[]ends with'\0'; which character ends theint[]?
In C, there is a difference between anarrayand a pointer to data. When "passing an array to a function", you in effect pass a pointer to the function. Unfortunately, you can't know if a pointer points to one element, or to a sequence of elements, and it's not possible to tell how many elements the sequence consist of....
In C, what is the difference between a NULL pointer and a pointer that points to 0?
The ISO/IEC 9899:TC2 states in6.3.2.3 Pointers 3 An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.55) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare un...
This question already has answers here:What is the difference between new/delete and malloc/free?(15 answers)Closed8 years ago. What are the differences between malloc and new in terms of their respective mechanisms of handling memory allocation?
mallocdoesn't throwbad_allocexception asnewdoes.Because malloc doesn't throw exceptions, you have to check its result againstNULL(or nullptr in c++11 and above), which isn't necessary withnew. However,newcan be used in a way it won't throw expections, as when functionset_new_handleris setmallocandfreedo not call objec...
I am writing daemon application for Debian Sid. It works perfectly most of the times, but dies silently after i put my laptop to suspend (or hibernate). So i have a couple of questions: What should I Google for solutions?Maybe, you have any ideas what is going on?
Trystrace-ing the daemon to see what is the reason it dies silently. Generally, suspend/hibernate alone should have no effect on user processes.
Is there some library or project out there that works like Zookeeper but has no java dependency? I'm looking at putting this on an embedded linux system, and need minimal footprint... something like a megabyte or less. I have Lua, C and C++ runtimes, and could put something like NewLISP on there if I had to. Most o...
There isaccord, Accord is a high-performance coordination service like Apache ZooKeeper It looks like accord iswritten in c.