question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I am to write a cross platform program for windows and linux ::
A Java program will send data to a tcp/ip port and there will be a C/C++ program which will continuously listen from that tcp/ip port when it gets some data it will do some works and send the result data to another tcp/ip port from which now the Java ... |
My suggestion:boost::asiofor C++ cross platform networking andgoogle protocol buffersfor specifying the cross platform/cross language protocol.
Use boost::asio for sending/receiving bytes of data and google protocol buffers to turn those bytes into something useful(ints, strings, etc).
|
I am using the hexdump -C to show realtime data from a pointing device on a linux box. The information it returns is 16 bytes of hex per line. Like this:
000001b0 a9 1c fd 4e f1 2c 0f 00 01 00 3e 00 01 00 00 00 |...N.,....>.....|
000001c0 a9 1c fd 4e 0e 2d 0f 00 01 00 3e 00 00 00 00 00 |...N.-....>.....|
000001... |
Most USB input devices conform to theUSB HIDspecification. The Xorgevdev(4)driver should be able to Just Use nearly any pointing device.
If you're writing your own driver,libusbmight be a good starting point.
|
I have one fileexample1.cppwith themainfunction. This file must have#include mylib.hand#include lib.h. Filemylib.halso has#include lib.h. When I try to compile this program, the errorredefinition xyz functionocurs.
example1.cpp
```
#include mylib.h
#include lib.h
int main(){
//code
}
```
mylib.h
```
#include lib.... |
You need to putinclude guardsin your header file to prevent it from getting included multiple times during compilation.
```
#ifndef LIB_H
#define LIB_H
// Actual header file code
#endif
```
|
I need to check the divisibility of a number in c. How can I use the modulus operatpr in C to check if a number is divisible by another number? I tried doing this:
```
if (file_int % 3) {
printf("Hoppity \n");
}
```
It didn't work, although file_int is equal to 9.
What did I do wrong?
Thanks
|
It didn't work because the operation will return 0 which will be treated as false.
You actually need:
```
if(!(file_int % 3)) {
printf("Hoppity \n");
}
```
|
Is there a #define that indicates whether Visual Studio is compiling in 64bit mode? I'd like to be able to include some code conditionally like so
```
#ifdef _IS_64BIT
...
#else //32 bit
...
#endif
```
I know I can create a flag myself, but I'm wondering if the compiler provides one.
|
```
#ifdef _WIN64
...
#else
...
#endif
```
Documented onMicrosoft docs
|
I was wondering if there is a way to get the installed memory type in Windows? I mean is there an API or any other way to query that on a PC there is DDR2 or DDR3 or SDRAM installed?
Thanks!
|
CPU-IDis able to do it, so it's definitely possible. They have aSDKavailable, but it'sexpensive.
QueryingWin32_PhysicalMemoryusing WMI may also help and is possible usingC/C++.
|
I'm trying to make a simple fibonacci calculator in C but when compilinggcctells me that I'm missing the pow and floor functions. What's wrong?
Code:
```
#include <stdio.h>
#include <math.h>
int fibo(int n);
int main() {
printf("Fib(4) = %d", fibo(4));
return 0;
}
int fibo(int n) {
double ... |
You need to compile with the link flag-lm, like this:
```
gcc fib.c -lm -o fibo
```
This will tell gcc to link your code against the math lib. Just be sure to put the flagafterthe objects you want to link.
|
```
struct node{
char a[100];
struct node* next;
};
typedef struct node* nodeptr;
main()
{
char b[100];
nodeptr p;
int n;
printf("enter the string\n");
scanf("%s",b);
n=strlen(b);
p=getnode();
p->a=b; ... |
Your code atp->a=bis simply not allowed as a is an array and not a pointer and you are trying to copy a pointer to an array. Trystrncpy(p->a, b, 100)(of course you should have 100 as a#define)
|
I know there are very many different non-standard ways of finding (and converting) the endianness of your hardware. For example,hereis one!
We have the standard functions likehtonl(),htons(),ntohl()andntohs()to convert values between host and network byte order.
Now my question is, in analogous to the above mentione... |
```
#include <stdio.h>
int little_endian(){
int x = 1;
return *(char*)&x;
}
int big_endian(){
return !little_endian();
}
int main(){
if(big_endian())
printf("big_endian\n");
if(little_endian())
printf("little_endian\n");
return 0;
}
```
|
I am trying to find an integer type length in C. Does anyone have a quick algorithm to check the length of it?
Thanks.
|
Do you mean this?
```
sizeof (int)
```
If you want it measured in bits, try
```
#include <limits.h>
(CHAR_BIT * sizeof (int))
```
|
I want to create a processBfrom processA. However, I don't wantBto be the child ofA, which will be the case if I simply usefork. How can I achieve that? In other words I want processBto keep on executing even if processAis killed.
|
You can use the setsid() function.
Alternatively, as you have tagged your question "linux", maybe you want to use daemon() instead of fork() + setsid().
|
I am trying to produce random numbers for each thread to use, but all the threads produce the same number.
The number changes when I run my program each time, but all the threads produce the same number for a given run.
What should I do to produce different random numbers for each thread?
```
void *Customer(void *c... |
Seeding the random number generator with the time will give you the same random number if the threads produce a random number at the same second. You could just seed with the time plus the thread number or something like that.
Or, as Dave suggested, you could just seed once outside the thread.
|
Arity is the number of operand(s) an operator can take. For example,+,-,*and&are the operators that can be used as both unary (one operand) and binary (two operands).?:is the only operator which takes three operands (that's why it is called ternary operator).
But what is the arity of,(comma) operator?
|
The comma operator is a binary operator, as indicated by its definition in theC Standard, §6.5.17:
```
Syntax
1 expression:
assignment-expression
expression , assignment-expression
```
|
I was readingthisquestion and then I made the following.
```
a = b + (c - (b = c)) + (a - (c = a))
```
I tried that in C and Java. It works with java , but not C.
Of course, it depends on how the compiler evaluate such expressions and after googling about that, I failed to find the answer.
|
The reason why it doesn't work in C is because C doesn't specify exactly when thec = awill occur. It can occur before or after the two other times it is referenced in that statement.
So depending on when the compiler decides to perform the assignmentc = a, the value of the expression will vary. It's not defined.
i.e... |
how do I allocate memory forstrlen(esc)in a proper way? Thetempandstrare char datatypes.
```
double esc = t1.tv_sec+(t1.tv_usec/1000000.0);
strAll = malloc(strlen(temp) + strlen(str) + strlen(esc) + 1);
```
|
You cannot takestrlen(esc). As I am sure the compiler has already told you, the argument tostrlen()must bechar *, you are passing it adouble. Try first converting thedoubleto array ofcharwithsnprintf().
|
I am to write a cross platform program for windows and linux ::
A Java program will send data to a tcp/ip port and there will be a C/C++ program which will continuously listen from that tcp/ip port when it gets some data it will do some works and send the result data to another tcp/ip port from which now the Java ... |
My suggestion:boost::asiofor C++ cross platform networking andgoogle protocol buffersfor specifying the cross platform/cross language protocol.
Use boost::asio for sending/receiving bytes of data and google protocol buffers to turn those bytes into something useful(ints, strings, etc).
|
I am using the hexdump -C to show realtime data from a pointing device on a linux box. The information it returns is 16 bytes of hex per line. Like this:
000001b0 a9 1c fd 4e f1 2c 0f 00 01 00 3e 00 01 00 00 00 |...N.,....>.....|
000001c0 a9 1c fd 4e 0e 2d 0f 00 01 00 3e 00 00 00 00 00 |...N.-....>.....|
000001... |
Most USB input devices conform to theUSB HIDspecification. The Xorgevdev(4)driver should be able to Just Use nearly any pointing device.
If you're writing your own driver,libusbmight be a good starting point.
|
I have one fileexample1.cppwith themainfunction. This file must have#include mylib.hand#include lib.h. Filemylib.halso has#include lib.h. When I try to compile this program, the errorredefinition xyz functionocurs.
example1.cpp
```
#include mylib.h
#include lib.h
int main(){
//code
}
```
mylib.h
```
#include lib.... |
You need to putinclude guardsin your header file to prevent it from getting included multiple times during compilation.
```
#ifndef LIB_H
#define LIB_H
// Actual header file code
#endif
```
|
I need to check the divisibility of a number in c. How can I use the modulus operatpr in C to check if a number is divisible by another number? I tried doing this:
```
if (file_int % 3) {
printf("Hoppity \n");
}
```
It didn't work, although file_int is equal to 9.
What did I do wrong?
Thanks
|
It didn't work because the operation will return 0 which will be treated as false.
You actually need:
```
if(!(file_int % 3)) {
printf("Hoppity \n");
}
```
|
Is there a #define that indicates whether Visual Studio is compiling in 64bit mode? I'd like to be able to include some code conditionally like so
```
#ifdef _IS_64BIT
...
#else //32 bit
...
#endif
```
I know I can create a flag myself, but I'm wondering if the compiler provides one.
|
```
#ifdef _WIN64
...
#else
...
#endif
```
Documented onMicrosoft docs
|
I was wondering if there is a way to get the installed memory type in Windows? I mean is there an API or any other way to query that on a PC there is DDR2 or DDR3 or SDRAM installed?
Thanks!
|
CPU-IDis able to do it, so it's definitely possible. They have aSDKavailable, but it'sexpensive.
QueryingWin32_PhysicalMemoryusing WMI may also help and is possible usingC/C++.
|
I'm trying to make a simple fibonacci calculator in C but when compilinggcctells me that I'm missing the pow and floor functions. What's wrong?
Code:
```
#include <stdio.h>
#include <math.h>
int fibo(int n);
int main() {
printf("Fib(4) = %d", fibo(4));
return 0;
}
int fibo(int n) {
double ... |
You need to compile with the link flag-lm, like this:
```
gcc fib.c -lm -o fibo
```
This will tell gcc to link your code against the math lib. Just be sure to put the flagafterthe objects you want to link.
|
```
struct node{
char a[100];
struct node* next;
};
typedef struct node* nodeptr;
main()
{
char b[100];
nodeptr p;
int n;
printf("enter the string\n");
scanf("%s",b);
n=strlen(b);
p=getnode();
p->a=b; ... |
Your code atp->a=bis simply not allowed as a is an array and not a pointer and you are trying to copy a pointer to an array. Trystrncpy(p->a, b, 100)(of course you should have 100 as a#define)
|
I know there are very many different non-standard ways of finding (and converting) the endianness of your hardware. For example,hereis one!
We have the standard functions likehtonl(),htons(),ntohl()andntohs()to convert values between host and network byte order.
Now my question is, in analogous to the above mentione... |
```
#include <stdio.h>
int little_endian(){
int x = 1;
return *(char*)&x;
}
int big_endian(){
return !little_endian();
}
int main(){
if(big_endian())
printf("big_endian\n");
if(little_endian())
printf("little_endian\n");
return 0;
}
```
|
I am trying to find an integer type length in C. Does anyone have a quick algorithm to check the length of it?
Thanks.
|
Do you mean this?
```
sizeof (int)
```
If you want it measured in bits, try
```
#include <limits.h>
(CHAR_BIT * sizeof (int))
```
|
I want to create a processBfrom processA. However, I don't wantBto be the child ofA, which will be the case if I simply usefork. How can I achieve that? In other words I want processBto keep on executing even if processAis killed.
|
You can use the setsid() function.
Alternatively, as you have tagged your question "linux", maybe you want to use daemon() instead of fork() + setsid().
|
I am trying to produce random numbers for each thread to use, but all the threads produce the same number.
The number changes when I run my program each time, but all the threads produce the same number for a given run.
What should I do to produce different random numbers for each thread?
```
void *Customer(void *c... |
Seeding the random number generator with the time will give you the same random number if the threads produce a random number at the same second. You could just seed with the time plus the thread number or something like that.
Or, as Dave suggested, you could just seed once outside the thread.
|
Arity is the number of operand(s) an operator can take. For example,+,-,*and&are the operators that can be used as both unary (one operand) and binary (two operands).?:is the only operator which takes three operands (that's why it is called ternary operator).
But what is the arity of,(comma) operator?
|
The comma operator is a binary operator, as indicated by its definition in theC Standard, §6.5.17:
```
Syntax
1 expression:
assignment-expression
expression , assignment-expression
```
|
I am trying to compile a program that uses the functionclock_gettime. The man page on Ubuntu says it has to be compiled with-lrtoption.
If I issue the command
```
gcc myprogram.c -lrt
```
my program compiles fine.
Now how do I add the option-lrtto Eclipse. I already tried adding-lrtto:
GCC Compiler->Miscellaneous... |
Its been a long time since I last used eclipse, but there should be a + button in the section you mentioned (GCC compiler -> etc -> libraries). Just click on it and write rt, then click on it again and write pthread, that should be it (to add both libraries, of course).
EDIT: nevermind, the post you mentioned says it... |
Suppose you have 3 files in your C project
```
- a.c
- a.h // Header for a.c
- b.c
```
Apple-Rfails to link files properly,lderror comes up.(ld: symbol(s) not found for architecture x86_64)
Runninggccmanually on a command line works finegcc -o executable a.c b.c
Can one redefine whatApple-Rdoes or should amake... |
If you have the Make bundle enabled, you should be able to doCommand-Bto build the project with the current Makefile. In any case, you should probably use a Makefile instead of relying on TextMate's "Run" command, which doesn't know about dependencies and whatnot.
|
The following command computes size of the stack for each running process on a Linux machine.
```
# find /proc -maxdepth 1 -type d -regex '/proc/[0-9]*' -exec cat '{}'/maps \; | grep stack | cut -d' ' -f1 | gawk --non-decimal-data 'BEGIN{FS="-"} {printf "%d\n", (("0x" $2) - ("0x" $1))/1024}' | sort
```
In almost all... |
The kernel sets new process stacks to 128kB insetup_arg_pages():
```
stack_expand = 131072UL; /* randomly 32*4k (or 2*64k) pages */
```
When you add a single 4kB guard page, that comes to 132kB. If the process has never used more than this much stack, it won't have been expanded past this size.
|
The C standard (ISO/IEC 9899:2011 or 9899:1999) defines a typeptrdiff_tin<stddef.h>.
The POSIX standard (ISO/IEC 9945; IEEE Std 1003.1-2008) defines a typessize_tin<sys/types.h>.
What is the difference between these types (or why were both deemed necessary)?Is there an implementation where the underlying base type f... |
Is there an implementation where the underlying base type for ssize_t
is not the same as for ptrdiff_t?
x86-16 with the large memory model. Pointers are far (32-bit), but individual objects are limited to one segment (sosize_tis allowed to be 16-bit).
|
I want to create a dll that unload it self in case of some condifiton, meaning
```
BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
if (ul_reason_for_call==DLL_PROCESS_ATTACH)
if (!CheckSomething()) //check if a file doesnt exists for example
FreeLibrary(hModule);
}
```
I trie... |
You can't unload the DLL,it hasn't been loaded yet. That's what theBOOLreturn is for. If you don't want to load the DLL, then returnFALSE.
|
I did enable the vim syntax highlight in vimrc,I can see void and int keyword is different color than other code,but the problem is I cannot see the function syntax highlight, function like memcpy malloc doesn't have syntax highlight,and of course my own function doesn't have syntax highlight too,
|
I usethis C syntax file extension, and I would recommend it, because it works nice: all functions, both built-in and user-defined, are highlighted. You can check outscreenshot.
Just for your information: there's colorschemedesert256on this screenshot, but, of course, you can use any colorscheme.
|
I am working on Microsoft Visual Studio environment. I came across a strange behavior
```
char *src ="123";
char *des ="abc";
printf("\nThe src string is %c", src[0]);
printf("\tThe dest string is %c",dest[0]);
des[0] = src[0];
printf("\nThe src string is %c", src[0]);
printf("\tThe dest string is %c",dest[0]... |
This is undefined behavior:
```
des[0] = src[0];
```
Try this instead:
```
char des[] ="abc";
```
|
I have made an application in which there is a filemain.cwhich uses a function from themaster.cfile. I would like to debug my application for all functions defined in themaster.cfile by usinggdb tool. Is this possible and if so how?
|
You must compile your program using-gflag.
Then you startgdb your_programand set break points:break master.c:37that will set a break point on master.c, line #37 or you could set breaks at functions:break foo().
Then start your program byrunand continue with the debugging process,inspect,continue,watch,display...
ht... |
Can someone please explaing why the string is not splitted in the following code
```
#include <stdio.h>
int main(void)
{
char name[] = "first:last";
char first[20], last[20];
sscanf(name, "%s:%s", first, last);
printf("first: %s, last: %s", first, last);
return 0;
}
```
The output is
first: ... |
You can use something like this:
```
sscanf(name, "%[^:]:%s", first, last);
```
:is not whitespace, so a regular%swill not consider it as a delimiter. Seescanffor more details.
(Edited demo:http://ideone.com/m4LVP)
|
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed9 years ago.Improve this question
I'm starting to do programming with CUDA C. Are there any IDE that are especially go... |
Definitely the better way to code CUDA in Windows right now is Nsight Visual Studio Edition environment. With the release of CUDA 5, comes also the Nvidia Nsight Eclipse Edition, with the same programming capabilities but with the IDE of Eclipse. Nsight Eclipse Edition is available on Linux and MacOS (but not Windows)... |
Let's saynis an integer (anintvariable in C). I need enough space for “4 times the ceiling of n divided by 3” bytes. How do I guarantee enough space for this?
Do you thinkmalloc(4*(int)ceil(n/3.0))will do, or do I have to add, say,1in order to be absolutely safe (due to possible rounding errors)?
|
you can achieve the same thing with pure integer arithmetic which guarantees that you allocate the correct amount of memory:editfixed brackets
```
malloc(4*((n+2)/3))
```
|
I have a question. Is there an efficient way to get the Hamiltonian paths between two nodes in a grid graph, leaving some predefined nodes out?
eg. (4*3 grid)
```
1 0 0 0
0 0 0 0
0 0 2 3
```
finding a Hamiltonian paths in this grid b/w vertices 1 and 2, but not covering 3? It seems bipartite graphs are a way, but w... |
Delete the nodes you dont need to include and run the brute force algorithm to find Hamiltonian path. This will take O((n-h)!+n), which is NP, where h is the number of nodes deleted, but that is the best you can do. Also to find Hamiltonian path, there is a dynamic approach but that too is exponential( O(2^n*n^2))
|
What happens internally when a functions that uses varargs is called? Are the arguments themselves stored on the heap or on the stack like any other arguments. If on the stack, how does that work?
|
It's implementation-dependent. But most probably, the args are placed on the stack, one after the other (after default argument promotions have been performed).
va_start,va_argetc. work by simply walking a pointer through the stack, and reinterpreting the bits as whatever type you ask for.
|
I've been working on a project that involves several preprocessing on a scanned document. Part of this preprocesses isskew detection and correction. Before skew detection and correction i have a binarization process going on for the document image.
I would like to see some projects or sample codes. Thanks !!
|
Some time ago I found a blog that had 2 interesting posts on this subject:
Detect skew angleRotation (Deskew)
These posts also share the source code.
|
I am looking for how to parse an XML file via a C libexpat and Linux. I'm looking for the parse does not load the entire file contents in memory, I want the parse is done by reading the xml document line by line.
Is there anyone I can propose a method using expat?
Thank you in advance for your help
|
XML_Parse just does that. See the sample code below:
```
actual_size = fread(xmlData, 1, 32, fp);
while (actual_size > 0) {
if (XML_Parse(parser, xmlData, actual_size, 0) == XML_STATUS_ERROR) {
printf("%s at line %l\n",
XML_ErrorString(XML_GetErrorCode(parser)),
(long) XML_... |
Well, my question may look like a basic stuff, but i am new to network programming side.
I wish to know:
1) Is it always required to bind a socket in order to receive message from that? I saw a sniffer code (raw socket) one in which directly it is invokingrecvfromand another piece of code in which it is invokingbinda... |
No, you don't need to bind().
If you're using a TCP or UDP socket where you are planning to either connect() or send a packet to a destination with sendto(), the kernel will automatically bind the socket to a suitable port number when you try to connect or send. This is generally the preferred way. bind()ing client s... |
My question is rather simple, yet I cannot find an easy solution:
I have an integer greater or eqal 16, so at least1000in binary. I wish to flip the third bit using the bitwise NOT operator. In this case, it would be1100.
Is there any operator which could do this? The~-operator flips all bits as far as I know, not ju... |
XOR with the bits that you want to flip.
```
int c = 0x10; // 10000b
int m = 0x08; // 01000b
c ^= m; // 11000b
```
|
Is there any possiblty to swap three numbers in a single statement
Eg :
a = 10b = 20c = 30
I want values to be changed as per the following list
```
a = 20
b = 30
c = 10
```
Can these values be transferred in a single line?
|
```
$ python
>>> a, b, c = 10, 20, 30
>>> print a, b, c
10 20 30
>>> a, b, c = b, c, a
>>> print a, b, c
20 30 10
```
|
I am working on Microsoft Visual Studio environment. I came across a strange behavior
```
char *src ="123";
char *des ="abc";
printf("\nThe src string is %c", src[0]);
printf("\tThe dest string is %c",dest[0]);
des[0] = src[0];
printf("\nThe src string is %c", src[0]);
printf("\tThe dest string is %c",dest[0]... |
This is undefined behavior:
```
des[0] = src[0];
```
Try this instead:
```
char des[] ="abc";
```
|
I have made an application in which there is a filemain.cwhich uses a function from themaster.cfile. I would like to debug my application for all functions defined in themaster.cfile by usinggdb tool. Is this possible and if so how?
|
You must compile your program using-gflag.
Then you startgdb your_programand set break points:break master.c:37that will set a break point on master.c, line #37 or you could set breaks at functions:break foo().
Then start your program byrunand continue with the debugging process,inspect,continue,watch,display...
ht... |
Can someone please explaing why the string is not splitted in the following code
```
#include <stdio.h>
int main(void)
{
char name[] = "first:last";
char first[20], last[20];
sscanf(name, "%s:%s", first, last);
printf("first: %s, last: %s", first, last);
return 0;
}
```
The output is
first: ... |
You can use something like this:
```
sscanf(name, "%[^:]:%s", first, last);
```
:is not whitespace, so a regular%swill not consider it as a delimiter. Seescanffor more details.
(Edited demo:http://ideone.com/m4LVP)
|
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed9 years ago.Improve this question
I'm starting to do programming with CUDA C. Are there any IDE that are especially go... |
Definitely the better way to code CUDA in Windows right now is Nsight Visual Studio Edition environment. With the release of CUDA 5, comes also the Nvidia Nsight Eclipse Edition, with the same programming capabilities but with the IDE of Eclipse. Nsight Eclipse Edition is available on Linux and MacOS (but not Windows)... |
Let's saynis an integer (anintvariable in C). I need enough space for “4 times the ceiling of n divided by 3” bytes. How do I guarantee enough space for this?
Do you thinkmalloc(4*(int)ceil(n/3.0))will do, or do I have to add, say,1in order to be absolutely safe (due to possible rounding errors)?
|
you can achieve the same thing with pure integer arithmetic which guarantees that you allocate the correct amount of memory:editfixed brackets
```
malloc(4*((n+2)/3))
```
|
I have a question. Is there an efficient way to get the Hamiltonian paths between two nodes in a grid graph, leaving some predefined nodes out?
eg. (4*3 grid)
```
1 0 0 0
0 0 0 0
0 0 2 3
```
finding a Hamiltonian paths in this grid b/w vertices 1 and 2, but not covering 3? It seems bipartite graphs are a way, but w... |
Delete the nodes you dont need to include and run the brute force algorithm to find Hamiltonian path. This will take O((n-h)!+n), which is NP, where h is the number of nodes deleted, but that is the best you can do. Also to find Hamiltonian path, there is a dynamic approach but that too is exponential( O(2^n*n^2))
|
What happens internally when a functions that uses varargs is called? Are the arguments themselves stored on the heap or on the stack like any other arguments. If on the stack, how does that work?
|
It's implementation-dependent. But most probably, the args are placed on the stack, one after the other (after default argument promotions have been performed).
va_start,va_argetc. work by simply walking a pointer through the stack, and reinterpreting the bits as whatever type you ask for.
|
I've been working on a project that involves several preprocessing on a scanned document. Part of this preprocesses isskew detection and correction. Before skew detection and correction i have a binarization process going on for the document image.
I would like to see some projects or sample codes. Thanks !!
|
Some time ago I found a blog that had 2 interesting posts on this subject:
Detect skew angleRotation (Deskew)
These posts also share the source code.
|
I am looking for how to parse an XML file via a C libexpat and Linux. I'm looking for the parse does not load the entire file contents in memory, I want the parse is done by reading the xml document line by line.
Is there anyone I can propose a method using expat?
Thank you in advance for your help
|
XML_Parse just does that. See the sample code below:
```
actual_size = fread(xmlData, 1, 32, fp);
while (actual_size > 0) {
if (XML_Parse(parser, xmlData, actual_size, 0) == XML_STATUS_ERROR) {
printf("%s at line %l\n",
XML_ErrorString(XML_GetErrorCode(parser)),
(long) XML_... |
Well, my question may look like a basic stuff, but i am new to network programming side.
I wish to know:
1) Is it always required to bind a socket in order to receive message from that? I saw a sniffer code (raw socket) one in which directly it is invokingrecvfromand another piece of code in which it is invokingbinda... |
No, you don't need to bind().
If you're using a TCP or UDP socket where you are planning to either connect() or send a packet to a destination with sendto(), the kernel will automatically bind the socket to a suitable port number when you try to connect or send. This is generally the preferred way. bind()ing client s... |
My question is rather simple, yet I cannot find an easy solution:
I have an integer greater or eqal 16, so at least1000in binary. I wish to flip the third bit using the bitwise NOT operator. In this case, it would be1100.
Is there any operator which could do this? The~-operator flips all bits as far as I know, not ju... |
XOR with the bits that you want to flip.
```
int c = 0x10; // 10000b
int m = 0x08; // 01000b
c ^= m; // 11000b
```
|
Is there any possiblty to swap three numbers in a single statement
Eg :
a = 10b = 20c = 30
I want values to be changed as per the following list
```
a = 20
b = 30
c = 10
```
Can these values be transferred in a single line?
|
```
$ python
>>> a, b, c = 10, 20, 30
>>> print a, b, c
10 20 30
>>> a, b, c = b, c, a
>>> print a, b, c
20 30 10
```
|
I'm trying this basic code block to familiarize myself with conditionals. I don't think I haved missed a parenthesis or anything, however I get an error that I am missing a statement before the second else clause, but I don't understand this.
```
#include stdio.h;
main()
{
int a = 2;
int b = 4;
int c = 6;... |
If you properly indent your code, you'll see the problem:
```
} else {
if ( c > d) {
c = c + d;
}
} else {
d = d / 2;
}
```
|
What is the best way to represent a C array in Erlang? I plan on passing a C array to Erlang using NIF. The array is composed of bytes and I'll need to modify some of the bytes as the program runs. Any help is appreciated.
|
If function in NIF not reallocate array than you can represent you array as a tuple with two elements - raw pointer and elements count.
|
I'm trying to convert a decimal to binary but I get unexpected result.
The following code returns00000000000000000000000000000010ÔýDv
Instead of00000000000000000000000000000010
```
#include <stdio.h>
#include <string.h>
char *bin(long dec, long len);
main(){
bin(2,32);
return 0;
}
char *bin(long dec, lon... |
Yourbarray is not 0-terminated. You are lucky that your program just doesn't crash!
bshould be of lengthlen+1, and when you are done writing in it, dob[len] = 0;before returning it.
|
```
int main (void)
{
int i;
for (i=1; i<=20; i++) {
int j;
unsigned long long fac = 1;
for ( j = 1; j<=i; ++j) {
fac *= j;
}
printf ("%2i! = %ld\n", i, fac);
}
return 0;
}
```
From 14! to 20! outputs wrong values.
It either gives a negative number or the num... |
```
printf ("%2i! = %ld\n", i, fac);
```
The problem is here, use proper notation for unsigned long long type value
Try:
```
printf ("%2i! = %llu\n", i, fac);
```
|
```
#include <unistd.h>
(size_t) sysconf(_SC_PAGESIZE);
```
sysconf(_SC_PAGESIZE) tells me that my memory page size is 4096 on my operating system and processor. Of the 4096 bytes in the memory page, how many can be used for data and how much is overhead/metadata?
I have an application where I am optimizing cache l... |
No metadata. 4096 bytes are usable.The OS does store metadata somewhere, but it's on other pages, which shouldn't bother you.
Whether or not you can access memory, however, doesn't depend on the page size. If you have allocated 100 bytes, you can access just 100 bytes. If you have allocated 4096, you can access 4096.... |
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed9 years ago.Improve this question
After writing so many for loop, I could not find to name iterator. I want write mean... |
If you have more then 3 nested loops in the same function, this is acode-smell.
You should probablyrefactoryour code [move some staff into other functions, and use these functions].
i,j,k should be enough for most functions.
|
When I disassembled my C code, I saw the following. What does this code do exactly? Does it have something to do with floating points?
```
movsd (%rdx,%rax,8),%xmm0
mulsd %xmm0,%xmm0
movsd %xmm0,0x30(%rsp)
```
|
it squares a number:
```
xmm0=*(rdx*8+rax);
xmm0*=xmm0;
rsp[0x30]=xmmm0;
```
xmm0 is a floating point register.
|
I've created a header file "foo.h" as well as an source file "bar.c" but can't seem to import bar.c into foo.h.
Is this possible? If so, could someone please point me in the right direction?
|
You've got it backwards....hfiles exist to tell other programs what a.cfile contains. The.cimplementsthe things listed in the header.
Then, when a different program wants to use some of the stuff you implemented, they#includeyour header. When it compiles, another program called thelinkeris also run. This connects the... |
When one declares
```
int my_number = 300;
```
Compiler allocates enough memory to store exactly 1 integer and writes bit representation of 300 in that space.
When oneinstead
```
#define MY_NUMBER 300
```
WheneverMY_NUMBERis mentioned, value is simply replaced with 300.
I understand that symbolic constants ar... |
Zero. The#define-d constant is not a real constant: it does not have a type, and it does not occupydatamemory. Its occurrences in your program are replaced with the literal300, that's all. The constant value does occupyprogrammemory in the binary code of your program, but it's not the kind of memory to which you could... |
I know there is the CLucene project, which is a port of Lucene from Java to C. But is there a Lucene wrapper in C/Objective-C similar to PyLucene that uses JNI and and embeds a JavaVM with Lucene in a separate process?
|
I explored this in some depth after askingthis similar questiona while back. The answer appears to be "no." I found CLucene as you did. It's got problems. I also found something called LuceneKit which was also mostly a mess. For my project I just mangled up the code from PyLucene just enough to get it working, and the... |
```
int a = 1;
int b = (1,2,3);
cout << a+b << endl; // this prints 4
```
Is(1,2,3)some sort of structure in c++ (some primitive type of list, maybe?)Why isbassigned the value3? Does the compiler simply take the last value from the list?
|
Yes, that's exactly it: the compiler takes the last value. That's the comma operator, and it evaluates its operands left-to-right and returns the rightmost one. It also resolves left-to-right. Why anyone would write code like that, I have no idea :)
Soint b = (1, 2, 3)is equivalent toint b = 3. It's not a primitive l... |
I have a doubt regarding the concept of encapsulation.
Isn't C language also does the encapsulation by 'struct' data type?
the data variables and the functions present in the struct can only be called by the struct variable. and no other variable in the system. Isn't it data hiding?
I am trying to relate this conce... |
There really only exists "partial hiding" of structs in C. You can look at this post for a more detailed explanation:
Is there any workaround for making a structure member somehow 'private' in C?
However, encapsulation in C++ is relatively similar. You cannot completely hide all data members from the client code (ev... |
I've been playing with WebGL quite a bit lately and I really digThree.js. It's really lightweight and just serves as something that makes wrangling most of the GL calls a bit easier, and provides a quick way of creating basic primatives like a sphere.
Now, in native land, it seems that all the frameworks want to be ... |
Here is a port of three to C++:https://github.com/jdduke/three_cpp
Core - 75% complete (TODO: Morph targets, shadows, plugin support)Extras - 5-10% complete (TODO: Pretty much everything)Examples - 25% complete (TODO: Examples involving morph targets an)
|
Using C and the Winsock library (UDP), I made a client-server multiplayer game.
Now I would like to make it so clients can be connected directly to each other (for example in Warcraft III when someone hosts a game the other players connect directly to him), but I do not know and could not find information on how to d... |
For the most part - especially in today's unfortunate world where most clients are behind NAT firewalls and ISPs that block so many incoming connections - client/server programs such as what you're looking to do will route all traffic through the central server, which is "guaranteed" to be accessible from all clients.... |
How I could convert array of type short to array of type double in C/C++?
I have code to read audio data from wav file and output is array of type short. So now I want to use this data for FFT (I don't want use libraries).
Any tricks or ideas?
|
You can'tconvertthe array; you can however create a new array with the converted values:
```
#include <iterator>
#include <algorithm>
short src[10] = ...;
double dst[sizeof(src)/sizeof(short)];
std::copy(std::begin(src), std::end(src), dst); // generic, C++11
std::copy(src, src + 10, dst); // a ... |
I'd like to create my very own list container using Cython. I'm a very new begginer to it, and following the documentation I could get to creating such a structure :
```
cdef struct s_intList:
int value
void* next
ctypedef s_intList intList
```
but when comes the time to acces the struct members, I can't... |
You have to allocate the memory for the intList. Either with a local variable or
using malloc.
```
cdef struct s_intList:
int value
void* next
ctypedef s_intList intList
cpdef object foo():
cdef intList li
li.value = 10
```
|
I have seen#ifndef ABCand#if !defined (ABC)in the same C source file.
Is there subtle difference between them?
(If it is a matter of style, why would someone use them in the same file)
|
No, there's no difference between the two when used that way. The latter form (usingdefined()) is useful when the initial#ifor one of the subsequent#elifconditions needs a more complex test.#ifdefwill still work, but it might be clearer using#if defined()in that case. For example, if it needs to test if more than one ... |
Is!!(x)guaranteed by the standard to return 0/1?
Note that I amnotasking about c++, where a bool type is defined.
|
Yes, in C99, see §6.5.3.3/4:
The result of the logical negation operator ! is0if the value of its operand compares
unequal to 0,1if the value of its operand compares equal to 0. The result has typeint.
The expression !E is equivalent to (0==E).
So!xand!!ycan only yield 0 or 1, asints.
For other operators, in C... |
I have a shared library written in C++. It exports a visible interface made ofextern "C"functions which create, destroy and manipulate opaque types.
Now, I'd like to have a pure C program which uses this library.
Can I do this (platform independently) ? When will the C++ runtime and the C++ static objects get initia... |
The initialization phase is platform dependent.
In the case of Linux, dynamically loaded libraries can have specially declared symbols that are automatically called bydlopen()when the library is loaded.
See the manpage fordlopen(3), sectionThe obsolete symbols init() and fini()for more info.
Static initializers are ... |
I am a newbie writing code for sound playback via "alsa api".
I have to repeatedly call a functionsend_output()10 times in a sec as:
```
while(true)
{
send_output();
usleep(100000);
}
```
but this is a bad way of programming since within theusleep()function processor is still busy executing the code.
I w... |
man usleep
```
usleep - suspend execution for microsecond intervals
```
|
Are there any functions in netapi32.dll or in some other .dll that can remove aremoteuser account from the Administrators group? Is it possible to do withNetLocalGroupDelMembers? If it is possible, where are parameters of admin's name and password in this function ?
|
Yes it is possible, as per thedocumentationyou just pass "domainname\username" in theLOCALGROUP_MEMBERS_INFO_3structure.
You don't specify the username and password when calling it, you just need to be running as that user.
|
This might sound rather awkward, but I want to ask if there is a commonly practiced way of storing tabular data in a text file to be read and written in C.
Like in python you can load a full text file nto an array byf.readlinesthen go through all the lines andspliteach line by a specific character or sequence of char... |
Pretty much the same way you would in any other language. Pick a field separator (I.E.,tabcharacter), open the text file for reading and parse each line.
Of course, inCit will never be as easy as it is inPython, but approaches are similar.
|
When one declares
```
int my_number = 300;
```
Compiler allocates enough memory to store exactly 1 integer and writes bit representation of 300 in that space.
When oneinstead
```
#define MY_NUMBER 300
```
WheneverMY_NUMBERis mentioned, value is simply replaced with 300.
I understand that symbolic constants ar... |
Zero. The#define-d constant is not a real constant: it does not have a type, and it does not occupydatamemory. Its occurrences in your program are replaced with the literal300, that's all. The constant value does occupyprogrammemory in the binary code of your program, but it's not the kind of memory to which you could... |
I know there is the CLucene project, which is a port of Lucene from Java to C. But is there a Lucene wrapper in C/Objective-C similar to PyLucene that uses JNI and and embeds a JavaVM with Lucene in a separate process?
|
I explored this in some depth after askingthis similar questiona while back. The answer appears to be "no." I found CLucene as you did. It's got problems. I also found something called LuceneKit which was also mostly a mess. For my project I just mangled up the code from PyLucene just enough to get it working, and the... |
```
int a = 1;
int b = (1,2,3);
cout << a+b << endl; // this prints 4
```
Is(1,2,3)some sort of structure in c++ (some primitive type of list, maybe?)Why isbassigned the value3? Does the compiler simply take the last value from the list?
|
Yes, that's exactly it: the compiler takes the last value. That's the comma operator, and it evaluates its operands left-to-right and returns the rightmost one. It also resolves left-to-right. Why anyone would write code like that, I have no idea :)
Soint b = (1, 2, 3)is equivalent toint b = 3. It's not a primitive l... |
I have a doubt regarding the concept of encapsulation.
Isn't C language also does the encapsulation by 'struct' data type?
the data variables and the functions present in the struct can only be called by the struct variable. and no other variable in the system. Isn't it data hiding?
I am trying to relate this conce... |
There really only exists "partial hiding" of structs in C. You can look at this post for a more detailed explanation:
Is there any workaround for making a structure member somehow 'private' in C?
However, encapsulation in C++ is relatively similar. You cannot completely hide all data members from the client code (ev... |
I've been playing with WebGL quite a bit lately and I really digThree.js. It's really lightweight and just serves as something that makes wrangling most of the GL calls a bit easier, and provides a quick way of creating basic primatives like a sphere.
Now, in native land, it seems that all the frameworks want to be ... |
Here is a port of three to C++:https://github.com/jdduke/three_cpp
Core - 75% complete (TODO: Morph targets, shadows, plugin support)Extras - 5-10% complete (TODO: Pretty much everything)Examples - 25% complete (TODO: Examples involving morph targets an)
|
Using C and the Winsock library (UDP), I made a client-server multiplayer game.
Now I would like to make it so clients can be connected directly to each other (for example in Warcraft III when someone hosts a game the other players connect directly to him), but I do not know and could not find information on how to d... |
For the most part - especially in today's unfortunate world where most clients are behind NAT firewalls and ISPs that block so many incoming connections - client/server programs such as what you're looking to do will route all traffic through the central server, which is "guaranteed" to be accessible from all clients.... |
How I could convert array of type short to array of type double in C/C++?
I have code to read audio data from wav file and output is array of type short. So now I want to use this data for FFT (I don't want use libraries).
Any tricks or ideas?
|
You can'tconvertthe array; you can however create a new array with the converted values:
```
#include <iterator>
#include <algorithm>
short src[10] = ...;
double dst[sizeof(src)/sizeof(short)];
std::copy(std::begin(src), std::end(src), dst); // generic, C++11
std::copy(src, src + 10, dst); // a ... |
I'd like to create my very own list container using Cython. I'm a very new begginer to it, and following the documentation I could get to creating such a structure :
```
cdef struct s_intList:
int value
void* next
ctypedef s_intList intList
```
but when comes the time to acces the struct members, I can't... |
You have to allocate the memory for the intList. Either with a local variable or
using malloc.
```
cdef struct s_intList:
int value
void* next
ctypedef s_intList intList
cpdef object foo():
cdef intList li
li.value = 10
```
|
I have seen#ifndef ABCand#if !defined (ABC)in the same C source file.
Is there subtle difference between them?
(If it is a matter of style, why would someone use them in the same file)
|
No, there's no difference between the two when used that way. The latter form (usingdefined()) is useful when the initial#ifor one of the subsequent#elifconditions needs a more complex test.#ifdefwill still work, but it might be clearer using#if defined()in that case. For example, if it needs to test if more than one ... |
Is!!(x)guaranteed by the standard to return 0/1?
Note that I amnotasking about c++, where a bool type is defined.
|
Yes, in C99, see §6.5.3.3/4:
The result of the logical negation operator ! is0if the value of its operand compares
unequal to 0,1if the value of its operand compares equal to 0. The result has typeint.
The expression !E is equivalent to (0==E).
So!xand!!ycan only yield 0 or 1, asints.
For other operators, in C... |
I have a shared library written in C++. It exports a visible interface made ofextern "C"functions which create, destroy and manipulate opaque types.
Now, I'd like to have a pure C program which uses this library.
Can I do this (platform independently) ? When will the C++ runtime and the C++ static objects get initia... |
The initialization phase is platform dependent.
In the case of Linux, dynamically loaded libraries can have specially declared symbols that are automatically called bydlopen()when the library is loaded.
See the manpage fordlopen(3), sectionThe obsolete symbols init() and fini()for more info.
Static initializers are ... |
I am a newbie writing code for sound playback via "alsa api".
I have to repeatedly call a functionsend_output()10 times in a sec as:
```
while(true)
{
send_output();
usleep(100000);
}
```
but this is a bad way of programming since within theusleep()function processor is still busy executing the code.
I w... |
man usleep
```
usleep - suspend execution for microsecond intervals
```
|
In a particular situation I need to have variable (character array or std:string) where the size should not be more than 10 kB.
How can I limit the size of this variable?
|
Just don't resize it to be more than the size limit:
```
char* realloc_lim(char* data, int new_count, bool &ok)
{
if(sizeof(char) * new_count > SIZE_LIMIT)
{
ok = false;
return null;
} else {
ok = true;
return (char*)realloc((void*)data, sizeof(char) * new_count);
}
}
`... |
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed11 years ago.Improve this question
see i have one audio track whose sample rate is 44100 then what does it mean ?
what is the duration of one frame of audio... |
A sample of audio is similar to a frame of video, it's a capture of the sound level at a particular time point, in the same way as a frame of video is a capture of the light pattern. A frame rate of 44,100 is 44,100 samples per SECOND, or 44.1 kHz. So a sample duration is 1/44,100 seconds = 2.26e-5 seconds.
We can he... |
I defined a macro as follows:
```
#define ccpd(__X__, __Y__) (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) ? CGPointMake(__X__ * 0.416667f ,__Y__ * 0.416667f) : CGPointMake(__X__,__Y__)
```
Later:
```
CGPoint p1 = ccpd(1280, 440);
CGPoint p2 = ccpd(1024 + 256, 440);
```
This what I get:
```
(gdb) p p1
... |
You macro in the second case expands to something like:
```
CGPointMake( 1024 + 256 * 0.416667f, ...
```
which is
```
CGPointMake( 1024 + (256 * 0.416667f), ...
```
Add parenthesis around the macro parameters:
```
CGPointMake( (__X__) * 0.416667f, (__Y__) * ...
```
or better: make a proper function and let the c... |
I have a library managed by autotools. I have the following line in theMakefile.am, as well as other necessary configurations
```
lib_LTLIBRARIES = libstuff.la
```
My project also builds a program to run some test suites. This program is configured as follows:
```
noinst_PROGRAMS = runtests
runtests_SOURCES = test/... |
The right way to do this is to add the-staticflag to anLDFLAGSvariable.
For all targets:AM_LDFLAGS = -static
Or specifically for the test program:runtests_LDFLAGS = -static
|
I intend to use syslog for logging in an application. I need to be able to disable logging, at compile time, perhaps using a macro. Is this possible to do with the syslog facilities, or do I need to wrap syslog in my own macros/functions? The ability to disable/enable log messages based on their priority is a plus.
|
Maybe you could wrap a call tosetlogmaskin define block.
setlogmasksets a mask (the “logmask”) that determines which future
syslog calls shall be ignored. If a program has not called setlogmask,
syslog doesn't ignore any calls. You can use setlogmask to specify
that messages of particular priorities shall be ig... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:how does do{} while(0) work in macro?
Example fromthisblog post:
```
#define VTAILQ_INSERT_BEFORE(listelm, elm, field) do { \
(elm)->field.vtqe_prev = (listelm)->field.vtqe_prev; \
VTAILQ_NEXT((elm), field)... |
Long story short:
If you use a non looped macro in an unbraced if else statement, you will get screwed.
```
if (a)
VTAILQ_INSERT_BEFORE(c, d, e);
else
blah(b);
```
Would break terribly in this case.
More detailed answer here:
Why use apparently meaningless do-while and if-else statements in macros?
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:C : pointer to struct in the struct definition
In my beginer course we need to declare a struct for tree search. I need pointers for reference of same type in each node. This decleration seems incorrect, pnode is not known in this context.... |
the C Faq is a good reference.http://c-faq.com/struct/selfref.html
I tend to use the typedef before the struct method
http://c-faq.com/decl/selfrefstruct.html
```
typedef struct a *APTR;
typedef struct b *BPTR;
struct a {
int afield;
BPTR bpointer;
};
struct b {
int bfield... |
Given a node in a graph that is reachable, how do you find all the nodes that are reachable ? How would you enable parallel computation of this information ? Given a number of cores, how many threads would you choose ?
For the first part, i would go with the Breadth first Search and second part, i think somehow i sho... |
There is a worked out example in the article:breadth-first graph search using an iterative map-reduce algorithm
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.