question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
This question already has answers here:Closed10 years ago.
Possible Duplicate:What does “-1L” mean in C?
What does "0L", "1L" mean in C ?
How is it different from "0" and "1" ?
Is there other literals than "L" with similar function in C ?
|
It's an integer constant that has along inttype instead ofint.
C11, § 6.4.4.1 Integer constants #1long-suffix: one oflL
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:C comma operator
I came across a line of code which I couldn't understand. I remember seeing something similar somewhere.
```
int x,y,z;
x=(y=2,z=2*y,z+4);
```
I know that the value assigned to x is 8. Can someone explain me why?
|
This is equivalent to:
```
y = 2; // y == 2
z = 2 * y; // z == 4
x = z + 4; // x == 8
```
The operands of the comma operator are evaluated from left to right and the result is the value of the right operand.
|
The ssh command line command prompts the user for a password like so:
Password:
In C, when I do:
```
system("ssh name@host");
system("password");
```
the command line will prompt the user and ignore any input coming from my program. It seems to always take input that's typed by the user. Is there a way to redirect... |
Indeed. SSH will open/dev/ttyand read the password directly from that, so there's no way you can pass it any input that way. I know of no way to override that behavior, apart from usinglibssh2, as shiplu said.
|
I thought that the function removes the parameters from the stack after it's done, but a function like printf removes a variable number of parameters from the stack when it's called.
How does it know how many parameters to remove from the stack? Is there a secret argument to specify how many arguments are passed?
Th... |
TheC calling conventionspecifies that is thecallerand not thecalleethe one responsible from popping the parameters from the stack. That's why functions with a variable argument list must becdecl. So,
I thought that the function removes the parameters from the stack after it's done.
That's only true for certain calli... |
What is the meaning of:
```
printf("%c", **++argv);
```
in a C command line program?
|
Print the first character of the first argument passed. i.e.argv[1][0]
argvis a pointer to pointer passed tomain().
**++argv:
First it is incremented (due to pre-increment) to point to the next pointer which isargv[1]and then dereferences that pointer to pointer using which isargv[1][0].
|
I am trying to implement a game using ncurses in C. I have to show the current time (the time must update each second) and my while loop looks like this
```
while(1)
{
clk = time(NULL);
cur_time = localtime(&clk);
mvprintw(0,1,"%d %d %d",cur_time->tm_hour,cur_time->tm_min,cur_time->tm_sec);
int key = ... |
There are a couple of functions you could use:
nodelaytimeout
int nodelay(WINDOW *win, bool bf);
Set bf true to make getch() non-blocking
void timeout(int delay);
Delay is in milliseconds, so if you set it to 1000, the getch will timeout after a second.
In both cases getch will return ERR if there is no input.
|
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
in c anything other than 0 is considered boolean true. so your if can be read like:
if x==0 or true or true or true...
what you probably meant wasif (x==0 || x==7 || x==14 ...)
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:What is a stack overflow error?
It just happens when I declare large arrays with the size of 4096*1024
```
First-chance exception at 0x01382e97 in nsfclient.exe: 0xC00000FD: Stack overflow.
Unhandled exception at 0x01382e97 in nsfclient.e... |
You should explicitly increase the stack size to be able to store bigger arrays on the stack. As far as I remember this is done using the/Foption.
Another option would be to use dynamic arrays(allocated usingmallocornew).
EDIT(thanks to Jefrrey Theobald): you will also have to increase the stack size in the linker, ... |
Is there any reason to prefer linker commands over include directivesifyou don't plan on recompiling the included files separately?
P.S. If it matters, I'm actually concerned with C++ and g++, but I thought gcc would be more recognizable as a generic compiler.
|
Is there any reason to prefer linker commands over include directives
Yes. You'll get into serious trouble if you include implementation (.c) files here and there. Meet the infamous "Multiple definitions of symbol _MyFunc" linker error...
(By the way, it's also considered bad style/practice, in general, only header ... |
Where do i find the definition/body of the printf/scanf & other similar predefined commonly used functions (getch, clrsr ...etc) of "Borland C" ?
|
You cannot.. You can just see the prototype ofprintf/scanfin the header file<stdio.h>
You can find it in the standard library which comes with whatever compiler you are using..
|
I implemented a precondition conjugate gradient method to resolve aAx = Bproblem by usingCUBLASlib andCUDA.
My code works fine when it deals with the40000x40000implicit matrixA.
However, when I increase the size to130000x130000, it givesCUBLAS_STATUS_INTERNAL_ERRORfromcublasDdotmethod.
Does anyone know why this ha... |
I solved the problem. Actually, it is not caused by theCUBLAS API. When I give larger size matrix to the solver, it takes longer time to solve it. However, the time is over the GPU watchdog limit, then the solver is terminated by the watchdog process. So, we bought a new GPU as our dedicated one and solved the problem... |
How can I test if a type is supported by a compiler? Say like uint64_t. Is there a reference somewhere I can use for learning how to test for any given types?
It is surprisingly hard to find this out via search engine. I tried "C test for data type" and many other things.
|
You can check that:
UINT64_MAXmacro is defined after includingstdint.h.
If you are not sure if c99 or higher is supported you can also enclose it in a check to__STDC_VERSION__to be>= 199901L. Note that also that__STDC_VERSION__macro is not present in C89/C90.
From the Standard (emphasis mine):
(C99, 7.18p4) "For e... |
This question already has answers here:Closed10 years ago.
Possible Duplicate:Dereferencing void pointers
I have a function call this way:
```
void foo(void *context) //function prototype
..
..
..
main()
{
.
.
foo(&(ptr->block)); //where ptr->block is of type integer.
.
.
.
void foo(void *context)
{
Here I try ... |
```
if((int *)context ==1)
```
you want this instead:
```
if(*(int *)context ==1)
```
You were casting to a pointer tointbut what you actually want is to actually access theintso you need to dereference the pointer.
|
Okay, i am stuck on how to get console information in c++. I know how to set things like the color with setConsoleTextAttribute, and the title with setConsoleTitle, but i don't know how to get that information in a method and return it. I am doing a jni project and i am stuck on this one part.
|
The two API calls you are looking for are GetConsoleScreenBufferInfo and GetConsoleTitle, documentation here:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683171%28v=vs.85%29.aspxhttp://msdn.microsoft.com/en-us/library/windows/desktop/ms683174%28v=vs.85%29.aspx
|
In C I use"1st line 1\n2nd line"for a newline, but what about VB? I know"1st line" & VbCrLf & "2nd line"but its too verbose, what is the escape char for a newline in VB?
I want to print
```
1st line
2nd line
```
I tried using\nbut it always outputs this no matter how many times I run the compiler
```
1st line\n2nd... |
You should useEnvironment.NewLine. That evaluates to CR+LF on Windows, and LF on Unix systems.
There are no escape sequences for CR or LF characters in VB. And that's why"\n"is treated literally. So,Environment.NewLineis your guy.
|
I thought that the function removes the parameters from the stack after it's done, but a function like printf removes a variable number of parameters from the stack when it's called.
How does it know how many parameters to remove from the stack? Is there a secret argument to specify how many arguments are passed?
Th... |
TheC calling conventionspecifies that is thecallerand not thecalleethe one responsible from popping the parameters from the stack. That's why functions with a variable argument list must becdecl. So,
I thought that the function removes the parameters from the stack after it's done.
That's only true for certain calli... |
What is the meaning of:
```
printf("%c", **++argv);
```
in a C command line program?
|
Print the first character of the first argument passed. i.e.argv[1][0]
argvis a pointer to pointer passed tomain().
**++argv:
First it is incremented (due to pre-increment) to point to the next pointer which isargv[1]and then dereferences that pointer to pointer using which isargv[1][0].
|
I am trying to implement a game using ncurses in C. I have to show the current time (the time must update each second) and my while loop looks like this
```
while(1)
{
clk = time(NULL);
cur_time = localtime(&clk);
mvprintw(0,1,"%d %d %d",cur_time->tm_hour,cur_time->tm_min,cur_time->tm_sec);
int key = ... |
There are a couple of functions you could use:
nodelaytimeout
int nodelay(WINDOW *win, bool bf);
Set bf true to make getch() non-blocking
void timeout(int delay);
Delay is in milliseconds, so if you set it to 1000, the getch will timeout after a second.
In both cases getch will return ERR if there is no input.
|
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
in c anything other than 0 is considered boolean true. so your if can be read like:
if x==0 or true or true or true...
what you probably meant wasif (x==0 || x==7 || x==14 ...)
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:What is a stack overflow error?
It just happens when I declare large arrays with the size of 4096*1024
```
First-chance exception at 0x01382e97 in nsfclient.exe: 0xC00000FD: Stack overflow.
Unhandled exception at 0x01382e97 in nsfclient.e... |
You should explicitly increase the stack size to be able to store bigger arrays on the stack. As far as I remember this is done using the/Foption.
Another option would be to use dynamic arrays(allocated usingmallocornew).
EDIT(thanks to Jefrrey Theobald): you will also have to increase the stack size in the linker, ... |
Is there any reason to prefer linker commands over include directivesifyou don't plan on recompiling the included files separately?
P.S. If it matters, I'm actually concerned with C++ and g++, but I thought gcc would be more recognizable as a generic compiler.
|
Is there any reason to prefer linker commands over include directives
Yes. You'll get into serious trouble if you include implementation (.c) files here and there. Meet the infamous "Multiple definitions of symbol _MyFunc" linker error...
(By the way, it's also considered bad style/practice, in general, only header ... |
Where do i find the definition/body of the printf/scanf & other similar predefined commonly used functions (getch, clrsr ...etc) of "Borland C" ?
|
You cannot.. You can just see the prototype ofprintf/scanfin the header file<stdio.h>
You can find it in the standard library which comes with whatever compiler you are using..
|
I implemented a precondition conjugate gradient method to resolve aAx = Bproblem by usingCUBLASlib andCUDA.
My code works fine when it deals with the40000x40000implicit matrixA.
However, when I increase the size to130000x130000, it givesCUBLAS_STATUS_INTERNAL_ERRORfromcublasDdotmethod.
Does anyone know why this ha... |
I solved the problem. Actually, it is not caused by theCUBLAS API. When I give larger size matrix to the solver, it takes longer time to solve it. However, the time is over the GPU watchdog limit, then the solver is terminated by the watchdog process. So, we bought a new GPU as our dedicated one and solved the problem... |
How can I test if a type is supported by a compiler? Say like uint64_t. Is there a reference somewhere I can use for learning how to test for any given types?
It is surprisingly hard to find this out via search engine. I tried "C test for data type" and many other things.
|
You can check that:
UINT64_MAXmacro is defined after includingstdint.h.
If you are not sure if c99 or higher is supported you can also enclose it in a check to__STDC_VERSION__to be>= 199901L. Note that also that__STDC_VERSION__macro is not present in C89/C90.
From the Standard (emphasis mine):
(C99, 7.18p4) "For e... |
This question already has answers here:Closed10 years ago.
Possible Duplicate:Dereferencing void pointers
I have a function call this way:
```
void foo(void *context) //function prototype
..
..
..
main()
{
.
.
foo(&(ptr->block)); //where ptr->block is of type integer.
.
.
.
void foo(void *context)
{
Here I try ... |
```
if((int *)context ==1)
```
you want this instead:
```
if(*(int *)context ==1)
```
You were casting to a pointer tointbut what you actually want is to actually access theintso you need to dereference the pointer.
|
Okay, i am stuck on how to get console information in c++. I know how to set things like the color with setConsoleTextAttribute, and the title with setConsoleTitle, but i don't know how to get that information in a method and return it. I am doing a jni project and i am stuck on this one part.
|
The two API calls you are looking for are GetConsoleScreenBufferInfo and GetConsoleTitle, documentation here:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683171%28v=vs.85%29.aspxhttp://msdn.microsoft.com/en-us/library/windows/desktop/ms683174%28v=vs.85%29.aspx
|
In C I use"1st line 1\n2nd line"for a newline, but what about VB? I know"1st line" & VbCrLf & "2nd line"but its too verbose, what is the escape char for a newline in VB?
I want to print
```
1st line
2nd line
```
I tried using\nbut it always outputs this no matter how many times I run the compiler
```
1st line\n2nd... |
You should useEnvironment.NewLine. That evaluates to CR+LF on Windows, and LF on Unix systems.
There are no escape sequences for CR or LF characters in VB. And that's why"\n"is treated literally. So,Environment.NewLineis your guy.
|
How would I return from nested GCD dispatch calls?
Let's say I have a method that looks like this:
```
- (void)foo {
dispatch_async(queue, ^{
if (flag) {
// I want out of here
return;
}
dispatch_sync(dispatch_get_main_queue(), ^{
if (flag) {
... |
Yes, your thinking is correct. Each block is a separate function, so return will only return from the current block. If you want to early-exit the dispatch_async'd block if the dispatch_sync'd one does, you'll need another check and return after the dispatch_sync.
|
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
Yourwhileloop should not be comparing against'0'.'0'(ascii) is value 48!
Strings don't end with 48.Strings end with 0.
You should be doing:
```
while(length[string] != 0)
```
(and all the other answers and comments about other problems in your code are also accurate)
|
Suppose I have two different structures, Struct1 and Struct2. They both have different elements in them.
What happens if I compare them like this:
```
if((Struct1) && (Struct2))
{
doSomething();
}
```
I just found some code with this logic and was wondering what was happening.
Thanks!
EDIT:Struct1 and Struct2 a... |
Using a structure in anifis illegal syntax for C - it won't be accepted by a conforming compiler. Put another way: you can't use a structure in a boolean context.
Most likely in your code - if itistrue code -Struct1aren't structures but (possibly) pointers or something else. In that case the if will be taken if both ... |
I am trying to get into kernel module programming. After some research, I am in a bit of confusion. My question is, do I need a kernel source for doing module programming?
Also if yes, do I need to recompile the kernel after I have compiled the modules I have written?
|
Do I need a kernel source for doing module programming ?
You need the kernel header files, normally I use:
$ sudo apt-get install build-essential linux-headers-$(uname -r)
Also if yes, Do I need to recompile the kernel after I have compiled the modules I have written ?
No
|
I would like to simplify the following expression (blockis an integer, either0or1):
```
if (block)
opts = opts & ~O_NONBLOCK;
else
opts = opts | O_NONBLOCK;
```
This is what I've come up with:
```
opts = block ? opts & ~O_NONBLOCK : opts | O_NONBLOCK;
```
I'm sure, however, that there's a much clever way t... |
How about this?
```
opts = (opts & ~O_NONBLOCK) | (!block * O_NONBLOCK);
```
I do prefer the explicitness of your first option over this somewhat cryptic solution, though.
|
I want my function to create an array and allocate memory fornpointers to functions (for example, functions that have no parameters and return int) and to return a pointer to that array.
I tried doing:
```
void* f(int n){
return calloc(int (*arrayName[])(void),n);
}
```
But i'm getting a syntax error. I'm pretty... |
Make your life easier and usetypedefs:
```
typedef int (*fp)();
fp * f(size_t n)
{
return calloc(n, sizeof(fp));
}
```
The hand-rolled declaration:int (*f(size_t n))()
|
I want to initialize an array of size 5 pointers that holds pointers to functions that have no parameters and which returns an int (could be any function that facilitate these requirements).
This is what i tried thus far but i get a syntax error:
```
int (*func)() fparr[5] = int (*func)();
```
What is wrong with t... |
If the function you want to supply as the default contents of the array is calledfunc, then
you better use atypedef,you have to use an array initializer
Consider:
```
typedef int (*IntFunc)(void);
IntFunc fparr[5] = { func, func, func, func, func };
```
Or the less readable way, if you prefer to avoidtypedef:
```... |
first the code compiles and runs with VS2010
but when I compile with cl.exe it gives
```
cannot convert parameter 1 from 'WCHAR [10]' to 'LPCTSTR'
```
the code is
```
char *fileName = "12.txt";
WCHAR ufileName[10];
MultiByteToWideChar(CP_ACP, MB_COMPOSITE, fileName, -1, ufileName, 10);
postFile(ufileName, clientS... |
You're trying to pass aWCHARarray to a function that expects aLPCTSTR.This articleexplains thatLPCTSTRis an array ofTCHARs and thatTCHARvaries in size for unicode and non-unicode builds.
Your code relies onsizeof(TCHAR) == sizeof(WCHAR)so you need unicode support to be enabled.
I'd guess that your build from within ... |
I'm writing a program in c on linux using gcc.
If I'm not using that sleep statement
it will print "thread created" 2,3 or 4 number of times randomly. Can anyone explain me this behavior?
//the following code is just a sample, i know is not really useful to create a thread just to print a string :)
```
void* makeRequ... |
You should join all threads that you create, endingmainas you do exits the whole process.
Alternatively you could end yourmainwithpthread_exit.
|
I know alot of similar questions were asked before but i couldn't find something that would fix this warning i get:
```
MyIntFunctions.c:19:2: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
```
Occurs here:
```
void IntPrint (const void *key)
{
printf("%d", *(int*)key); // ... |
You need to include the appropriate header
```
#include <stdio.h>
```
If you're not sure which header a standard function is defined in, the function'sman pagewill state this.
|
```
do I need to manually do that ?
Does CopyMemory accept shifting the destination ?
the following isn't working
```
```
requestBuffer = VirtualAlloc(NULL, sizeof(fileBuffer) + sizeof(sendRequest) + 2, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
CopyMemory(requestBuffer,sendRequest, sizeof(sendRequest));... |
It sounds likerequestBufferis avoid *. You cannot use pointer arithmetic withvoidpointers. Try casting to(PBYTE)before adding:
```
CopyMemory((PVOID)((PBYTE)requestBuffer+sizeof(requestBuffer)), ...
```
|
I want my function to create an array and allocate memory fornpointers to functions (for example, functions that have no parameters and return int) and to return a pointer to that array.
I tried doing:
```
void* f(int n){
return calloc(int (*arrayName[])(void),n);
}
```
But i'm getting a syntax error. I'm pretty... |
Make your life easier and usetypedefs:
```
typedef int (*fp)();
fp * f(size_t n)
{
return calloc(n, sizeof(fp));
}
```
The hand-rolled declaration:int (*f(size_t n))()
|
I want to initialize an array of size 5 pointers that holds pointers to functions that have no parameters and which returns an int (could be any function that facilitate these requirements).
This is what i tried thus far but i get a syntax error:
```
int (*func)() fparr[5] = int (*func)();
```
What is wrong with t... |
If the function you want to supply as the default contents of the array is calledfunc, then
you better use atypedef,you have to use an array initializer
Consider:
```
typedef int (*IntFunc)(void);
IntFunc fparr[5] = { func, func, func, func, func };
```
Or the less readable way, if you prefer to avoidtypedef:
```... |
first the code compiles and runs with VS2010
but when I compile with cl.exe it gives
```
cannot convert parameter 1 from 'WCHAR [10]' to 'LPCTSTR'
```
the code is
```
char *fileName = "12.txt";
WCHAR ufileName[10];
MultiByteToWideChar(CP_ACP, MB_COMPOSITE, fileName, -1, ufileName, 10);
postFile(ufileName, clientS... |
You're trying to pass aWCHARarray to a function that expects aLPCTSTR.This articleexplains thatLPCTSTRis an array ofTCHARs and thatTCHARvaries in size for unicode and non-unicode builds.
Your code relies onsizeof(TCHAR) == sizeof(WCHAR)so you need unicode support to be enabled.
I'd guess that your build from within ... |
I'm writing a program in c on linux using gcc.
If I'm not using that sleep statement
it will print "thread created" 2,3 or 4 number of times randomly. Can anyone explain me this behavior?
//the following code is just a sample, i know is not really useful to create a thread just to print a string :)
```
void* makeRequ... |
You should join all threads that you create, endingmainas you do exits the whole process.
Alternatively you could end yourmainwithpthread_exit.
|
I know alot of similar questions were asked before but i couldn't find something that would fix this warning i get:
```
MyIntFunctions.c:19:2: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
```
Occurs here:
```
void IntPrint (const void *key)
{
printf("%d", *(int*)key); // ... |
You need to include the appropriate header
```
#include <stdio.h>
```
If you're not sure which header a standard function is defined in, the function'sman pagewill state this.
|
```
do I need to manually do that ?
Does CopyMemory accept shifting the destination ?
the following isn't working
```
```
requestBuffer = VirtualAlloc(NULL, sizeof(fileBuffer) + sizeof(sendRequest) + 2, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
CopyMemory(requestBuffer,sendRequest, sizeof(sendRequest));... |
It sounds likerequestBufferis avoid *. You cannot use pointer arithmetic withvoidpointers. Try casting to(PBYTE)before adding:
```
CopyMemory((PVOID)((PBYTE)requestBuffer+sizeof(requestBuffer)), ...
```
|
Which roles are used when i call a function with pointer argument unless declare the function before? I know that float are promoted to double and that are executed the integral promotion, but what happens at the pointers?
|
Nothing. Default argument promotions don't apply to arguments of pointer type so they are left unchanged in type and value.
|
I used netbeans in Windows 7 as my IDE. And below is my assembly code:
```
/* Atomic exchange (of various sizes) */
inline void *xchg_64(void *ptr, void *x)
{
__asm__ __volatile__("xchgq %0,%1"
:"=r" ((unsigned long long) x)
:"m" (*(volatile long long *)ptr), "0" ((unsigned long lo... |
There is no way to directly exchange the values of two memory locations. Intel just hasn't provided that kind of instructions.
You will have to code it as load-exchange-store using a register as an intermediary.
And in that case you could just as well code it in C...
|
I've been learning to use Flex (the lexical analyser) and I've been compiling with the following command:
gcc -lfl -o test lex.yy.c
and all is well. However, I want to link it with other files, so I compile and link it separately with
gcc -c lex.yy.c
followed by
gcc -lfl -o test lex.yy.o
but gcc tells me that th... |
add-lflat the end instead of beginning.
|
I tried using the following code to read a text from the keyboard and write it into the filetext.dat. The file was created but it was empty.
```
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <io.h>
#include <string.h>
int main()
{
char s[201];
int n,f = open("text.dat", O_RDWR | O_CREAT)... |
write(f, s, strlen(s))Though I'd useread()instead offgets()and used its result instead ofstrlen()
|
I must create a Person and each Person should have a Fridge. Is this the best way of doing it? If so what am I doing wrong? Thanks in advance.
```
typedef struct {
int age;
struct FRIDGE fridge;
} PERSON;
typedef struct {
int number;
} FRIDGE;
FRIDGE fr;
fr.number=1;
PERSON me;
me.name=1;
me.fridge = fr;
```
T... |
struct FRIDGEis something different thanFRIDGE.
You need to either use typeFRIDGEin your other structure.
```
typedef struct {
int age;
FRIDGE fridge;
} PERSON;
```
or define your fridge asstruct FRIDGE
```
struct FRIDGE {
int number;
};
```
Also, the structure may have to be defined before you use it (e.g. ab... |
I want to calculate:
(-15 % 3) which should be 0 but instead i'm getting 1:
When i explicitly do:
```
int IntFcn (const void *key, size_t tableSize)
{
printf("%d\n",(*(int*)key)); // prints -15
printf("%d\n",tableSize); // prints 3
printf("%d\n",(-15) % 3); // prints 0
}
```
I get the right result (0) b... |
In your second case the second operand of modulo is unsigned integer thus the first operand is promoted to unsigned as well before performing the modulo. So the result will be(unsigned)(-15) % 3which is equal (for 32-bitint) to4294967281 % 3 == 1.
|
In the following code, I want to replace the termination condition to: if the ratio of guess square and x is close to 1, while loop should terminate. I tried various expressions, but none run the code properly. any suggestion?
```
# include<stdio.h>
float absolute(float x)
{
if (x < 0)
x = -x;
retu... |
hit the answer: while statement should be like this:
```
while ( absoluteValue((guess * guess) / x - 1.0) >= 0.0001 )
```
|
My program will open a file and print the contents in the terminal. As the file is large, the terminal goes two or more page. I'll have to slide up to the first line of the file to read from the beginning. Is it possible using C program?
```
void hfile()
{
printf("\033[2J");
printf("\033[0;0H");
FILE *ffp;
char c;
f... |
Not via stdlib. You will have to use some third-party library like ncurses.
|
Please have a look at the code, clang is giving me the error "incompatible pointer to integer conversion", why is it happening?
```
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
char* name;
name = malloc (sizeof(char) * 6);
*name = "david";
return 0;
}
```
|
Whatever is happening is happening at this line:
```
*name = "david";
```
The type of*namewould bechar, as you are dereferencing thecharpointed to byname. The type of"david"ischar[6], as it's astring literalof 6 chars (5 + null terminator). An array typedecaysinto a pointer and acharis anintegral type; your assignme... |
I need to prevent an application from being started on a windows machine. The most obvious way (having an infinite loop and using EnumProcesses/OpenProcess/TerminateProcess) implies that the target application/process has already been started and also that it ran for a certain period of time.
Renaming/editing/patchin... |
If you are running Windows 7 or newer (or anything based on it), then you can use the AppLocker feature:
http://technet.microsoft.com/en-us/library/dd723686(v=ws.10).aspx
|
I want to store 5 names without wasting 1byte , so how can allocate memory using malloc
|
That's for all practical purposesimpossible,mallocwill more often than not return blocks of memory bigger than requested.
|
I'd like to create a program that causes a runninggeditprocess to open a.txtfile in a new tab using C. The file would be the argument I supply to the program. However, I'd like to avoid usingsystem()altogether.
I'm on Linux. Is this possible? If so, by what means?
|
You don't needsystem(). You can use fork/execlp
```
if(!fork())
execlp("gedit", "gedit", filename, NULL);
```
The version of gedit that's on my laptop uses a new tab by default if there's a running instance already, but I'm not sure about other versions.
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:Passing two-dimensional array via pointer
```
int table[20][20];
int** table1 = table;
int a;
table[0][0] = 4;
a = table1[0][0];
```
the last line gives me Access violation, and i dont get it ..
thanks in advance!
|
The short answer is that a pointer to a pointer is not the same as an array of arrays.
|
I am trying to use OpenCV in Raspberry Pi (embedded system) so I need the OpenCV C API source code so that I can compile it and use it.
After some search I found that C API was designed in OpenCV 1.x. Now it is supported for backward compatibility only. It is deprecated and may be removed in the future.
OpenCV has C... |
OpenCV C API is part of newer OpenCV releases as well.
However OpenCV internals are C++ in OpenCV 2.0 and later. So you cannot compile newer OpenCV without C++ support.
|
I want to pass a pointer to a variable. Sometimes it would be an integer and sometimes maybe a character. In the example below i pass the pointerptoCreateObjectbut when i try to retrieve the value of the variable the pointer points to i get an awkward result:
```
int i =0;
int *p = malloc(sizeof(int));
*p = i;
Objec... |
This:
```
(int) key
```
is not dereferencing the pointer to access the data it points at, it's re-interpreting the pointer value (the address) itself as the integer.
You need:
```
printf("%d\n", *(int *) key);
```
|
I have the following recurrence formula:
```
f(0) = 0
f(1) = 1
f(n) = n + f(floor(n/2))
```
which can be expressed in code as:
```
int f(int n) {
int s = 0;
for (; n; n >>= 1)
s += n;
return s;
}
```
Is there a closed-form that will allow me to computef(n)in one step?
If not, is there anyt... |
Searching onOEISgives this series:
A005187: a(n) = a([n/2]) + n; also denominators in expansion of
1/sqrt(1-x) are 2^a(n); also 2n - number of 1's in binary expansion of
2n.
So the second parts gives the formula of2*n - bitcount(2*n). You can calculate this with some efficient bitcount implementation, such as gc... |
I'm looking for a very simple implementation of RSA in C. I need to place it in a DSP, so I'd like to use something very thin and straightforward.
Nonetheless, I just found only examples with little numbers (int or long) while I need to implement RSA at least at 1024 bits, so I also have to cope with large numbers.
C... |
TheLibTomCryptand related projects are very clean and understandable.
|
I'd like to useCprogram to find the total number of directives like#include,#define,#ifdef,#typedef, etc. Could you suggest any logic for that? I'm not interested in using any scripting or tools. I want it to be done purely usingCprogram.
|
Storeall the directivesin an array of pointers (or arrays).
Read the C file line by line and check if the first word starts with any of the directives in the list excluding any whitespaces at the beginning.
```
char *directives[]={"#assert", "#define#, ......};
int count[NUM_DIRS]= { 0 };
```
Everytime you find a ... |
I was looking at a basic Box2D program, more specificallythis one.
Everything is fairly simple and makes sense, except for this line:
```
Shape.SetAsBox((32.f/2)/SCALE, (32.f/2)/SCALE); // SCALE = 30
```
Now I know we divide bySCALEto scale 1m->30px but why is 32.f divided by 2? I don't understand why we divide b... |
from themanual:
groundBox.SetAsBox(50.0f, 10.0f);The SetAsBox function takes the half-width and half-height(extents)
|
Can anyone suggest some good references for writing a touchpad driver for linux. Where would I get hardware documentation from. I have read most of the linux device driver books and now I want to take it to the next level.
|
Are you sure there is no current support for your sentelic in linux kernel? Take a look at Documentation/input/sentelic.txt in Linux source code. If it does not give you direct answers, you'll be able to see how to implement something similar instead. Take a look at its sources, too.
Moreover, if you are not really, ... |
lets say I have a file test.c that contains:
```
char buffer1[1024];
int somefunction()
{
char buffer2[1024];
// do stuff
}
```
now I know buffer2 is allocated on the stack on the frame belonging to somefunction calls, but where is buffer1 allocated ?
|
These variables are typically onBSS(variables which don't have explicit initialization in the source code, so they get the value 0 by default) ordata segment(initialized datas). Here,buffer1is uinitialized, so it will probably be allocated on BSS segment, which starts at the end of the data segment.
Frombravegnuwebsi... |
```
int main(void)
{
int i;
int array[5];
for (i = 0; i <= 20; i++)
array[i] = 0;
return 0;
}
```
Why is the above code stuck in an infinite loop?
|
You declare an array with 5 elements but write 21 elements to it. Writing past the end of an array results in undefined behaviour. In you case, you're writing to the loop counteri, resetting it to 0, probably when you assignarray[5].
If you want to fix your program, change the loop to write to the correct number of... |
I read thatstrcpyis for copying a string, andstrdupreturns a pointer to a new string to duplicate the string.
Could you please explain what cases do you prefer to usestrcpyand what cases do you prefer to usestrdup?
|
strcpy(ptr2, ptr1)is equivalent towhile(*ptr2++ = *ptr1++)
where as strdup is equivalent to
```
ptr2 = malloc(strlen(ptr1)+1);
strcpy(ptr2,ptr1);
```
(memcpy versionmight be more efficient)
So if you want the string which you have copied to be used in another function (as it is created in heap section) you can use... |
I have the following recurrence formula:
```
f(0) = 0
f(1) = 1
f(n) = n + f(floor(n/2))
```
which can be expressed in code as:
```
int f(int n) {
int s = 0;
for (; n; n >>= 1)
s += n;
return s;
}
```
Is there a closed-form that will allow me to computef(n)in one step?
If not, is there anyt... |
Searching onOEISgives this series:
A005187: a(n) = a([n/2]) + n; also denominators in expansion of
1/sqrt(1-x) are 2^a(n); also 2n - number of 1's in binary expansion of
2n.
So the second parts gives the formula of2*n - bitcount(2*n). You can calculate this with some efficient bitcount implementation, such as gc... |
I'm looking for a very simple implementation of RSA in C. I need to place it in a DSP, so I'd like to use something very thin and straightforward.
Nonetheless, I just found only examples with little numbers (int or long) while I need to implement RSA at least at 1024 bits, so I also have to cope with large numbers.
C... |
TheLibTomCryptand related projects are very clean and understandable.
|
I'd like to useCprogram to find the total number of directives like#include,#define,#ifdef,#typedef, etc. Could you suggest any logic for that? I'm not interested in using any scripting or tools. I want it to be done purely usingCprogram.
|
Storeall the directivesin an array of pointers (or arrays).
Read the C file line by line and check if the first word starts with any of the directives in the list excluding any whitespaces at the beginning.
```
char *directives[]={"#assert", "#define#, ......};
int count[NUM_DIRS]= { 0 };
```
Everytime you find a ... |
I was looking at a basic Box2D program, more specificallythis one.
Everything is fairly simple and makes sense, except for this line:
```
Shape.SetAsBox((32.f/2)/SCALE, (32.f/2)/SCALE); // SCALE = 30
```
Now I know we divide bySCALEto scale 1m->30px but why is 32.f divided by 2? I don't understand why we divide b... |
from themanual:
groundBox.SetAsBox(50.0f, 10.0f);The SetAsBox function takes the half-width and half-height(extents)
|
Can anyone suggest some good references for writing a touchpad driver for linux. Where would I get hardware documentation from. I have read most of the linux device driver books and now I want to take it to the next level.
|
Are you sure there is no current support for your sentelic in linux kernel? Take a look at Documentation/input/sentelic.txt in Linux source code. If it does not give you direct answers, you'll be able to see how to implement something similar instead. Take a look at its sources, too.
Moreover, if you are not really, ... |
lets say I have a file test.c that contains:
```
char buffer1[1024];
int somefunction()
{
char buffer2[1024];
// do stuff
}
```
now I know buffer2 is allocated on the stack on the frame belonging to somefunction calls, but where is buffer1 allocated ?
|
These variables are typically onBSS(variables which don't have explicit initialization in the source code, so they get the value 0 by default) ordata segment(initialized datas). Here,buffer1is uinitialized, so it will probably be allocated on BSS segment, which starts at the end of the data segment.
Frombravegnuwebsi... |
```
int main(void)
{
int i;
int array[5];
for (i = 0; i <= 20; i++)
array[i] = 0;
return 0;
}
```
Why is the above code stuck in an infinite loop?
|
You declare an array with 5 elements but write 21 elements to it. Writing past the end of an array results in undefined behaviour. In you case, you're writing to the loop counteri, resetting it to 0, probably when you assignarray[5].
If you want to fix your program, change the loop to write to the correct number of... |
I'd like to useCprogram to find the total number of directives like#include,#define,#ifdef,#typedef, etc. Could you suggest any logic for that? I'm not interested in using any scripting or tools. I want it to be done purely usingCprogram.
|
Storeall the directivesin an array of pointers (or arrays).
Read the C file line by line and check if the first word starts with any of the directives in the list excluding any whitespaces at the beginning.
```
char *directives[]={"#assert", "#define#, ......};
int count[NUM_DIRS]= { 0 };
```
Everytime you find a ... |
I was looking at a basic Box2D program, more specificallythis one.
Everything is fairly simple and makes sense, except for this line:
```
Shape.SetAsBox((32.f/2)/SCALE, (32.f/2)/SCALE); // SCALE = 30
```
Now I know we divide bySCALEto scale 1m->30px but why is 32.f divided by 2? I don't understand why we divide b... |
from themanual:
groundBox.SetAsBox(50.0f, 10.0f);The SetAsBox function takes the half-width and half-height(extents)
|
Can anyone suggest some good references for writing a touchpad driver for linux. Where would I get hardware documentation from. I have read most of the linux device driver books and now I want to take it to the next level.
|
Are you sure there is no current support for your sentelic in linux kernel? Take a look at Documentation/input/sentelic.txt in Linux source code. If it does not give you direct answers, you'll be able to see how to implement something similar instead. Take a look at its sources, too.
Moreover, if you are not really, ... |
lets say I have a file test.c that contains:
```
char buffer1[1024];
int somefunction()
{
char buffer2[1024];
// do stuff
}
```
now I know buffer2 is allocated on the stack on the frame belonging to somefunction calls, but where is buffer1 allocated ?
|
These variables are typically onBSS(variables which don't have explicit initialization in the source code, so they get the value 0 by default) ordata segment(initialized datas). Here,buffer1is uinitialized, so it will probably be allocated on BSS segment, which starts at the end of the data segment.
Frombravegnuwebsi... |
```
int main(void)
{
int i;
int array[5];
for (i = 0; i <= 20; i++)
array[i] = 0;
return 0;
}
```
Why is the above code stuck in an infinite loop?
|
You declare an array with 5 elements but write 21 elements to it. Writing past the end of an array results in undefined behaviour. In you case, you're writing to the loop counteri, resetting it to 0, probably when you assignarray[5].
If you want to fix your program, change the loop to write to the correct number of... |
I read thatstrcpyis for copying a string, andstrdupreturns a pointer to a new string to duplicate the string.
Could you please explain what cases do you prefer to usestrcpyand what cases do you prefer to usestrdup?
|
strcpy(ptr2, ptr1)is equivalent towhile(*ptr2++ = *ptr1++)
where as strdup is equivalent to
```
ptr2 = malloc(strlen(ptr1)+1);
strcpy(ptr2,ptr1);
```
(memcpy versionmight be more efficient)
So if you want the string which you have copied to be used in another function (as it is created in heap section) you can use... |
My question is quite simple. Is there any possible way to unpack packed .xz file in from C code? I would probably call some default linux-integrated program to unpack it for me, but how exactly does it work? I call the external function and than somehow I get directly back to the program content of the extracted file?... |
I would usesystem("xz -dl file.xz"), but there is good info here and links to source code to implementations:http://tukaani.org/xz/format.html
|
Is it possible to usescanfin order to give a value to a macro substitution calledSIZE(#define SIZE) but without saving the value that came withscanfin another variable?
|
Macros are evaluated at pre-compilation by pre-compilerscanfis evaluated by the compiler. Compiler doesn't understand macros. So no.
|
Do standard C library implementations, especiallyglibc(the GNU C Library) provide linked lists, stack et al. data structures, or do we have to roll our own?
Thanks.
|
The C Standard does not provide data structures like linked list and stack.Some compiler implementations might provide their own versions but their usage will be non portable across different compilers.
So Yes, You have to write your own.
|
I want accurate information about stack overflowing in VC++ (32 bit and 64 bit), and specially in recursion. In Debug mode, this happens so soon in recursion (like 4500 running of a simple recursive function don't do anything or like). However, it seems release mode is different. It was hard to understand, and I didn'... |
As Andreas Brinckstates in his related answer:
In VC++ the default stack size is 1 MB i think, so with a recursion
depth of 10.000 each stack frame can be at most ~100 bytes.
This stack size limit can be modified using:
Project → Properties → Configuration Properties → Linker → System → Stack Reserve Size.
|
First apologize for asking this dumb question:
How to call this function in c (GNU C)
```
char *ftoa(float f, char *buf, int places)
```
|
This is how you call it:
```
int decimal_places = 10;
char* result = malloc(decimal_places + 1);
ftoa(SOME_FLOAT_VALUE, result, decimal_places);
```
The function returns itsbufargument. As always, don't forget to free() theresultstring when you're done with it.
|
I was playing around with Box2D in SFML2 and realized; when I change the gravity of the world, the dynamic bodies that have been untouched for a little while aren't affected by the gravity change. I prepared a video to make this explanation more clear.
Any solutions? Do I have to make my own gravity, and why does thi... |
Objects in Box2D goes to sleep after they come to rest. After changing parameters like gravity you will have to wake up the sleeping objects, likely by callingWakeUpon all the objects. Objects are also woken up automatically when something collides with it, which is why the gravity seems to start taking effect after s... |
With:
```
char *x = malloc(1024);
strcpy(x, "asdf");
x = strdup(x);
free(x); // OK
free(x); // Segfault
```
If I just free it once, will I still be leaking? And if so, how to avoid it?
|
You leak memory because you forget the first pointer. Do it like this:
```
char * x = malloc(1024);
strcpy(x, "asdf");
char * y = strdup(x);
free(x);
free(y);
```
|
I am confused with the concept of file position as used in lseek. Is this file position maintained at inode level or a simple variable which could have different values for different process working on the same file?
|
Per thelseek docs, the file position is associated with the open file pointed to by a file descriptor, i.e. the thing that is handed to your byopen. Because of functions likedupandfork, multipledescriptorscan point to a singledescription, but it's the description that holds the location cursor.
Think about it: if it ... |
My question is quite simple. Is there any possible way to unpack packed .xz file in from C code? I would probably call some default linux-integrated program to unpack it for me, but how exactly does it work? I call the external function and than somehow I get directly back to the program content of the extracted file?... |
I would usesystem("xz -dl file.xz"), but there is good info here and links to source code to implementations:http://tukaani.org/xz/format.html
|
Is it possible to usescanfin order to give a value to a macro substitution calledSIZE(#define SIZE) but without saving the value that came withscanfin another variable?
|
Macros are evaluated at pre-compilation by pre-compilerscanfis evaluated by the compiler. Compiler doesn't understand macros. So no.
|
Do standard C library implementations, especiallyglibc(the GNU C Library) provide linked lists, stack et al. data structures, or do we have to roll our own?
Thanks.
|
The C Standard does not provide data structures like linked list and stack.Some compiler implementations might provide their own versions but their usage will be non portable across different compilers.
So Yes, You have to write your own.
|
I want accurate information about stack overflowing in VC++ (32 bit and 64 bit), and specially in recursion. In Debug mode, this happens so soon in recursion (like 4500 running of a simple recursive function don't do anything or like). However, it seems release mode is different. It was hard to understand, and I didn'... |
As Andreas Brinckstates in his related answer:
In VC++ the default stack size is 1 MB i think, so with a recursion
depth of 10.000 each stack frame can be at most ~100 bytes.
This stack size limit can be modified using:
Project → Properties → Configuration Properties → Linker → System → Stack Reserve Size.
|
First apologize for asking this dumb question:
How to call this function in c (GNU C)
```
char *ftoa(float f, char *buf, int places)
```
|
This is how you call it:
```
int decimal_places = 10;
char* result = malloc(decimal_places + 1);
ftoa(SOME_FLOAT_VALUE, result, decimal_places);
```
The function returns itsbufargument. As always, don't forget to free() theresultstring when you're done with it.
|
I was playing around with Box2D in SFML2 and realized; when I change the gravity of the world, the dynamic bodies that have been untouched for a little while aren't affected by the gravity change. I prepared a video to make this explanation more clear.
Any solutions? Do I have to make my own gravity, and why does thi... |
Objects in Box2D goes to sleep after they come to rest. After changing parameters like gravity you will have to wake up the sleeping objects, likely by callingWakeUpon all the objects. Objects are also woken up automatically when something collides with it, which is why the gravity seems to start taking effect after s... |
With:
```
char *x = malloc(1024);
strcpy(x, "asdf");
x = strdup(x);
free(x); // OK
free(x); // Segfault
```
If I just free it once, will I still be leaking? And if so, how to avoid it?
|
You leak memory because you forget the first pointer. Do it like this:
```
char * x = malloc(1024);
strcpy(x, "asdf");
char * y = strdup(x);
free(x);
free(y);
```
|
I am confused with the concept of file position as used in lseek. Is this file position maintained at inode level or a simple variable which could have different values for different process working on the same file?
|
Per thelseek docs, the file position is associated with the open file pointed to by a file descriptor, i.e. the thing that is handed to your byopen. Because of functions likedupandfork, multipledescriptorscan point to a singledescription, but it's the description that holds the location cursor.
Think about it: if it ... |
I did some googling and couldn't find any good article on this question. What should I watch out for when implementing an app that I want to be endian-agnostic?
|
The only time you have to care about endianness is when you're transferring endian-sensitive binary data (that is, not text) between systems that might not have the same endianness. The normal solution is to use "network byte order" (AKA big-endian) to transfer data, and then swizzle the bytes if necessary on the oth... |
I have an existing embedded source code which runs directly on a microcontroller with no operating system. I need to port the code to run on a specific RTOS.
Are there any guidelines in where to start when attempting wuch a thing ?
Resources, best practices, and other insight will be much appriciated.
|
RTOS preemptive multitasking is all about I/O performance. You need drivers that can make a thread ready when I/O is complete, eg. by signaling a semaphore. Nothing else is remotely as important.
Sadly, this usually means a system redesign to eliminate the performance-crippling polling that existed before :((
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:Do-While and if-else statements in C/C++ macros
I have the following macros :
```
#define FREE1(x) do { free(x); x = NULL; } while (0)
#define FREE2(x) free(x); x = NULL
```
What is the difference between these macros?
|
Consider the following example
```
if (some_test) FREE2(x);
```
expands to
```
if (some_test)
free(x);
x = NULL; // happens regardless of value of some_test
```
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:what does “%.*s” mean in printf in c
I have found the following line :
```
asprintf(&c, "%s%.*s", *msg_in, size * rxed, buffer)
```
And I want to know the meaning of%.*s
|
The%.*sformat means "print a string using a field width ofncharacters, wherenis read from the next argument".
So here, it printsbufferwith a width ofsize * rxedcharacters. (padding with spaces if necessary)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.