question
stringlengths
25
894
answer
stringlengths
4
863
Consider the code: ``` void foo(char a[]){ a++; // works fine, gets compiled //... } ``` Now, consider this: ``` void foo(){ char a[50]; a++; // Compiler error //... } ``` I heard an array is equivalent to a constant pointer and can't be incremented as it is not a lvalue......
When you pass an array as an argument to a function, it decays to a pointer.So the thing you increment inside the function body is a pointer, not an array.
``` gcc (GCC) 4.6.3 20120306 (Red Hat 4.6.3-2) c89 ``` Hello, I am creating a thread to do some work. However, the definition is like this: ``` void *thread_send_fd(void *data) ``` I am creating the thread like this: ``` pthread_create(&thread_send, NULL, thread_send_fd, NULL) ``` However, as I am not actually u...
You can use ``` __attribute__((unused)) ``` or ``` (void)varname; ``` Choose whichever is easier for you
I am writing a C program to count the lines in files using system calls like open(), read(), write() close(). The same program I did with library calls fopen(), fread(), fwrite() and was working great, but with just system calls, I am stuck. ``` int fd1; // file descriptor fd1=open("f1.txt",O_RDONLY); // opening...
You compared a pointer (buffer) to char ('\n') You should dereference the pointer, for example: ``` if (*buffer == '\n') ``` or ``` if (buffer[0] == '\n') ```
Is this code valid C: ``` fputc(*("Checking 7 bytes before this string"-7), stdout); ``` Is there anything in the C standard against doing this? i.e reading a couple of bytes before a string literal. What about this: (assuming that these locations actually exist for the process) ``` for (i=(char *)0x400000; i<(char...
The first will result in undefined behavior, as you are going out of the boundaries of the string literal (underflow) The second is example is undefined as well, as you access address that are not guaranteed to be accessible, or even exist. The off-limit memory locations are not of C, but of the OS and the compiler....
``` #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int main() { uint32_t ip = 0; printf("%s\n",inet_ntoa(*(struct in_addr *)ip)); return 0; } ``` I don't want to do this by declaring any temporary variable. This program gives segmentation fault. ``` struct in_addr { ui...
You're casting an int to a pointer. Perhaps you want this: ``` *(struct in_addr *)&ip ``` But the result is implementation-defined (for a start, there're endianness considerations).
Is this correct, is it gonna leak memory in C? ``` unsigned char * prep( int length,int args, ... ) { unsigned char *message = (unsigned char *) malloc(length ); va_list listp; va_start( listp, args ); int i = 0; int len = 0; unsigned char *source_message ; int step = 0; for( i = 0 ...
That's correct, it will leak memory. As long as you remember to free the return value of that function, you should be fine, however.
strtokfunction uses a static variable for parsing the string into tokens. So this causes a conflict when multiple calls are done. Other than using threads how could I do the following: thx- Can I use a function pointer to allocate the function at 2 different places? Would this make the static variable inside "strt...
usestrtok_r()(re-entrant version).
During one review I came across a piece of code like the following : ``` #if defined(x) || y ``` What does the above statement mean ? Will the condition execute properly ?
Yes it is valid. Here is what the Standard (C99) says in 6.10p1: ``` if-group: # if constant-expression new-line groupopt # ifdef identifier new-line groupopt # ifndef identifier new-line groupopt ``` thedefinedoperator is seen as unary operator part of a constant expression (6.10.1p1). In your example, the condit...
I have a function as below ``` extern "C" int FuncTrace(const char *fmt, ...) { va_list args; va_start(args, fmt); return printf(fmt, args); } ``` If I print some thing on console as below, it does not work? ``` FuncTrace(" %s \n", __PRETTY_FUNCTION__ ); ``` Can someone help me correct the FuncTrace()...
You need thevprintffunction if you want to pass in ava_listpseudo-argument: ``` return vprintf(fmt, args); ```
Getting a segmentation fault for the following code. Please advise. ``` struct columns { char* c_name; char* c_type; char* c_size; }; int main(int argc, char* argv[]) { int column_num = 3; struct columns col[10]; //columns *col = (columns*) malloc (sizeof(columns) * column_num); strcpy(col[...
None of your pointers in the structure are actually initialized to anything. You have to give them a dimension, or dynamically allocate some memory for them.
Well my project requires me for make a link list within a link list. Is it ok for me to define it this way? ``` struct users { int user_ID; struct playlist{ int album; int track_num; struct playlist *next; } struct users *next; }; ```
Why not separate the structures? ``` struct Playlist{ int album; int track_num; struct Playlist *next; } struct users { int user_ID; struct Playlist playlist struct users *next; }; ``` it makes it easier to read, and easier to comprehend.
I have an embedded device communicatiing with a host (with Tera Term) through USART. I realised the ASCII characters could be "extended" through the escape character^[. For example,^[Ais "up arrow". Is there an ASCII escape for "clear line"? Where can I find a list of escapes?
This listis a list of ansi escape codes. Your terminal may or may not support them. Following themore complete listmentioned there, you can see the following information: ``` Esc[K Clear line from cursor right EL0 Esc[0K Clear line from cursor right EL0 Esc[1K Clear line from cursor left EL1 Esc[2K Clear...
How to set the boundaries of words usingSphinx? For example, i want to find a phrase: "some." ButSphinxfinds "something"! I've tried to setSPH_MATCH_PHRASE): ``` sphinx_set_match_mode(sph, SPH_MATCH_PHRASE); ```
I would suggest to use extended syntax: SPH_MATCH_EXTENDED2 And use phrase search operator like: ``` $cl->Query('"some"'); ``` Check out the manual:http://sphinxsearch.com/docs/current.html#extended-syntax
Why is it necessary to specify the number of elements of a C-array when it is passed as a parameter to a function (10 in the following example)? ``` void myFun(int arr[][10]) {} ``` Is it so because the number of elements is needed to determine the address of the cell being accessed?
Yes. It's becausearr[i][j]means((int *)arr)[i * N + j]ifarris anint [][N]: the pointer-arithmetic requires the length of a row.
I am making a module where I need to change the __be 32 format of address into char, which function could I use and under which header file it comes (I know to convert char to __be32 we use in_aton).
For kernels older than 2.6.26(if not mistaken) you need to use theNIPQUADmacro, like: ``` pritk("%d.%d.%d.%d\n", NIPQUAD(your_b32_address)); ``` For newer kernels a switch toprintkwas added: ``` printk("%pI4\n", your_b32_address); ``` Have a look here:http://www.kernel.org/doc/htmldocs/kernel-hacking/common-routin...
I have some code reading a text file and scanning for words between brackets: '[' and ']'. When I find the line starting with a '[' I read the string with: ``` line[64] = "[word]"; sscanf(line, "[%s]", resource); printf("%s\n",resource); ==> word] ``` but I always end up with the string+the bracket. How can i for...
Exclude the]from the set of characters thescanf()reads: ``` char resource[100]; if (sscanf(line, "[%99[^]]]", resource) != 1) /* error */; /* same as */ if (sscanf(line, "[" "%99[^]]" "]", resource) != 1) /* error */; /* literal scanset literal */ ```
I am writing a kernel module which forms its own packet at ip level and then sends the data . I just want to know how to find the ip address of a local network interface.
There are defined ioctlsSIOCGIFADDR(to get if address) andSIOCSIFADDR(to set if address). All device configuration for IPv4 is done innet/ipv4/devinet.c. You can refer to this source file to get more information.
I'm interested in doing something like anenumbut where the increments aren't always one, sort of like this: ``` typedef enum{this=0,that=3,something=5}example; ``` I am wondering what is the best way to do something like this, as I gather the above is either not possible or not advised. Basically I want to usekConst...
That's allowable, quite normal, and definitely better than#define. Minor nit-pick:#defineisn't a statement. It's a preprocessor construct that is expanded out before the compiler proper even sees it.
I am using Eclipse to generate a JNI header file. I looked inprogram files\java\jre6\binand found a lot of.exeand.dllfiles, but I couldn't find the commandjavahwhich was in the documentation for using JNI to create bindings to C libraries.Any help?
Use the following panel to define a new external tool for javah.exe. Point "Location" to the javah.exe tool. Set "Working Directory" to ``` ${workspace_loc:/${project_name}/bin} ``` Set "Arguments" to: ``` -classpath ${project_classpath} -v -d ${workspace_loc:/${project_name}/src} ${java_type_name} ``` To run ...
I have to usescanf()for accepting name of user inNSStringobject.If i use%sthen it will show me error. My Code is : ``` NSString *name; scanf("%s",&name); //It is showing error scanf("%@",&name); //It also show me error ``` What I should do?
You can't usescanf(), since it can't take aNSStringobject as an argument. You can first scan characters in achar *c-'string' and after that create aNSStringfrom it with- (id)initWithCString:(const char *)nullTerminatedCString encoding:(NSStringEncoding)encoding.
I use Python with C (with SWIG), where the main module in Python processes data using C library. It crashes somewhere in the C library, so I want to analyse core dump and find the bug. But, I do not havea regular executableto run with gdb, I havemain.py, the library_library.sogenerated from my C code, and.oobject fil...
IIRC you can do this by running python through gdb, i.e. ``` gdb python gdb> run -m main.py ```
I have a (C, Linux) application which handles Ctrl-C SIGINT by shutting down. I'd like to add another signal handler so that I can use another keystroke combo for "reload configuration while running". So I'm looking from a signal I can send to the foreground process by keystroke, which doesn't force the process to qu...
You can usectrl+Z, ``` SIGTSTP ``` Value = 20 For more details refer thislink.
I have a scenario where i created pipe for communication between two child and parent. Parent writes (using write function)data to the pipe and closes the respective file descriptor. The problem is when i want to write data again to the pipe, the write function is returning error code -1. I think its because writing e...
Once a pipe is closed, it's closed. You can't bring it back. If you want to write more to it, don't close it in the first place - it's as simple as that.
Is there anyway that I can hook into the tab completion for bash from a C or C++ progra, specifically for arguments. For example if I wanted to do./myprogram stTABit would complete tostart. I wasn't sure if this was something I can hook into during compile and put in like the metadata or if its a bash call/script th...
It is indeed possible to customize completion in bash, although it's not something a program can do for itself.Hereis the start of a two-part article that explains what you need to know.
``` *(int *)CV = (int)0; ``` I was looking at a C code and can't understand this line of code. Could you interpret this and explain what it does?
It castsCVto a pointer to anint, dereferences said pointer, and assigns the pointed-tointthe value0. Here's a demo.Also,(int)0is the same as0in this situation, so that can be changed to make things a little simpler.
Inverted index is designed to be fast for searching but not that easy for updating. So far as I know incremental index is used to update inverted index data. So what are the algorithms or main concepts of real-time searching, how did they do that?
Real-time search can still use an inverted index. You have to maintain this index in a form that can be both efficiently updated and queried, of course, which doesn't come free - but it's certainly doable. Another common technique is to have multiple indexes - one master index (updated frequently), and some overlay (o...
I#include <string.h>but when I callstrcasestr(src, search);I get the following error messageimplicit declaration of function ‘strcasestr’. how to I compile:gcc-4.6 -Wall -lsqlite3 -lunac -Werror -O2 -o foo.out foo.chow to fix this? Thanks in advance.
As specified in thecorresponding manpage, sincestrcasestris a nonstandard extension you must#define _GNU_SOURCEbefore the#include <string.h>before any#include(other files may already include<string.h>, thanks @Cubbi for pointing out this potential problem); this can also easily be accomplished by specifying-D_GNU_SOUR...
This is an iOS question. I build a static library (aframeworkin iOS) which is then included in an app. The size of the result binary (500kb) is smaller than the size of the static library (6mb). How does this work? My understanding of static library is that the static library is included in the final binary
Because you are not using all the functions of your library. A static library of archive type.ais a collection of.oobject files and only the object files needed in your program are included at link time.
This question already has answers here:Closed11 years ago. Possible Duplicate:Porting a C array declaration to Delphi I'm converting a C code to Delphi, and I want to convert a variable declaration, but I really don't know.. Can you help? ``` char szImageName[BUFMAXLEN]; ``` Thank you.
The Delphi equivalent is: ``` var szImageName: array [0..BUFMAXLEN-1] of AnsiChar; ``` Take care to useAnsiCharrather thanCharsince in modern versions of Delphi the generic typeCharis aliased to the 2 byteWideChar. Of course if you are on pre-Unicode Delphi then this warning is not pertinent. The biggest differen...
I want to store some value from SQLite database in my buffer, but the qlite3_column_text() has the following prototype: ``` const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); ``` then when I do: ``` out[size] = sqlite3_column_text(stmt, 0); ``` I get the following error message: ``` assignment dis...
It's easy withstrdup; ``` out[size] = strdup((const char*)sqlite3_column_text(stmt, 0)); ``` Note that this will malloc the copy, so you have to call free() on the pointer later not to get a leak. Of course this assumes that youroutarray can store values of the type char*, you're not showing how it's defined.
I have a (C, Linux) application which handles Ctrl-C SIGINT by shutting down. I'd like to add another signal handler so that I can use another keystroke combo for "reload configuration while running". So I'm looking from a signal I can send to the foreground process by keystroke, which doesn't force the process to qu...
You can usectrl+Z, ``` SIGTSTP ``` Value = 20 For more details refer thislink.
I have a scenario where i created pipe for communication between two child and parent. Parent writes (using write function)data to the pipe and closes the respective file descriptor. The problem is when i want to write data again to the pipe, the write function is returning error code -1. I think its because writing e...
Once a pipe is closed, it's closed. You can't bring it back. If you want to write more to it, don't close it in the first place - it's as simple as that.
Is there anyway that I can hook into the tab completion for bash from a C or C++ progra, specifically for arguments. For example if I wanted to do./myprogram stTABit would complete tostart. I wasn't sure if this was something I can hook into during compile and put in like the metadata or if its a bash call/script th...
It is indeed possible to customize completion in bash, although it's not something a program can do for itself.Hereis the start of a two-part article that explains what you need to know.
``` *(int *)CV = (int)0; ``` I was looking at a C code and can't understand this line of code. Could you interpret this and explain what it does?
It castsCVto a pointer to anint, dereferences said pointer, and assigns the pointed-tointthe value0. Here's a demo.Also,(int)0is the same as0in this situation, so that can be changed to make things a little simpler.
Inverted index is designed to be fast for searching but not that easy for updating. So far as I know incremental index is used to update inverted index data. So what are the algorithms or main concepts of real-time searching, how did they do that?
Real-time search can still use an inverted index. You have to maintain this index in a form that can be both efficiently updated and queried, of course, which doesn't come free - but it's certainly doable. Another common technique is to have multiple indexes - one master index (updated frequently), and some overlay (o...
I#include <string.h>but when I callstrcasestr(src, search);I get the following error messageimplicit declaration of function ‘strcasestr’. how to I compile:gcc-4.6 -Wall -lsqlite3 -lunac -Werror -O2 -o foo.out foo.chow to fix this? Thanks in advance.
As specified in thecorresponding manpage, sincestrcasestris a nonstandard extension you must#define _GNU_SOURCEbefore the#include <string.h>before any#include(other files may already include<string.h>, thanks @Cubbi for pointing out this potential problem); this can also easily be accomplished by specifying-D_GNU_SOUR...
This is an iOS question. I build a static library (aframeworkin iOS) which is then included in an app. The size of the result binary (500kb) is smaller than the size of the static library (6mb). How does this work? My understanding of static library is that the static library is included in the final binary
Because you are not using all the functions of your library. A static library of archive type.ais a collection of.oobject files and only the object files needed in your program are included at link time.
This question already has answers here:Closed11 years ago. Possible Duplicate:Porting a C array declaration to Delphi I'm converting a C code to Delphi, and I want to convert a variable declaration, but I really don't know.. Can you help? ``` char szImageName[BUFMAXLEN]; ``` Thank you.
The Delphi equivalent is: ``` var szImageName: array [0..BUFMAXLEN-1] of AnsiChar; ``` Take care to useAnsiCharrather thanCharsince in modern versions of Delphi the generic typeCharis aliased to the 2 byteWideChar. Of course if you are on pre-Unicode Delphi then this warning is not pertinent. The biggest differen...
I am using gmp's mpf_t to try and get very high precision. My range of precision ranges from negative trillions to positive trillions, as well as 1 over these numbers. However mpf doesn't support a power function that allows negative exponents, is there a way to get around this if I want to raise my value to 10^-30?...
When in doubt, apply math: ``` 10^-30 = 1 / 10^30 ``` Just raise it to the positive power and take the reciprocal. There's a division functionmpf_ui_div()that takes an integer numerator for that.
I complied my program with only-goption, and add some libs like-lpthread But when I use gdb to debug my program, using step it will step into some system functions, likeforkandmemcpy. Is there a way to avoid that? It happens after I installvalgrindon my computer. Kernel:2.6.38-13
You need to run the following from a gdb prompt.. ``` (gdb) set auto-solib-add off ``` It prevents gdb from loading symbols from libraries.
Say, I have the following struct inC#: ``` public struct MyStructCSharp { private byte[] offsets = new byte[] { 28, 20, 27, 36 }; } ``` How do you do the same inC/C++? The following doesn't seem to work: ``` typedef struct _MyStructCpp { _MyStructCpp() { offsets[] = {28, 20, 27, 36}; } pri...
You cannot assign to an array after it has been declared. Aside from that, the syntax would be wrong. If it only ever has 4 elements then do this or just use avectorif you can. ``` struct MyStruct { MyStruct() { offsets[0] = 28; offsets[1] = 20; offsets[2] = 27; offsets[3] = 36; } private: u...
I compile my C++ program to LLVM IR using the following command. ``` clang++ -O4 -emit-llvm program.cpp -c -o program.ll -S -pthread ``` However, now I want to do the same for multiple files. How can I do that? I want to produce one IR file after the compilation (not separate IR files for each file). In other words ...
You're probably looking for thellvm-linkcommand, which links bitcode files together.
I'm learning to write non-blocking server and client applications using epoll, poll, etc. and came across this event flag: POLLOUT: Writing now will not block. I understand the concept of blocking reads. But what are blocking writes?
If you are writing to a device like a pipe, socket or terminal at a faster rate than the other side is reading, eventually you will fill up the relevent kernel buffer and subsequent writes will block until some data is read by the other side.
How does one pass a const char *path to fts_open? I would like to pass a filePath.
I assume you want to know how to pass this single path to theargv(typechar const **) parameter offts_open. This parameter is described thus: argvIs a NULL terminated array of character pointers naming one or more paths that make up the file hierarchy. So you need to create an array of length two whose elements are o...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. So, my idea is quite simple: print ...
Useitertools.product. Use the below example and extend as per your need ``` >>> [x for x in itertools.product("01",repeat=2)] [('0', '0'), ('0', '1'), ('1', '0'), ('1', '1')] >>> ```
I have an array of structs and I intend to pass each element of the array into separate pthreads in a for loop. Here's my struct: ``` struct arrayData{ int *a; int *b; int up, low; } ``` Here's the pointer to the first struct and a malloc (don't know if I quite get what goes on here): ``` struct arrayData * instan...
You are trying to convert a struct to a pointer in the last parameter. You need to pass the the struct's address with&. ``` pthread_create( &thread[i], NULL, add, &instance[i]); ``` As jørgensenmentioned, thevoid *cast is unnecessary.
I am using gmp's mpf_t to try and get very high precision. My range of precision ranges from negative trillions to positive trillions, as well as 1 over these numbers. However mpf doesn't support a power function that allows negative exponents, is there a way to get around this if I want to raise my value to 10^-30?...
When in doubt, apply math: ``` 10^-30 = 1 / 10^30 ``` Just raise it to the positive power and take the reciprocal. There's a division functionmpf_ui_div()that takes an integer numerator for that.
I complied my program with only-goption, and add some libs like-lpthread But when I use gdb to debug my program, using step it will step into some system functions, likeforkandmemcpy. Is there a way to avoid that? It happens after I installvalgrindon my computer. Kernel:2.6.38-13
You need to run the following from a gdb prompt.. ``` (gdb) set auto-solib-add off ``` It prevents gdb from loading symbols from libraries.
Say, I have the following struct inC#: ``` public struct MyStructCSharp { private byte[] offsets = new byte[] { 28, 20, 27, 36 }; } ``` How do you do the same inC/C++? The following doesn't seem to work: ``` typedef struct _MyStructCpp { _MyStructCpp() { offsets[] = {28, 20, 27, 36}; } pri...
You cannot assign to an array after it has been declared. Aside from that, the syntax would be wrong. If it only ever has 4 elements then do this or just use avectorif you can. ``` struct MyStruct { MyStruct() { offsets[0] = 28; offsets[1] = 20; offsets[2] = 27; offsets[3] = 36; } private: u...
I compile my C++ program to LLVM IR using the following command. ``` clang++ -O4 -emit-llvm program.cpp -c -o program.ll -S -pthread ``` However, now I want to do the same for multiple files. How can I do that? I want to produce one IR file after the compilation (not separate IR files for each file). In other words ...
You're probably looking for thellvm-linkcommand, which links bitcode files together.
I'm learning to write non-blocking server and client applications using epoll, poll, etc. and came across this event flag: POLLOUT: Writing now will not block. I understand the concept of blocking reads. But what are blocking writes?
If you are writing to a device like a pipe, socket or terminal at a faster rate than the other side is reading, eventually you will fill up the relevent kernel buffer and subsequent writes will block until some data is read by the other side.
How does one pass a const char *path to fts_open? I would like to pass a filePath.
I assume you want to know how to pass this single path to theargv(typechar const **) parameter offts_open. This parameter is described thus: argvIs a NULL terminated array of character pointers naming one or more paths that make up the file hierarchy. So you need to create an array of length two whose elements are o...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. So, my idea is quite simple: print ...
Useitertools.product. Use the below example and extend as per your need ``` >>> [x for x in itertools.product("01",repeat=2)] [('0', '0'), ('0', '1'), ('1', '0'), ('1', '1')] >>> ```
I have an array of structs and I intend to pass each element of the array into separate pthreads in a for loop. Here's my struct: ``` struct arrayData{ int *a; int *b; int up, low; } ``` Here's the pointer to the first struct and a malloc (don't know if I quite get what goes on here): ``` struct arrayData * instan...
You are trying to convert a struct to a pointer in the last parameter. You need to pass the the struct's address with&. ``` pthread_create( &thread[i], NULL, add, &instance[i]); ``` As jørgensenmentioned, thevoid *cast is unnecessary.
I complied my program with only-goption, and add some libs like-lpthread But when I use gdb to debug my program, using step it will step into some system functions, likeforkandmemcpy. Is there a way to avoid that? It happens after I installvalgrindon my computer. Kernel:2.6.38-13
You need to run the following from a gdb prompt.. ``` (gdb) set auto-solib-add off ``` It prevents gdb from loading symbols from libraries.
Say, I have the following struct inC#: ``` public struct MyStructCSharp { private byte[] offsets = new byte[] { 28, 20, 27, 36 }; } ``` How do you do the same inC/C++? The following doesn't seem to work: ``` typedef struct _MyStructCpp { _MyStructCpp() { offsets[] = {28, 20, 27, 36}; } pri...
You cannot assign to an array after it has been declared. Aside from that, the syntax would be wrong. If it only ever has 4 elements then do this or just use avectorif you can. ``` struct MyStruct { MyStruct() { offsets[0] = 28; offsets[1] = 20; offsets[2] = 27; offsets[3] = 36; } private: u...
I compile my C++ program to LLVM IR using the following command. ``` clang++ -O4 -emit-llvm program.cpp -c -o program.ll -S -pthread ``` However, now I want to do the same for multiple files. How can I do that? I want to produce one IR file after the compilation (not separate IR files for each file). In other words ...
You're probably looking for thellvm-linkcommand, which links bitcode files together.
I'm learning to write non-blocking server and client applications using epoll, poll, etc. and came across this event flag: POLLOUT: Writing now will not block. I understand the concept of blocking reads. But what are blocking writes?
If you are writing to a device like a pipe, socket or terminal at a faster rate than the other side is reading, eventually you will fill up the relevent kernel buffer and subsequent writes will block until some data is read by the other side.
How does one pass a const char *path to fts_open? I would like to pass a filePath.
I assume you want to know how to pass this single path to theargv(typechar const **) parameter offts_open. This parameter is described thus: argvIs a NULL terminated array of character pointers naming one or more paths that make up the file hierarchy. So you need to create an array of length two whose elements are o...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. So, my idea is quite simple: print ...
Useitertools.product. Use the below example and extend as per your need ``` >>> [x for x in itertools.product("01",repeat=2)] [('0', '0'), ('0', '1'), ('1', '0'), ('1', '1')] >>> ```
I have an array of structs and I intend to pass each element of the array into separate pthreads in a for loop. Here's my struct: ``` struct arrayData{ int *a; int *b; int up, low; } ``` Here's the pointer to the first struct and a malloc (don't know if I quite get what goes on here): ``` struct arrayData * instan...
You are trying to convert a struct to a pointer in the last parameter. You need to pass the the struct's address with&. ``` pthread_create( &thread[i], NULL, add, &instance[i]); ``` As jørgensenmentioned, thevoid *cast is unnecessary.
This question already has answers here:Closed11 years ago. Possible Duplicate:Is there any reason to use the 'auto' keyword in C / C++? I read that: ``` int i; ``` and ``` auto int i; ``` are equivalent. If so, what's the use of auto keyword in C? Is there any special cases when auto is more useful? Or things th...
Auto is just implicit in C, but due to how rarely (read never) it is used in actual code explicitly its meaning has changed in C++11. Auto just specifies automatic storage, meaning the variable will go away when it goes out of scope.
I have two prgrams lets say prog1 and prog2. I am opening a file with prog1 and doing some operations on it. Now without closing the file in prog1 i am sending its file descriptor to prog2 using unix sockets which then does some operations in it. Though i get the same descriptor i passed in prog1 but doing a fstat()...
I believe this site has what you're looking for: http://www.lst.de/~okir/blackhats/node121.html There's also information in Linux'sman 7 unixon usingSCM_RIGHTSand other features of Unix sockets. Fix for broken link:http://web.archive.org/web/20131016032959/http://www.lst.de/~okir/blackhats/node121.html
Problem with compiling. ``` gcc (GCC) 4.6.3 20120306 (Red Hat 4.6.3-2) c89 cmake version 2.8.7 ``` Not sure how to start with this one. I have googled it but couldn't come up with anything. This is the warning I am getting: ``` <command-line>:0:11: warning: extra tokens at end of #undef directive [enabled by defau...
I would expect a warning like this if you had a line like the following in one of your source files: ``` #undef FOO BAR BAZ ``` TheBARandBAZare ignored by the compiler, hence the warning. What's at character 11 of your command-line? Can you post the command line?
Someone can point me reliable method to run given application in different session of same user on Windows ? I code in C. Thanks in advance.
The easiest way is to leverage Task Scheduler which can do this. Use the method in this answer, but specify the local computer name, and a username and password: start remote process within the context You should specify that it doesn't interact with the desktop.
I need to create an ASN.1 BER encoded file with multiple records. I've been searching for one (tools like oss, asn1c, ... etc), but I can't find one that suits me with a full example on how multiple records can be encoded in one file. Does anyone know a good tool? Thanks
The tools won't really help you design your file-format, orprotocol; that is a manual task that you must perform. You will need to design the rules of how data is stored and in what form each element will take. The tools will help with implementation, allowing you to take your protocol definition and generating C or...
I have a number like56789098.9899and i want to use it in usleep() which accepts only anunsigned integeras argument.how to solve this problem? sleeptime = time_alloted - time_taken. Heresleeptimeis anunsigned intvariable.
First,usleepaccept ausenconds_targuement, anduseconds_tdoesn't have to be anunsigned int. Seeusleepspec here.http://pubs.opengroup.org/onlinepubs/7908799/xsh/usleep.html Second, note that the arguments must not larger than 1,000,000. And also remember to check the return value ofusleepsince it may fail. Then just us...
I'm using MPI with C, I've importedmpi.hand I am able to use MPI functions likeMPI_Type_create_subarray()andMPI_Type_commit(), but I get a linker error when I try to useMPI_Type_create_resized(). Any idea why I wouldn't have that function, or maybe there is an alternative? I'm trying to scatter and gather blocks of ...
I looked at the documentation for older versions (maybe you had an old implementation that didn't support that function), but even the "ancient" version contains the aforementioned function. This leads me to believe that maybe there was a problem when you downloaded/linked/etc the library. Maybe try re-downloading and...
Is there a way to halt execution, somewhat like SIG_ABRT, butimmediately, even if we're not on the main thread?
Core Foundationhas a macroHALTthat should do the trick, if youreally,reallythink it's necessary to do this: ``` #if defined(__ppc__) #define HALT do {asm __volatile__("trap"); kill(getpid(), 9); } while (0) #elif defined(__i386__) || defined(__x86_64__) #if defined(__GNUC__) #define HALT do {asm __vol...
I am writing an LLVM pass which modifies the LLVM bitcode. For one variable, I want it to use a register, say R15 on x86. How can I instruct LLVM to use this register when generating machine code? Can this be instructed at the bitcode level?
You can use inline assembler to model this requirement. There is no way to "tie" specific variable to register.
Let's say I have created a program in C/C++ and have a source code. I'd like to know the total memory during the program execution. Someone has mentioned something about "malloc" and "hook" Is there any other way to trace the spaced used?
If you are running Linux or something Unix-based, you could most likely useValgrind. Valgrind runs the program and intercepts all of its memory allocations and prints the stats once it exits. It's a very useful tool for checking for memory leaks and memory usage. If you're running Windows, I haven't a clue.
I'm trying to do a mesh-to-circle collision system for my game. I've seen some examples where you iterate over all the verts of the mesh and check if they are inside the circle. But the problem is that sometimes the vertices are not inside the circle, but the lines that this vertices form are. In this cases, the colli...
If you want you could calculate the distance from the line to the center of the circle. But I think it will be too costly. If the distance is lower than the radio you could have a collision. You will need to check if this part of the line is between the points.Distance line to point
I'm trying to read certain values from a particular register. The manual specifies that I must access the 16-bit LSB access first and 16-bit MSB access next. Do I just read in all 32 bits at once and then mask the remaining 16 msb/lsb respectively as needed? Or would there be a way to read only 16 bits fist. Thanks, ...
If the manual says to first access the 16-bit LSB and then the 16-bit MSB, do as the manual says. For example (little endian): ``` #define REG (*(volatile uint32_t *) 0x1234) uint16_t val_hi, val_lo; val_lo = *((volatile uint16_t *) &REG); val_hi = *((volatile uint16_t *) &REG + 1); ``` Note that compilers also ...
I am using eclipse c/c++ when i create a c project then it does not shows winavr gcc in the toolchain list but i have installed WinAVR-20100110 in c drive and my eclipse is also in the same directory. it shows cygwin,solarize,linux,macosx,mingw gcc
Eclipse does not look for AVR toolchain by default, even if it is in path (you did add it there?). You need to create an cross GCC project, then tell it the prefix of your toolchain (avr- i guess). When you select "New C project" select Cross GCC in Toolchains listbox, then in next step enter the prefix, set path to t...
I was interviewing a guy for a mid-level software engineering position yesterday, and he mentioned that in C, NULL is not always zero and that he had seen implementations of C where NULL is not zero. I find this highly suspect, but I want to be sure. Anyone know if he is right? (Responses will not affect my judgement...
I'm assuming you mean the null pointer. It is guaranteed to compare equal to0.1But it doesn't have to be represented with all-zero bits.2 See also thecomp.lang.c FAQon null pointers. See C99, 6.3.2.3.There's no explicit claim; but see the footnote for C99, 7.20.3 (thanks to @birryree in the comments).
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. Here i want to do UDP Socket progra...
There is a lot of sites that gives examples on how do that: For example, the following site: UDP Example
This Verilog tutorial(see the table at the end) suggests that{ }is a concatenation operator is C. I don't remember curly brackets as being anoperatorin C. Is{ }a concatenation operator in C?
No, that's just nonsense. No idea what that's about.
When I have aPyObject *obtained fromPyArg_ParseTuple, do I need to make sure toPy_DECREFit before I return from the function? Example: ``` static PyObject * modulefunc(PyObject * self, PyObject * args) { PyObject * obj; if (!PyArg_ParseTuple(args, "O", &obj)) { return NULL; } if (!PyObject_T...
No. PyArg_ParseTuple gives you aborrowed reference.
I saw this code snippet ``` const volatile int * volatile * const X; ``` but I can't understand what does the second * means. I understand that const volatile int * volatile const X; means a volatile const integer pointer to a volatile const data.
A useful site for understanding non-trivial C declarations iscdecl.org. The description for: ``` const volatile int * volatile * const X; ``` fromcdeclis: declare X as const pointer to volatile pointer to const volatile int
Will this leak memory? ``` char *str = "Hello/World"; char *pos = rindex(str, '/'); *pos = 0; ```
No, but this will invoke undefined behavior as you are writing to a string literal. String literals are not required to be modifiable in C.
So I've been working on a small app that at some runs runs an application as another user, I'm writing it in C and using the MinGW GCC compiler to compile and link it. My issue is that whenever I try to use the WINAPI function CreateProcessWithLogonW() I get an error that says "Undefined reference to CreateProcessWith...
The correct solution is to actually #include the correct mingw32 headers: i.e. ``` #include <windows.h> ``` Though the solution that Anthales proposed works, it doesn't scale well.
This question already has answers here:Why does the order of the loops affect performance when iterating over a 2D array?(7 answers)Closed4 years ago. Which of the following orderings of nested loops to iterate over a 2D array is more efficient in terms of time (cache performance)? Why? ``` int a[100][100]; for(i=0...
The first method is slightly better, as the cells being assigned to lays next to each other. First method: ``` [ ][ ][ ][ ][ ] .... ^1st assignment ^2nd assignment [ ][ ][ ][ ][ ] .... ^101st assignment ``` Second method: ``` [ ][ ][ ][ ][ ] .... ^1st assignment ^101st assignment [ ][ ][ ][ ][ ] .... ^2nd as...
I came across sizeof(str -1) a couple of time on net but never used it myself. I am just curious what is the difference between sizeof(str-1) and sizeof(str) -1 where str is the character array say char str[] = "Hello";
sizeof(str)is the size of the arraystr. In this case, that's 6 (including the nul terminator). Sosizeof(str)-1is 5 (it excludes the nul terminator). str-1has typechar*in C andconst char*in C++, because of array-to-pointer decay. Sosizeof(str-1)is the size of a pointer-to-char. It has nothing to do with the length of ...
I need to display the names of the files in a specified directory. How can I do this using only C standard function?
There is no portable way to list all the files in a specified directory using only the C Standard library. Functions likereaddirare part of POSIX but not part of the C Standard library. You have to remember that not all operating systems have a concept of directory. An example is the MVS OS on IBM System/360 and Sys...
I need to write an algorithm that reads keyboard stream until it gets a correct password. like if the password is ababac, and the input is abababa, it means so far it read ababa and now it waits for a c to get unlocked, if an f comes in instead of a c, then it restarts its process. it easily can be done in O(n^2), b...
I think online version ofKnuth-Morris-Pratt algorithmwill do the job. You would have to store and calculate index array (additional O(n) memory in case of circular array implementation), though.
I want to run script file on android Shell using Native C program. I tried usingsystemfunction but it's not working. ``` result = system("sh ./test.sh"); LOGD("result is %d", result); ``` system command returns 0 means its not executed script file successfully. test.sh contains ``` echo "test...." ``` Android N...
where is 'sh'? and what is your '.' current directory when the application runs? try: result = system("/system/bin/sh /full/path/to/test.sh");
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen...
If you want to start searching from the 5. character, do ``` strchr(&m_DSServer[4],':') ```
How can I create a buffer in linux kernel withoutmalloc()function (orcalloc()) and clean buffer withoutfree()function?
You cannot use standard c library functions likemalloc()orcalloc()inside the kernel, The code you write in kernel links to the functionality provided by the kernel itself. You can usekmalloc()& then free it withkfree().
I'm reading expert c, and got through setjump and longjump section, so want make the code running on my ubuntu 11.10, but when I include setjump.h, the gcc compiler complain that it can't find the header file, I find there is not a setjump.h in the /user/include/ directory. So what should I do? Can you give me some su...
From thesetjmp(3)man page: SYNOPSIS #include <setjmp.h>
I'm writing a driver that requires me to clear all the memory allocated to zero.memsetis a userspace function, but I would like to know if the kernel provides a macro that helps me do this.
It's truememset()in ``` include <string.h > ``` not supposed to appear in kernel code.And the fact is it may cost you a lot to trace down wherememset()is included during driver development. Actuallymemset()is defined in ``` #include<linux/string.h> ``` it says: ``` #ifndef __KERNEL__ #include <string.h> #else /* ...
I'm using libffi to load dlls at runtime on multiple platforms. The correct system paths are automatically searched, I just need to know what the name of the system dll is on the Microsoft platform housing the standard c library functions.
Windows ships with a C runtime in msvcrt.dll. If you are writing a self-contained program and want to call functions from the C standard library, then perhaps this is what you need. If your program uses libraries that are linked against other C runtimes, this will be no good to you. But in that case, you don't need ...
I'm building a voip app for iOS devices using the H.323 protocol and was wondering if there any libraries in Objective C (or C/C++) that let me convert my audio to H.323
There are only 2 OpenSource H.323 libraries both C++:H323PlusandOPAL. And then there is the commercial Radvision SDK, which is done in C as far as I know.
At the moment I am using OpenCV's KNN implementation to classify images. It currently classifies images into P, S or rectangle, and correctly. However if I feed it an image of noise it will attempt to classify it as 1 of the 3 classifications I stated earlier. To get it to classify as noise, should I train the KNN to ...
The way to do it is to use the dists variable in the knn_nearest function. It spits out the distance between your vector and the K unit vectors, the further the distance the less they have in common with the test data.
``` #include <stdio.h> int main(int argc, char *argv[]) { long* fp; while(1) { fp = (long* ) malloc (sizeof(long)); printf("%d\t",fp); } } ``` I ran this. I got result such as: ``` 1193392 1193408 1193424 1193440 1193456 1193472 1193488 1193504 1193520 1193536 1193552 1193568 1193584...
Not necessarily. It could indicate that the granularity of the allocator is 16 bytes.
I'm just trying to understand how does non-blocking recvfrom works? I'm writing an application that communicates with the certain device that sends data at about 10 Mbps speed. I've made infinte loop that calls recvfrom successively and strip off the header and copy rest of message in some temporary buffer. Now my que...
Only one datagram in the case of UDP. Concatenating packets would violate one of the (few) fundamental guarantees made by that protocol: that the boundaries between datagrams sent are preserved. Recent versions of Linux haverecvmmsgthat lets you receive multiple datagrams per syscall.
How I would go about capturing/intercepting signals sent to another process from my own process? Willing to use C, Ruby, or any Linux package.
You can write a library wrapper that will replace systemsignal/sigactioncalls to intercept setting of the signal handler and set your own handlers. On received signal, you can do your job and call user handler later. UseLD_PRELOADto replace systemsignal/sigactionroutines by your own.
my problem is as follows : pcap_loop() grabs all arriving frames from the listening interface and if one of these frames contains IP data i forward it with pcap_sendpacket(). as soon as i send it the pcap_loop() grabs it and processes it again. somebody may knows the answer to solve that? thanks in advance and regar...
On at least some platforms, sending packets through pcap will, by default, cause those packets to be seen by pcap. Windows is one of them, so that applies to WinPcap. The standard libpcap API to turn this off,pcap_setdirection(), is not available in current versions of WinPcap. In order to turn that off, you'll hav...
I have found theexampleof using thelocal sockets. The code from examle uses the path ``` #define UNIXSTR_PATH "/tmp/unix.str" ``` as the name of a socket. Is this a best practice of choosing the socket name? Should I use something like ``` /var/run/com.company.executable.socket ``` writing the daemon on Linux Ubun...
Putting it in/var/runis fine, but the sockets are usually named after the executable itself and not in some Javaesque fashion.
In a makefile, there is a line: ``` CFLAGS += $(shell $(CC) -fno-stack-protector -E -x c /dev/null >/dev/null 2>&1 && echo -fno-stack-protector) ``` What's the use ofshell $(CC) -fno-stack-protector -E -x c /dev/null >/dev/null 2>&1? It seems to do nothing. And how the whole line works? Thanks in advance.
It tests whether-fno-stack-protectoris a valid command-line option for your C compiler, and if it is it then appends this option toCFLAGS, otherwise it does nothing.
programming my arduino microcontroller board in C, I noticed a strange behaviour. Because of an logic mistake in my program the controller accessed the-1th element of an integer array. ``` int array[5]; array[4] = 27; // array[-1] gives 27 now. ``` Is it correct that I get the last element of an array by using-1...
No, accessing elements outside of the index range is undefined behavior. In your case, the element at the address just prior to the beginning of your array is set to 27. Since accessing array elements in C is nothing more than doing "straight" pointer arithmetic, passing negative indexes is not disallowed. You could ...