question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I read INI file strings through GetPrivateProfileString API. However, the INIs in local windows directory could be read like that.
How can I read and edit a INI file in a Remote machine.
|
You should not expect to be able to modify INI files stored on remote machines. Whatever your problem is, this is not the solution.
|
How do I read command-line parameters in C? For example, in
```
./test --help
```
or
```
./test --build
```
how do I access "--build" or "--help"?
|
Your parameters are in argv:
```
int main(int argc, char **argv)
```
if you printf the content of argv (argv[0],argv[1] etc) youll get the idea.
try:
```
int main (int argc, char **argv)
{
for(int i = 0;i< argc;i++)
printf("%s\r\n",argv[i]);
}
```
|
In my Operating System class we are programming in C and we overrode the Timer Interrupt, after that from the timer interrupt we wrote we have to handle 4 processes, but we need to get the context of the process, like the instruction pointer, data segment, etc. How can we get that information from c? if not, do we need to use also ASM inside the C code? thanks :D
I'm using virtual box with Windows XP 32 bits, and using the DOS 16 bit virtual machine
|
Yes, you pretty much need at least a little bit of assembly language. A typical starting point ispusha. That preserves the main general purpose registers so you have someplace to work without destroying anything critical. If you're supporting the FPU, you'll probably want to look atfsave. You restore those withpopaandfrestorerespectively.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:about “int const *p” and “const int *p ”
Difference between
```
const char *p
```
and
```
char * const p?
```
is that fist one means cannot change char. Later one means cannot change the pointer. Am I right?
Thank you!
|
```
const char *p
```
means the characters cannot be changed.*p = '\0'is illegal. Varpis a pointer to aconst char.
```
char * const p
```
means the pointer cannot be changed.p = 0is illegal. Constantpis a pointer to achar.
```
const char * const p
```
means neither can be changed. Constantpis a pointer to aconst char.
Update: Added third declaration.
|
```
char *xyz()
{
char str[32];
strcpy(str,"Hello there!");
return(str);
}
void main()
{
printf("%s",xyz());
}
```
When I call xyz(), is it will return a dangling pointer ?
Thanks
|
Yes, it is a dangling pointer. Your program invokes undefined behaviour.
On some systems it might crash your application, on others it might appear to work correctly. But either way, you should not do it.
|
I want to read floats (and ints afterwards) from a line I'm getting out of a file. When I'm debugging it, I can see it's getting the line out of the file no problem, but when I try to sscanf it, I'm getting garbage. Here's my code:
```
while(fgets(line, 1000, file) != EOF)
{
//Get the first character of the line
c = line[0];
if(c == 'v')
{
sscanf(line, "%f", &v1);
printf("%f", v1);
}
}
```
The value stored in v1 is garbage. Why is this not working, and how can I get floats and ints out of this line?
|
You're including the first character (which is 'v') in the call to sscanf, so the call is failing andv1is left untouched (with garbage in it). Try this instead:
```
sscanf(line+1, "%f", &v1);
```
|
I'm writing a C console application, and I want to parse command line arguments in visual studio while debugging, I know how to do it in eclipse but can't find this option in visual studio. So where can I find this option?
|
In your project, go to:
Project->Project nameProperties
alternately hit Alt+F7, or, in solution explorer, right click on your project and choose "properties" from the drop down menu.
then, go to:
Configuration Properties->Debugging
You can pass command line arguments in on the line that saysCommand Arguments
|
I need to convert a binary number to a two-digit decimal number. For example:
```
01111 becomes 15
00011 becomes 03
```
I'm not simply trying to display the digits. I need to put each digit into an int variable. Say I have two int variables, leftnum and rightnum.
Then in the first example, leftnum = 1 and rightnum = 5.
In the second example, leftnum = 0 and rightnum = 3.
There are two restrictions which make this a little difficult. mod and / can only be used with powers of 2.
|
```
int i = 0;
do {
i ++;
} while (i * 10 <= originalInt);
int leftInt = i - 1; // e.g. for "originalInt = 40" -> "i = 5", so we must decrement 1
int rightInt = originalInt - leftInt * 10;
```
or more compact and using less variables:
```
int leftInt = 0;
do {leftInt ++;} while (leftInt * 10 <= originalInt);
int rightInt = originalInt - (-- leftInt) * 10;
```
|
I have a UTF-8 string as achar*. In order to get theone byte per characterproperty (and thus have random access into the string by character indexes) I currently just remove all UTF-8 continuation bytes from it (I would like to avoid "proper" conversion to a static byte width representation).
Instead of removing all continuation bytes I would like to be able to check whether a given multi-byte UTF-8 character is alphanumeric (or not) and then replace it with a corresponding ASCII character (let's sayafor alphanumerics and.otherwise). How do I do this?
|
For each byte in the string:
If it is an ASCII byte, just copy it.If it is a UTF-8 head byte, decode starting from that byte towchar_tusingmbrtowc, determine an ASCII character whose classification matches by comparing the results of theisw*()functions, and copy that ASCII character to the output.If it is anything else, skip it.
|
Let's say I have a number like 21 and I want to split it up so that I get the numbers 2 and 1.
To get 1, I could do 1 mod 10. So basically, the last digit can be found out by using mod 10.
To get 2, I could do (21 - (1 mod 10))/10.
The above techniques will work with any 2-digit number.
However, let me add a further constraint, that mod can only be used with powers of 2. Then the above method can't be used.
What can be done then?
|
```
2 == 23 / 10
3 == 23 - (23 / 10) * 10
```
|
Is it possible to allocate 7 bytes of memory and just free the first 3 bytes to form a 4 byte block, through any Windows APIs.
|
You could usememmove()to move the last four bytes to the start of the allocated block then userealloc()to shrink it down to four bytes.
But why would you ever want to? You can always just have another pointer to the last four bytes of malloced memory like this:
```
typedef unsigned char uint8;
uint8* psevenbytes = (uint8*)malloc(sizeof(uint8) * 7);
if (psevenbytes != NULL)
{
uint8* pfourbytes = psevenbytes + 3;
// ... do stuff
free(psevenbytes);
psevenbytes = NULL;
}
```
Or you could use astruct.
|
In mac os x, you can combine 32bit, powerpc and 64bit binaries in one executable using "lipo" is something like this possible in linux?
|
I think Fatelf (available athttp://icculus.org/fatelf/) is what you are actually asking for, but it requires certain patches to kernel, glibc, gdb etc. So it's currently not for the faint of heart to use. It may be a reasonable burden for a developer to compile on a modified system, but it also requires client-side systems to be modified, too.
|
is there a C macro or some kind of way that i can check if my c program was compiled as 64bit or 32bit at compile time in C?
Compiler: GCC
Operating systems that i need to do the checks on: Unix/Linux
Also how could i check when running my program if the OS is capable of 64bit?
|
Since you tagged this "gcc", try
```
#if __x86_64__
/* 64-bit */
#endif
```
|
I want to usePMD 4.2.5to find duplicates in my C code. I use the example commandline from their documentation:
```
java net.sourceforge.pmd.cpd.CPD --minimum-tokens 100 --files C:\src --language cpp
```
this gives me the error:
```
Can't find the custom format --language: java.lang.ClassNotFoundException
```
I tried a lot of different other things too, none worked. The GUI version of the PMD works nicely.
What commandline do i have to use to get PMD to detect duplicate code?
|
It seems it wants to load a class to do the language-specific parsing; make sure your CLASSPATH is set up properly.
|
I need to edit the header information of several PDF files.
What I'd like to achieve is to remove all header data before%PDF-X.Y.Z.
What I came up with as a possible solution was to open the PDF in binary mode, read each character until%PDF-X.Y.Zis found.
Then continue reading the rest of the stream and save it to a new file. I thought this way I will end up with an exact binary copy of the PDF, just with different header information.
What's the easiest/best way to do this in C?
Are there any libraries available that could help me do this?
I'm also interested in hearing different approaches to solve this problem.
Thanks.
|
Actually you can trow away all information before%PDFtag, BUT you make xref table at the end of file invalid. This table contains offset references to PDF objects.
Easiest way was: remove the part before%PDFand count, how much you trow away, reduce values in xref according.
|
I have 2 processes talking to each other Sender and Receiver via socket.I would like to catch signal Control-C and instead of exiting - display some output.Sender and Receiver are working fine,so I added signal(SIGINT,handler) to Sender's body. handler() just outputs some text.So when I run them and hit Cnt-C - signal gets caught and handler outputs the text but exits the Sender process.Sender has a loop that listens for user input unless Cnt-D - so why handler is making Sender exit?
|
If you are not re-registering the signal inside the handler, then it will revert to the default value, and exit once a signal has been sent the second time. For more detailed explanation look at my posthere.
|
I want to use gdb for looking into the various details of the fork() system call. To do this, I used one breakpoint at the fork() and from there onwards i am using step command but this way it is not working fine.
Can somebody explain me how to use gdb to look into every single step occuring during fork() system call?
|
Maybe you meant that you want to follow the child process instead of the parent once the fork is called? In that case:
If you want to follow the child
process instead of the parent process,
use the command set follow-fork-mode.set follow-fork-modemodeSet the debugger response to a program call of fork or vfork. A call
to fork or vfork creates a new
process. The mode argument can be:parent: The original process is debugged after a fork. The child
process runs unimpeded. This is the
default.child: The new process is debugged after a fork. The parent process runs
unimpeded.
|
C Programming:
What happens when a thread tries to acquire a mutex lock, and fails to get it?
Does it go to sleep?
Will the thread be woken up when pthread_mutex_unlock(&mutex); is called?
Then try to obtain the lock again?
|
From theman page:
Thepthread_mutex_lock()function locksmutex. If the mutex is already locked, the calling thread will block until the mutex becomes available.
So yes - your thread is blocked until the lock is available and it can obtain it.
|
From what I know an integer is in the range of 32,768 to 32,767.
A long integer is in the range of 2,147,483,648 to 2,147,483,647.
I doubledchecked wikipedeia to make sure.
The problem now:
```
int a=2147483647;
printf("a: %d\n", a);
```
Why does this work? If I add 1 to 2147483647 then it prints garbage, something to be expected if the variable is a long integer. But why does it allow me to assign a long integer number to an integer in the first place?
|
From what I know an integer is in the range of 32,768 to 32,767.
This is incorrect. The range ofintis at least -32,767 to 32,767; it might have greater range and on most 32-bit and 64-bit platforms it does.
You can find out the range of theinttype on your platform by checking theINT_MAXandINT_MINmacros defined in<limits.h>.
|
I compiled gcc on one of my ubuntu 10.10 hosts, and installed it in /c. I can compile c and c++ programs fine on that host but when i copy /c (which contains bin, libexec etc) to a ubuntu 10.04.2 host i get:
```
/c/libexec/gcc/i686-pc-linux-gnu/4.5.2/cc1: error while loading shared libraries: libmpc.so.2: cannot open shared object file: No such file or directory
```
when compiling a simple .c file.
I've also installed and compiled gmp, mpfr and mpc from source (same versions as i did on the 10.10 host) but it's still coming up with the same error.
The reason i'm not recompiling gcc on each host is because it takes too long, and prefer not to use the gcc (from the build-essential) deb that comes with ubuntu
Please help
|
did you export your LD_LIBRARY_PATH environment variable? Looking at the error, it's not able to find libmpc.so.2.
Try 'locate libmpc.so.2' and if you can find that,
export LD_LIBRARY_PATH=
|
I read INI file strings through GetPrivateProfileString API. However, the INIs in local windows directory could be read like that.
How can I read and edit a INI file in a Remote machine.
|
You should not expect to be able to modify INI files stored on remote machines. Whatever your problem is, this is not the solution.
|
How do I read command-line parameters in C? For example, in
```
./test --help
```
or
```
./test --build
```
how do I access "--build" or "--help"?
|
Your parameters are in argv:
```
int main(int argc, char **argv)
```
if you printf the content of argv (argv[0],argv[1] etc) youll get the idea.
try:
```
int main (int argc, char **argv)
{
for(int i = 0;i< argc;i++)
printf("%s\r\n",argv[i]);
}
```
|
In my Operating System class we are programming in C and we overrode the Timer Interrupt, after that from the timer interrupt we wrote we have to handle 4 processes, but we need to get the context of the process, like the instruction pointer, data segment, etc. How can we get that information from c? if not, do we need to use also ASM inside the C code? thanks :D
I'm using virtual box with Windows XP 32 bits, and using the DOS 16 bit virtual machine
|
Yes, you pretty much need at least a little bit of assembly language. A typical starting point ispusha. That preserves the main general purpose registers so you have someplace to work without destroying anything critical. If you're supporting the FPU, you'll probably want to look atfsave. You restore those withpopaandfrestorerespectively.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:about “int const *p” and “const int *p ”
Difference between
```
const char *p
```
and
```
char * const p?
```
is that fist one means cannot change char. Later one means cannot change the pointer. Am I right?
Thank you!
|
```
const char *p
```
means the characters cannot be changed.*p = '\0'is illegal. Varpis a pointer to aconst char.
```
char * const p
```
means the pointer cannot be changed.p = 0is illegal. Constantpis a pointer to achar.
```
const char * const p
```
means neither can be changed. Constantpis a pointer to aconst char.
Update: Added third declaration.
|
```
char *xyz()
{
char str[32];
strcpy(str,"Hello there!");
return(str);
}
void main()
{
printf("%s",xyz());
}
```
When I call xyz(), is it will return a dangling pointer ?
Thanks
|
Yes, it is a dangling pointer. Your program invokes undefined behaviour.
On some systems it might crash your application, on others it might appear to work correctly. But either way, you should not do it.
|
I want to read floats (and ints afterwards) from a line I'm getting out of a file. When I'm debugging it, I can see it's getting the line out of the file no problem, but when I try to sscanf it, I'm getting garbage. Here's my code:
```
while(fgets(line, 1000, file) != EOF)
{
//Get the first character of the line
c = line[0];
if(c == 'v')
{
sscanf(line, "%f", &v1);
printf("%f", v1);
}
}
```
The value stored in v1 is garbage. Why is this not working, and how can I get floats and ints out of this line?
|
You're including the first character (which is 'v') in the call to sscanf, so the call is failing andv1is left untouched (with garbage in it). Try this instead:
```
sscanf(line+1, "%f", &v1);
```
|
I'm writing a C console application, and I want to parse command line arguments in visual studio while debugging, I know how to do it in eclipse but can't find this option in visual studio. So where can I find this option?
|
In your project, go to:
Project->Project nameProperties
alternately hit Alt+F7, or, in solution explorer, right click on your project and choose "properties" from the drop down menu.
then, go to:
Configuration Properties->Debugging
You can pass command line arguments in on the line that saysCommand Arguments
|
I need to convert a binary number to a two-digit decimal number. For example:
```
01111 becomes 15
00011 becomes 03
```
I'm not simply trying to display the digits. I need to put each digit into an int variable. Say I have two int variables, leftnum and rightnum.
Then in the first example, leftnum = 1 and rightnum = 5.
In the second example, leftnum = 0 and rightnum = 3.
There are two restrictions which make this a little difficult. mod and / can only be used with powers of 2.
|
```
int i = 0;
do {
i ++;
} while (i * 10 <= originalInt);
int leftInt = i - 1; // e.g. for "originalInt = 40" -> "i = 5", so we must decrement 1
int rightInt = originalInt - leftInt * 10;
```
or more compact and using less variables:
```
int leftInt = 0;
do {leftInt ++;} while (leftInt * 10 <= originalInt);
int rightInt = originalInt - (-- leftInt) * 10;
```
|
I have a UTF-8 string as achar*. In order to get theone byte per characterproperty (and thus have random access into the string by character indexes) I currently just remove all UTF-8 continuation bytes from it (I would like to avoid "proper" conversion to a static byte width representation).
Instead of removing all continuation bytes I would like to be able to check whether a given multi-byte UTF-8 character is alphanumeric (or not) and then replace it with a corresponding ASCII character (let's sayafor alphanumerics and.otherwise). How do I do this?
|
For each byte in the string:
If it is an ASCII byte, just copy it.If it is a UTF-8 head byte, decode starting from that byte towchar_tusingmbrtowc, determine an ASCII character whose classification matches by comparing the results of theisw*()functions, and copy that ASCII character to the output.If it is anything else, skip it.
|
Let's say I have a number like 21 and I want to split it up so that I get the numbers 2 and 1.
To get 1, I could do 1 mod 10. So basically, the last digit can be found out by using mod 10.
To get 2, I could do (21 - (1 mod 10))/10.
The above techniques will work with any 2-digit number.
However, let me add a further constraint, that mod can only be used with powers of 2. Then the above method can't be used.
What can be done then?
|
```
2 == 23 / 10
3 == 23 - (23 / 10) * 10
```
|
Is it possible to allocate 7 bytes of memory and just free the first 3 bytes to form a 4 byte block, through any Windows APIs.
|
You could usememmove()to move the last four bytes to the start of the allocated block then userealloc()to shrink it down to four bytes.
But why would you ever want to? You can always just have another pointer to the last four bytes of malloced memory like this:
```
typedef unsigned char uint8;
uint8* psevenbytes = (uint8*)malloc(sizeof(uint8) * 7);
if (psevenbytes != NULL)
{
uint8* pfourbytes = psevenbytes + 3;
// ... do stuff
free(psevenbytes);
psevenbytes = NULL;
}
```
Or you could use astruct.
|
In mac os x, you can combine 32bit, powerpc and 64bit binaries in one executable using "lipo" is something like this possible in linux?
|
I think Fatelf (available athttp://icculus.org/fatelf/) is what you are actually asking for, but it requires certain patches to kernel, glibc, gdb etc. So it's currently not for the faint of heart to use. It may be a reasonable burden for a developer to compile on a modified system, but it also requires client-side systems to be modified, too.
|
is there a C macro or some kind of way that i can check if my c program was compiled as 64bit or 32bit at compile time in C?
Compiler: GCC
Operating systems that i need to do the checks on: Unix/Linux
Also how could i check when running my program if the OS is capable of 64bit?
|
Since you tagged this "gcc", try
```
#if __x86_64__
/* 64-bit */
#endif
```
|
I want to usePMD 4.2.5to find duplicates in my C code. I use the example commandline from their documentation:
```
java net.sourceforge.pmd.cpd.CPD --minimum-tokens 100 --files C:\src --language cpp
```
this gives me the error:
```
Can't find the custom format --language: java.lang.ClassNotFoundException
```
I tried a lot of different other things too, none worked. The GUI version of the PMD works nicely.
What commandline do i have to use to get PMD to detect duplicate code?
|
It seems it wants to load a class to do the language-specific parsing; make sure your CLASSPATH is set up properly.
|
I need to edit the header information of several PDF files.
What I'd like to achieve is to remove all header data before%PDF-X.Y.Z.
What I came up with as a possible solution was to open the PDF in binary mode, read each character until%PDF-X.Y.Zis found.
Then continue reading the rest of the stream and save it to a new file. I thought this way I will end up with an exact binary copy of the PDF, just with different header information.
What's the easiest/best way to do this in C?
Are there any libraries available that could help me do this?
I'm also interested in hearing different approaches to solve this problem.
Thanks.
|
Actually you can trow away all information before%PDFtag, BUT you make xref table at the end of file invalid. This table contains offset references to PDF objects.
Easiest way was: remove the part before%PDFand count, how much you trow away, reduce values in xref according.
|
I have 2 processes talking to each other Sender and Receiver via socket.I would like to catch signal Control-C and instead of exiting - display some output.Sender and Receiver are working fine,so I added signal(SIGINT,handler) to Sender's body. handler() just outputs some text.So when I run them and hit Cnt-C - signal gets caught and handler outputs the text but exits the Sender process.Sender has a loop that listens for user input unless Cnt-D - so why handler is making Sender exit?
|
If you are not re-registering the signal inside the handler, then it will revert to the default value, and exit once a signal has been sent the second time. For more detailed explanation look at my posthere.
|
I want to use gdb for looking into the various details of the fork() system call. To do this, I used one breakpoint at the fork() and from there onwards i am using step command but this way it is not working fine.
Can somebody explain me how to use gdb to look into every single step occuring during fork() system call?
|
Maybe you meant that you want to follow the child process instead of the parent once the fork is called? In that case:
If you want to follow the child
process instead of the parent process,
use the command set follow-fork-mode.set follow-fork-modemodeSet the debugger response to a program call of fork or vfork. A call
to fork or vfork creates a new
process. The mode argument can be:parent: The original process is debugged after a fork. The child
process runs unimpeded. This is the
default.child: The new process is debugged after a fork. The parent process runs
unimpeded.
|
C Programming:
What happens when a thread tries to acquire a mutex lock, and fails to get it?
Does it go to sleep?
Will the thread be woken up when pthread_mutex_unlock(&mutex); is called?
Then try to obtain the lock again?
|
From theman page:
Thepthread_mutex_lock()function locksmutex. If the mutex is already locked, the calling thread will block until the mutex becomes available.
So yes - your thread is blocked until the lock is available and it can obtain it.
|
From what I know an integer is in the range of 32,768 to 32,767.
A long integer is in the range of 2,147,483,648 to 2,147,483,647.
I doubledchecked wikipedeia to make sure.
The problem now:
```
int a=2147483647;
printf("a: %d\n", a);
```
Why does this work? If I add 1 to 2147483647 then it prints garbage, something to be expected if the variable is a long integer. But why does it allow me to assign a long integer number to an integer in the first place?
|
From what I know an integer is in the range of 32,768 to 32,767.
This is incorrect. The range ofintis at least -32,767 to 32,767; it might have greater range and on most 32-bit and 64-bit platforms it does.
You can find out the range of theinttype on your platform by checking theINT_MAXandINT_MINmacros defined in<limits.h>.
|
How would you compare strings when the characters(and)should come after the alphanumeric characters. Do I have to write a function or is there any library function available?
Thank you for your answers!
|
You can usestd::lexicographical_comparewith a custom predicate. That predicate should take 2 chars, and return false if the first should come before the second.
|
In a previousquestion, I learned how to indent macros as regular C code on emacs. I just need this because of#pragma ompdirectives from OpenMP, but I'd like to maintain all other kind of macros, like#ifand#endif, indented as the default.
```
(c-set-offset (quote cpp-macro) 0 nil)
```
The rule above treats all macros as the same. My question is: Is there a way to specialize this rule?
|
If you look atM-x describe-variable c-offsets-alist, which defines a list of variables that represent the syntactic constructs of the various programming languages, you'd only seecpp-macroandcpp-macro-contwhich represent macros and continuing macros respectively. The list does not tell between#pragmaand say,#if.
So, there is no direct way that Emacs provides to tell#pragmafrom other directives.
|
I am trying to connect to unix domain socket created by another process.
here is what i am doing. the file is exists on the file system when I running it.
```
socketFd = socket(AF_UNIX, SOCK_STREAM, 0);
if (socketFd < 0) {
socketFd = -1;
return -1;
}
bzero(&address, sizeof(struct sockaddr_un));
address.sun_family = AF_UNIX;
size_t address_length = sizeof(address.sun_family) +
sprintf(address.sun_path, "/tmp/%s", COMMON_SOCKET);
connect(socketFd, (struct sockaddr *)&address, address_length);
```
i got error and errno is ENOENT. but doing ls on /tmp show me the file is there.
what do i do wrong ?
|
You're confused aboutaddress_length. It should simply be:
```
size_t address_length = sizeof(address);
```
or really just:
```
connect(socketFd, (struct sockaddr *)&address, sizeof(address));
```
|
I am not clear with following code
```
struct nsproxy init_nsproxy = INIT_NSPROXY(init_nsproxy);
```
this can be seen herehttp://lxr.free-electrons.com/source/kernel/nsproxy.c?v=2.6.28#L27
I am not able to understand the use of macro INIT_NSPROXY which is herehttp://lxr.free-electrons.com/source/include/linux/init_task.h?v=2.6.28#L53
the macro is defined to use INIT_NSPROXY(nsproxy) but when the above snippet is initializing then it is using INIT_NSPROXY(init_nsproxy) how is that possible?
|
```
#define INIT_NSPROXY(nsproxy) // etc.
```
In this macro definition,nsproxyis the name of the parameter to the macro.
In the macro replacement list (everything on the line after the#define INIT_NSPROXY(nsproxy)part), anywhere that thensproxytoken appears, it is replaced by whatever argument is passed.
In this case, the argumentinit_nsproxyis being passed.
|
Why doesstruct sockaddrcontain an address family field? Isn't the address family already fixed with the call tosocket()?
|
sockaddris used in more places than justconnectandbind, including places where you don't have some external knowledge of the address family involved -getaddrinfobeing one.
Additionally, whilst I don't believe the following equates to practice anywhere, I can see it having been in the eye of whoever designed this stuff originally: the call tosocket()defines the protocol family.sockaddrcontains the address family. In practice, I believe these are always the same, but you could theoretically have a protocol capable of supporting two different address types.
EDIT: There's another way that the parameter is useful. If you're using datagram (UDP) sockets and you have a socket in a "connected" state with a default destination address, you canclear out that addressby callingconnect()with asockaddrwithsa_familyset toAF_UNSPEC.
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed7 years ago.Improve this question
Can you tell me where i can see a source of examples GTK+ projects (non gtkmm). It is desirable that be used Glade for design UI. I want to see how to organize program and get experience.
|
You've got plenty of projects in GTK+ in many languages on theGNOME development servers.
|
I want to have a static function which I declare in my .c file before defining it:
```
//file a.c version 1
static int foo();
...
static int foo()
{
...
}
```
However, it seems that I can leave thestatickeyword out of the function definition and I get no compiler warnings... e.g.
```
//file a.c version 2
static int foo();
...
int foo()
{
...
}
```
Am I correct in assuming these two forms are exactly the same?If so, why is this discrepancy allowed and which form should I use?
|
Yes 7.1.1/6
A name declared in a namespace scope without astorage-class-specifierhas external linkage unless it has internal linkage because of a previous declaration and provided it is not declaredconst.
See also the examples of 7.1.1/7
|
the cURL example given here
http://curl.haxx.se/libcurl/c/getinmemory.html
shows how to get a url to memory. i would like to change the above code to use in c++ without much change. I would like to replace the malloc and realloc with something else. Is there a way to get the above code to work by using an STL like list or vector of strings to save the url to memory?
|
as nick has pointed out, luckyspin.org/?p=28 gave me the answer.
```
static int writer(char *data, size_t size, size_t nmemb,
std::string *buffer)
{
int result = 0;
if (buffer != NULL){
buffer->append(data, size * nmemb);
result = size * nmemb;
}
return result;
}
```
|
I've been reading through the DES standard and part of the standard mentioned the bit parity & weak keys. So I've been wondering about the merits of weak keys and their side affects. Some example of weakly formed keys were represented in Hexadecimal format. So part of my assessment relating to weak keys that the repetition of the same 8bit/4bit/2bit groupings throughout a key are classifiable as weak keys! Are my conclusions correct?
|
Yes. For example classic weak key is0x0101010101010101. Problem with the selected permutations.Here is the detailed explanation.
|
Ireallywant to put more in the body to explain the question… but the title really covers it all. As far as I can suss,librtis more “official” (it’s a standard part oflibc?), but I also remember seeing that Node.js useslibeio. Which should I spend more time looking into? What about portability? How different are their APIs?
(I’d appreciate it if somebody with ≥1,500 rep could add the tags “libeio” and “librt” to this question, as I cannot.)
|
libeio wraps standard calls in threads, and handles a large swath of the common system calls.
librt only has a few calls -- read and write, but not, for example, stat.
|
```
#define STR1 "s"
#define STR2 "1"
#define STR3 STR1 ## STR2
```
Is it possible to concatenateSTR1andSTR2, to"s1"?
You can do this by passing args to another Macro function. But is there a direct way?
|
If they're both strings you can just do:
```
#define STR3 STR1 STR2
```
This then expands to:
```
#define STR3 "s" "1"
```
and in the C language, separating two strings with space as in"s" "1"is exactly equivalent to having a single string"s1".
|
Size of the integer depends on what?
Is the size of an int variable in C dependent on the machine or the compiler?
|
It's implementation-dependent. The C standard only requires that:
charhas at least 8 bitsshorthas at least 16 bitsinthas at least 16 bitslonghas at least 32 bitslong longhas at least 64 bits (added in 1999)sizeof(char) ≤ sizeof(short) ≤ sizeof(int) ≤ sizeof(long) ≤ sizeof(long long)
In the 16/32-bit days, thede factostandard was:
intwas the "native" integer sizethe other types were the minimum size allowed
However, 64-bit systems generally didnotmakeint64 bits, which would have created the awkward situation of having three 64-bit types and no 32-bit type.Somecompilers expandedlongto 64 bits.
|
I need to multiply two polynomials each having small integral coefficients. I need a fast FFT routine in C/C++ which can convolve them. I have seen several libraries but they seem to be too large spread over multiple files. What is important is I need code which is not too long and can be very easily used and compiled in a single.c/.cppfile.
FFT should be optimized for real inputs at least if not small integers.Radix 4 implementation if available would be fine too.Compiling it should take no special compilation flags as compilation of program has to be done in external environment which I can't control.
One that very well matches my needs ishere. But I need something twice as fast.
|
For a straightforward and easy to use FFT implementation tryKissFFT. If you need absolute maximum performance though, and don't mind a little complexity, then it has to beFFTW.
|
Should I write OpenGL program by using C or C++? Really confused.
|
You can use either. The OpenGL API is in C and C++ is backward compatible with C. Just choose your favourite language.
|
What is the difference between the int typesint8_t,int_least8_tandint_fast8_t?
|
The difference is defined in the sections of the C99 standard that Carl Norum quoted. But it may be useful to have an example.
Suppose you have a C compiler for a 36-bit system, withchar= 9 bits,short= 18 bits,int= 36 bits, andlong= 72 bits. Then
int8_tdoes not exist, because there is no way to satisfy the constraint of havingexactly8 value bits with no padding.int_least8_tis a typedef ofchar. NOT ofshortorint, because the standard requires thesmallesttype with at least 8 bits.int_fast8_tcan be anything. It's likely to be a typedef ofintif the "native" size is considered to be "fast".
|
i'm developing a php extension (not my first one), but today i stumble
upon a problem i never had : when i run phpize, i get this output :
```
error: possibly undefined macro: LT_SHARED_LIBADD
```
My config.m4 is pretty straightforward, i tried phpize on an other
extension without any issue, i copy pasted the config.m4 from another
extension and just changed the names and still get the problem.
Here is the config.m4 :
```
PHP_ARG_ENABLE(vault, whether to enable Vault support,
[ --enable-vault Enable Vault support])
if test "$PHP_VAULT" = "yes"; then
AC_DEFINE(HAVE_VAULT, 1, [Whether you have Vault])
PHP_NEW_EXTENSION(vault, vault.c, $ext_shared)
fi
```
Anybody ever had that issue? Google didn't find anything on this...
|
Turns out, phpize didn't like the name "vault", changed it, and it works. Serious WTF moment ಠ_ಠ
|
how can i convert a integer with radix 10 to a binary string with C without having the itoa function?
|
You can print a '0' if the number is even or '1' if it is even, then divide by 2 and recurse. Only the other way around ... or something like that.
Example with 13
```
13 is odd so print 1 and divide by 2 giving 6
6 is even so print 0 and divide by 2 giving 3
3 is odd so print 1 and divide by 2 giving 1
1 is odd so print 1 and divide by 2 giving 0
0 reached so stop and read the printing backwards
from this ^^^ column
```
13 is 1101 in binary
|
I am creating a simple video editing application using Java, JNI, C, and FFmpeg. The UI is being designed in Java and I am talking with FFmpeg from a C file using JNI. Does anyone have any suggestions as to the best way I should go about saving part of a video file using FFmpeg? I am allowing the users to choose parts of the video to save and what I am thinking as of right now is to basically loop through all of the packets and decode each frame (if need to encode to a different format) then save the frame to a file. All the while seeking to different parts of the video based on the users start and stop sections of their crops. If this doesn't make sense I would be glad to clear it up. Any ideas are much appreciated as I am just looking to create the most efficient and correct way to go about doing this. Thanks!
|
Use xuggler? It will do all for you without you having to figure out the jni bindings.
|
I'm patching an OTP module (yubico_pam) and I'm trying to access thecontrol-flagselected by the administrator (e.g.required, sufficient, etc).
Any idea? Is this feasible at all (without parsing the file)?
|
There's no way to query this information within the API. We have to avoid the need of knowing this value or specifically instruct the user on what control-flag he should use.
|
I study C and I noticed that I can't find the implementation file for some header files like, for example,stdio.hwhich is a library which contains a lot of input/output functions, likeprintf. Where can I find its implementation?
|
Download one of these:
glibcuclibcdietlibcBSD libc
Or, even better, download several of these and compare their implementations. Of course, these are likely doing a lot of things different compared toyourparticular standard library implementation, but would still be quite interesting for e.g. non-platform-specific functionality such as sprintf.
|
Each side is 60 degrees. and the top and bottom sides are horizontal
I thinkwidth = (cos(60) * sideLength * 2) + sideLength = sideLength * 2
This seems a bit off
|
width should be2*sideLength(sideLength = cos(60) * sideLength * 2)
height will besin(60) * sideLength * 2 = sqrt(3)*sideLength
|
This question already has answers here:The most efficient way to implement an integer based power function pow(int, int)(20 answers)Closed5 years ago.
I implemented this functionpower()which takes two argumentsaandband computes ab.
```
typedef long long int LL;
LL power(int a,int b)
{
int i = 1;
LL pow = 1;
for( ; i <= b ; ++i )
pow *= a;
return pow;
}
```
Given : abfalls in the range oflong long int.Problem : How to reduce the time complexity of my algorithm?
|
Exponentiation by Squaring.
A non-recursive implementation
```
LL power(int a, int b)
{
LL pow = 1;
while ( b )
{
if ( b & 1 )
{
pow = pow * a;
--b;
}
a = a*a;
b = b/2;
}
return pow;
}
```
This algorithm requireslog2bsquarings and at mostlog2bmultiplications.
The running time isO(log b)
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:Is There A Built-In Way to Split Strings In C++?
i have one string variable which contains:
string var = "this_is.that_alos" how i can separate only "that_alos" from it.
i.e. i need only second part after "that_alos"
|
```
std::string var = "this_is.that_alos";
std::string part = var.substr(var.find_first_of('.'));
```
If you want to exclude the'.', just add 1:
```
std::string part = var.substr(var.find_first_of('.') + 1);
```
|
This is actually a SPOJ problem:WAYS
Now this is a very easy task what we need to do is to compute theCentral binomial coefficients.
However the problem setter includes a very notorious source limit of 120 bytes, so my question is how to get past that source code limit in the languages that are allowed?
|
Assuming, thatC(2n,n) = (2n)!/(n!)^2 = (2n(2n-1)/n^2) * C(2(n-1),n-1) = ((4n-2)/n)*C(2(n-1),n-1)here is function, which calculates central binomial:
```
int f(int n)
{
return n==1? 2 : f(n-1)*(4*n-2)/n;
}
```
Edit: Here is probably shortest code:
```
int f(int n){return n<2?2:f(n-1)*(4*n-2)/n;}
```
It is only 44 characters.
|
I have the following C code:
```
person->title
```
The title is a three byte char array. All I want to do is print those three bytes. I can't use the string formatter with printf because there is no null byte.
How can I print this out without having to copy it or add a null byte to it?
Thanks in advance!
UPDATE
Turns out it's not an array, just three adjacent bytes. If I try to compile with the code suggested:
person->title[0]
It fails with the error:
```
test.c:46: error: subscripted value is neither array nor pointer.
```
|
```
printf("%c%c%c",person->title[0],person->title[1],person->title[2]);
```
|
I need to enumarate all the file in a dir and then navigate to the subdir and do the same.
Ideally the algorithm should work in the same way on linux macos [windows(obsolete) no more].
UPDATE: I'm now aware of VFS but I'm puzzled to use VFS for enumerate dir. Any suggestion ? Should I open a dir as file ?
|
POSIX.1-2001 specifiesopendir,readdir, andclosedir,seekdir,rewinddir, andtelldir. Your platform likely has man pages describing how to use them.
These are reportedly not supported directly by MS libraries, instead apparently preferring to useFindFirstandFindNextover there, but there's supposedly several emulation libraries that provide the above; you'll have to sort that part on your own, as I'm not very familiar with Win32.
|
How can I get UNIX time in decimals in C, like Python does that?
What I have in C usinghttp://bytes.com/topic/c/answers/221083-how-show-unix-time-c
```
me@laptop$ ./time
1299556464
```
What I want and it works in Python:
```
>>> time.time()
1299556249.3973091
```
|
Everything's open source, it's easy to find out what Python's doing.
FromPython/Modules/timemodule.c,
```
static double
floattime(void)
{
/* There are three ways to get the time:
(1) gettimeofday() -- resolution in microseconds
(2) ftime() -- resolution in milliseconds
(3) time() -- resolution in seconds
```
There is also the POSIX functionclock_gettimewhich has resolution in nanoseconds.
|
I'm using Eclipse CDT for a C project.
I found out most of the frameworks require installation to use.
I need one framework that doesn't require installation and just need to include the
.h files or/and .c files so that I can use the framework anywhere.
The MinUnit is very cool but it's tool simple. I can use the MinUnit If there's a plugin like Junit to generate the test function stubs for me.
Is there any Eclipse CDT plugin to generate test function stubs like Junit did?
Thank you!
|
What about CUnit? When I used it - I just added the files as a sub-project to my development tree.
|
I am writing a small application in C and want to clear the terminal/dos window of text.
So far I have:
```
if (system("cls"))
system("clear");
```
Which seems to work fine on just about everything except Mac, which gives me the error:
sh: cls: command not found TERM
environment variable not set.
Whats weird, is thatclearfrom the terminal works, but notsystem(clear);and I am not sure why.
Does anyone know how I can stop this, or modify my code to clear the screen on a Mac terminal which will work on other ANSI C compliant compilers, without, obviously, writing a bunch of '/n's to the console?
|
It turns out this is a problem with compiling and running inside XCode. When compiled and run outside XCode, the code works as expected. Doh!
|
I try to send linked list between child processes that comes from same parent. Child1 needs to find the first prime number in the list and delete it and its multiples then send to Child2. Child2 does same and it sends to Child3 and ChildN does same and send to Child1. However, I try to send address data between instead of all the numbers but is it a proper way because maybe I force my child process to enter another's address space. So what is the best way you think of or any other way instead of sending address?
|
You can also use System V shared memory (look at functions likeshmat) ormmapto have memory shared between the processes. Boost.Interprocess has a C++ wrapper around those calls such that you can create a linked list directly in shared memory without copying.
|
I'm trying to figure out if this could somehow be overflowed:
```
void print_address(char *p)
{
arp_ hw;
int i;
hw.length = (size) *(p + _OFFSET1); //189 + 4 = 193
memcpy(hw.addr, packet + _OFFSET2, hw.length);
return;
}
```
where packet is an input read from a .txt file?
|
Yes, it can be overflowed; if the value at offset 4 in the packet is greater than 128, you will overflow theaddrfield inhwaddr.
|
I am creating a simple video editing application using Java, JNI, C, and FFmpeg. The UI is being designed in Java and I am talking with FFmpeg from a C file using JNI. Does anyone have any suggestions as to the best way I should go about saving part of a video file using FFmpeg? I am allowing the users to choose parts of the video to save and what I am thinking as of right now is to basically loop through all of the packets and decode each frame (if need to encode to a different format) then save the frame to a file. All the while seeking to different parts of the video based on the users start and stop sections of their crops. If this doesn't make sense I would be glad to clear it up. Any ideas are much appreciated as I am just looking to create the most efficient and correct way to go about doing this. Thanks!
|
Use xuggler? It will do all for you without you having to figure out the jni bindings.
|
I'm patching an OTP module (yubico_pam) and I'm trying to access thecontrol-flagselected by the administrator (e.g.required, sufficient, etc).
Any idea? Is this feasible at all (without parsing the file)?
|
There's no way to query this information within the API. We have to avoid the need of knowing this value or specifically instruct the user on what control-flag he should use.
|
I study C and I noticed that I can't find the implementation file for some header files like, for example,stdio.hwhich is a library which contains a lot of input/output functions, likeprintf. Where can I find its implementation?
|
Download one of these:
glibcuclibcdietlibcBSD libc
Or, even better, download several of these and compare their implementations. Of course, these are likely doing a lot of things different compared toyourparticular standard library implementation, but would still be quite interesting for e.g. non-platform-specific functionality such as sprintf.
|
Each side is 60 degrees. and the top and bottom sides are horizontal
I thinkwidth = (cos(60) * sideLength * 2) + sideLength = sideLength * 2
This seems a bit off
|
width should be2*sideLength(sideLength = cos(60) * sideLength * 2)
height will besin(60) * sideLength * 2 = sqrt(3)*sideLength
|
This question already has answers here:The most efficient way to implement an integer based power function pow(int, int)(20 answers)Closed5 years ago.
I implemented this functionpower()which takes two argumentsaandband computes ab.
```
typedef long long int LL;
LL power(int a,int b)
{
int i = 1;
LL pow = 1;
for( ; i <= b ; ++i )
pow *= a;
return pow;
}
```
Given : abfalls in the range oflong long int.Problem : How to reduce the time complexity of my algorithm?
|
Exponentiation by Squaring.
A non-recursive implementation
```
LL power(int a, int b)
{
LL pow = 1;
while ( b )
{
if ( b & 1 )
{
pow = pow * a;
--b;
}
a = a*a;
b = b/2;
}
return pow;
}
```
This algorithm requireslog2bsquarings and at mostlog2bmultiplications.
The running time isO(log b)
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:Is There A Built-In Way to Split Strings In C++?
i have one string variable which contains:
string var = "this_is.that_alos" how i can separate only "that_alos" from it.
i.e. i need only second part after "that_alos"
|
```
std::string var = "this_is.that_alos";
std::string part = var.substr(var.find_first_of('.'));
```
If you want to exclude the'.', just add 1:
```
std::string part = var.substr(var.find_first_of('.') + 1);
```
|
This is actually a SPOJ problem:WAYS
Now this is a very easy task what we need to do is to compute theCentral binomial coefficients.
However the problem setter includes a very notorious source limit of 120 bytes, so my question is how to get past that source code limit in the languages that are allowed?
|
Assuming, thatC(2n,n) = (2n)!/(n!)^2 = (2n(2n-1)/n^2) * C(2(n-1),n-1) = ((4n-2)/n)*C(2(n-1),n-1)here is function, which calculates central binomial:
```
int f(int n)
{
return n==1? 2 : f(n-1)*(4*n-2)/n;
}
```
Edit: Here is probably shortest code:
```
int f(int n){return n<2?2:f(n-1)*(4*n-2)/n;}
```
It is only 44 characters.
|
I have the following C code:
```
person->title
```
The title is a three byte char array. All I want to do is print those three bytes. I can't use the string formatter with printf because there is no null byte.
How can I print this out without having to copy it or add a null byte to it?
Thanks in advance!
UPDATE
Turns out it's not an array, just three adjacent bytes. If I try to compile with the code suggested:
person->title[0]
It fails with the error:
```
test.c:46: error: subscripted value is neither array nor pointer.
```
|
```
printf("%c%c%c",person->title[0],person->title[1],person->title[2]);
```
|
I need to enumarate all the file in a dir and then navigate to the subdir and do the same.
Ideally the algorithm should work in the same way on linux macos [windows(obsolete) no more].
UPDATE: I'm now aware of VFS but I'm puzzled to use VFS for enumerate dir. Any suggestion ? Should I open a dir as file ?
|
POSIX.1-2001 specifiesopendir,readdir, andclosedir,seekdir,rewinddir, andtelldir. Your platform likely has man pages describing how to use them.
These are reportedly not supported directly by MS libraries, instead apparently preferring to useFindFirstandFindNextover there, but there's supposedly several emulation libraries that provide the above; you'll have to sort that part on your own, as I'm not very familiar with Win32.
|
How can I get UNIX time in decimals in C, like Python does that?
What I have in C usinghttp://bytes.com/topic/c/answers/221083-how-show-unix-time-c
```
me@laptop$ ./time
1299556464
```
What I want and it works in Python:
```
>>> time.time()
1299556249.3973091
```
|
Everything's open source, it's easy to find out what Python's doing.
FromPython/Modules/timemodule.c,
```
static double
floattime(void)
{
/* There are three ways to get the time:
(1) gettimeofday() -- resolution in microseconds
(2) ftime() -- resolution in milliseconds
(3) time() -- resolution in seconds
```
There is also the POSIX functionclock_gettimewhich has resolution in nanoseconds.
|
I'm using Eclipse CDT for a C project.
I found out most of the frameworks require installation to use.
I need one framework that doesn't require installation and just need to include the
.h files or/and .c files so that I can use the framework anywhere.
The MinUnit is very cool but it's tool simple. I can use the MinUnit If there's a plugin like Junit to generate the test function stubs for me.
Is there any Eclipse CDT plugin to generate test function stubs like Junit did?
Thank you!
|
What about CUnit? When I used it - I just added the files as a sub-project to my development tree.
|
I am writing a small application in C and want to clear the terminal/dos window of text.
So far I have:
```
if (system("cls"))
system("clear");
```
Which seems to work fine on just about everything except Mac, which gives me the error:
sh: cls: command not found TERM
environment variable not set.
Whats weird, is thatclearfrom the terminal works, but notsystem(clear);and I am not sure why.
Does anyone know how I can stop this, or modify my code to clear the screen on a Mac terminal which will work on other ANSI C compliant compilers, without, obviously, writing a bunch of '/n's to the console?
|
It turns out this is a problem with compiling and running inside XCode. When compiled and run outside XCode, the code works as expected. Doh!
|
I try to send linked list between child processes that comes from same parent. Child1 needs to find the first prime number in the list and delete it and its multiples then send to Child2. Child2 does same and it sends to Child3 and ChildN does same and send to Child1. However, I try to send address data between instead of all the numbers but is it a proper way because maybe I force my child process to enter another's address space. So what is the best way you think of or any other way instead of sending address?
|
You can also use System V shared memory (look at functions likeshmat) ormmapto have memory shared between the processes. Boost.Interprocess has a C++ wrapper around those calls such that you can create a linked list directly in shared memory without copying.
|
I.E., you enter the number 5, and the character A and the output would yield F. I have no idea how to even start to go about this, any give me a push in the right direction?
|
Individual characters are represented by numbers according to theASCII code(usually). In C, if you add a number to a character, you're shifting the character down. Try:
```
char c = 'A';
int n = 5;
printf("%c\n", c + n);
```
|
What is a simple translation in code for 'textscan' from matlab into C or C++?
I am using Ubuntu and I am trying to translate a Matlab code into C++.
Thank you very much.
|
First, the answer is not the same if you're using C or if you're using C++. These are different programming languages.
Matlab is a much higher-level language than C and C++. In Matlabtextscanreads from filesorstrings. C and C++ have different mechanisms for that.
To read from a file :
In C, you should use theFILEobject and its associated functions (fopen, fgets ...) from the header file :stdio.h.
In C++, you should usestd::ifstreamfrom the<fstream>header file. For formatted input use the>>operator.
To read from a string :
In C, you might want to look at the functions in thestring.hheader.
In C++, the better way is to use thestd::istringstreamclass from thesstreamheader file.
|
I have been using something like this:
```
int main(int argc, char *argv[])
{
#ifdef DEBUG
printf("RUNNING DEBUG BUILD");
#else
printf("Running... this is a release build.");
#endif
...
```
However this requires me to compile with -DDEBUG for the debug build. Does GCC give me some way for me to determine when I am compiling with debug symbols (-g flag) such as defining its own preprocessor macro that I can check for?
|
Answer is no. Usually these macros (DEBUG, NDEBUG, _DEBUG) are set by the IDE/make system depending on which configuration (debug/release) you have active. I think these answers can be of help:
C #define macro for debug printing
Where does the -DNDEBUG normally come from?
_DEBUG vs NDEBUG
|
I have a very basic question. I would like to know if here is a built-in function in Objective-C or C to help me find if a specific number it's in a certain range. I know that this is probably easy question but still I didn't found an answer. On short terms, would like to avoid using multiple "if"s and "else"s for this test.
|
```
NSLocationInRange(c, NSMakeRange(a, (b - a)))
```
This returns a BOOL if c lies within a and b. However a,b and c must be unsigned int. And this is really not very good looking. So I guess it is far better to compare myself.
```
c >= a && c <= b
```
|
How does one shrink a file in C? For example, if I open a 2mb file, do some work and decide only 1mb of the file should still exist, how is this accomplished? I know how to use write( fd,....) to write to a file, but what if I want to carve out certain parts in the middle of a file or truncate it?
|
You're likely looking fortruncate()ftruncate()or on windows,SetEndOfFile(). There's no way to "cut" out a piece of the file, you will need to rewrite it from front and then truncate it.
|
I'm working on a C program that crops .ppm files from a starting point pixel (x,y) (top left corner of cropped image) to an end point pixel (x+w,x+h)(bottom left corner of cropped image).
The data in .ppm files is of the following format:
r g b r g b r g b r g b r g b r g br g b r g b r g b r g b r g b r g br g b r g b r g b r g b r g b r g br g b r g b r g b r g b r g b r g b
Is there a simple way, wich avoids the use of 2 dimensional arrays, to do this using scanf()?
|
One easy way would be to simply keep track of your pixel coordinate as you read the file in. If you're currently in the crop rectangle, store the pixel; otherwise, skip it.
If you want to get more fancy: figure out the byte offset for the start of each row, seek to it, then read in the whole row.
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed8 years ago.Improve this question
I am trying to make a BitTorrent client in C and I need a library. What is a good, widely-used open-source BitTorrent library for C? I've foundlibbtbut the latest version was more than one and a half year ago. I have also triedGitHubbut there was no C library.
Thanks in advance.
|
Look atlibtorrent-rasterbar. It's used by the deluge torrent client. I'm not sure if it's the same libtorrent as in datenwolf's answer.
|
Okay, I'd like to write a simple C app for Linux (say Ubuntu with Gnome) that would do the following:
Open a WindowDraw something in that window using a main loop, e.g. the current loop number. I don't want to use controls, but to draw directly on the window surfaceClose the window & the app
I can do that in Windows, but I've no idea how I could do that in Linux.
Thanks!
|
Unless you want a full-blown GUI (in which case I'd recommendQtorGTK), thenSDLis a very popular and extremely simple free cross-platform library that gives you a drawing surface and some simple IO facilities. It's natively C, but has bindings to a large number of other languages.
|
Here is a bit of c code i have,i dont know what is the usage of this specifier !%2!s!%3!s!\ means ? this is the code shown below
```
dev.FormatMessage( _T(!%2!s!%3!s!\\"), level,
value, simplify() );
```
|
It is a template that is passed to theFormatMessagefunction; the output from this function will substitute the strings pointed to by thelevelandvaluevariables and the return value from thesimplifyfunction at the places between the percent sign and the second exclamation mark following it.
So, the output will be two backslash characters (the C compiler expects literal backslashes to be escaped, so it will only be two of them in the compiled program here), followed by the three substitutions, followed by a single backslash.
|
Um, I'm a bit new to C so I'm wondering as to why would it gives me the following error messages when compiling this lines:
```
void (ESCALLBACK *drawFunc) ( void* );
void (ESCALLBACK *keyFunc) ( void*, unsigned char, int, int );
```
For the first line it gives me:
error: expected ‘)’ before ‘*’ token
And for the second:
error: expected ‘;’ before ‘void’
It's quite possible that I am not giving you enough info, but for the moment I am wondering why would it printsucherror messages. I mean, they don't look very helpful and I don't think they even come close to the real problem here.
Sorry if I sound silly, I am a Java dev learning C.
Thanks!
|
This probably means that ESCALLBACK isn't defined and it's misparsing the rest of the line (and so giving you an unhelpful error).
Make sure you're including the header that defines ESCALLBACK.
|
```
if ((pos < n) && (key == ptr->keys[pos].value))
{
struct return_values* function(&ptr->keys[pos]);
}
```
while compilation i get the error
```
error: syntax error before '&' token in this line
struct return_values* function(&ptr->keys[pos]);
```
i am passing the address of ptr->keys[pos] to the function
```
struct return_values* function(struct classifier fun_ptr)
```
where struct return_values is the return type what is the error here h
|
You need to assign the result of functon to a variable:
```
struct return_values* values = function(&ptr->keys[pos]);
```
|
I was wondering what the difference in is between calling a method like :
```
int x;
mymethod(x);
```
and
```
mymethod(&x);
```
|
Because C always does call-by-value,if you want the function to be able to change the xinside the function itself, you have to pass the address of x.
```
mymethod(x);
```
will pass x, for example if x is 2, you could as well have writtenmymethod(2)
```
mymethod(&x)
```
will pass the address to x. Now the method canchange the valuestored at that address, so after the function is completed, the actual value of x might have been changed.
Now you can also declare a pointer:
```
int* y; //y is now a pointer to a memory address
y = &x; //y now points to the memory address of x;
*y = 5; will set the "value found at the address y" to 5, thus will set x to 5;
```
|
```
int * const front = mmap(0, sizeof(int), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
int * const back = mmap(0, sizeof(int), PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
int * const buffer = mmap(0, sizeof(int)*50, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
```
I am getting the following error:"error: initializer element is not constant"
How do I remove it?
I know it won't work if I do something likeint a[b];, but why is it happening here?
|
You haven't said, but it's pretty likely that you're working in C, not C++, and that these are variables with static duration? In C, you canonlyintialize a static variable with something that is acompile-timeconstant expression. A function-call is not a compile-time constant expression.
|
So I've been starting DS programming, and I notice that to draw a pixel the color must be a RGB(0, 31, 0). Is there any way to change that to something like RGB(0, 255, 0)?
|
If you have a green-valuegwith a range of 0-255, you can convert it to NintendoDS's 0-31 range by usingg*31/255. If you are asking us if you can actually do something to make your NintendoDS display a range of 0-255 for each channel the answer is no,butyou could use dithering (search-engine it).
|
In 1988, the number of transistors in the Intel 386 SX microprocessor was 275,000. What were the transistor counts of the Pentium II Intel microprocessor in 1997?
If Intel doubles the number of transistors every two years, the new processor would have
```
Pn = 275,000 * 2^n (where n = 9/2 = 4.5)
= 275,000 * 22.63
= 6.2 million transistors
```
So How would be a code for this using C, C++ or java...
|
Indeed. Moore changed his projection in 1975 to doubling the number of transistors everytwoyears.
```
#include <stdio.h>
#include <math.h>
int main () {
double transistors = 275000;
double years = 1997-1988;
printf("%f", transistors*pow(2.0,years/2)); // 6222539.674442
getch();
return 0;
}
```
|
I am getting a segmentation fault in the following code:
```
void print_stack(Node * root) {
while(root != NULL) {
// print the node
root = root->next;
}
}
```
Whereas this works:
```
int print_stack(Node ** root) {
Node * tmp = *root;
while(*root != NULL) {
// print the node
*root = (*root)->next;
}
*root = tmp;
}
```
The question is what am I doing wrong? For both functions I am passing the address of a Node pointer to the head of the list. I am trying to get the first function to work because it seems more ideal (no pointer allocation and no permanent change to root pointer).. thanks.
EDIT:I have posted the code here:http://dpaste.com/477724/
|
You passed the address of a Node pointer while the function takes just a Node pointer.
This:
```
print_stack(&main);
```
should be this:
```
print_stack(main);
```
|
I have the following piece of code:
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int n = 260;
int *p = &n;
char *pp = (char*)p;
*pp = 0;
printf("n = %d\n", n);
system("PAUSE");
return 0;
}
```
The output put of the program isn = 256.
I may understand why it is, but I am not really sure.
Can anyone give me a clear explanation, please?
Thanks a lot.
|
Theint260 (= 256 * 1 + 4) will look like this in memory - note that this depends on theendiannessof the machine - also, this is for a 32-bit (4 byte)int:
```
0x04 0x01 0x00 0x00
```
By using acharpointer, you point to the first byte and change it to0x00, which changes the int to 256 (= 256 * 1 + 0).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.