question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
+1 for reading it. It's a brilliant, concise book, brilliantly written.
|
Is there a way to get send() to wait until all the data that has been sent has been ACK-ed (or return -1 if the timeout for an ACK has been reached), or is there some other mechanism to wait for the ACK after the send() but before doing something else?
I am using the standard Unix Berkeley sockets API.
I know I coul... |
AFAIK there is no way.
Also, it wouldn't be reliable, the ACK means only that the kernel received the data, in the meantime the client or its machine could have crashed. You would think the client received the data, but actually it never processed it.
|
I am using system() to launch evince on Linux, it works fine until I load a document and try to close it. When I try to close the document system() never returns:
My code:
```
char systemString[MAXPATHLEN];
sprintf( systemString, "%s", "evince" );
int ret = system( systemString );
if ( ret == -1 )
{
perror( "sys... |
I found its because SIGTERM is being blocked but the program. This is a large legacy program.
|
The Names array of char* is located in file1.cpp
```
char* Names[] = {
"name1",
"name2",
...
"nameN"
};
```
How do I declare it as "extern" in file2.cpp in order to get the values?
|
```
extern char *Names[];
```
This should probably go in file1.h.
|
I'm documenting code C with doxygen but this function can´t
```
/**
* @fn void myApp_StartReporting( void )
*
* @brief bla bla....
*
* @see myAccReportPeriod
*
* @return none
*/
static void myApp_StartReporting( void );
```
If remove static the documentation is ok.
Thank you very much.
|
By default doxygen skips static functions. Did you set theEXTRACT_STATIC = YESoption in your Doxyfile?
Also a style note (which was my first guess on what's wrong):
If the documentation block is placed immediately before the entity that it describes the@fntag is not needed.
|
I am working on MicroC on Atom 32bit.
I declared 2 tasks with 0x100 stack size (more than enough for my tasks). When I call a function in one of my task, and I check itsifcondition:
```
if (OSSchedLockNestingCtr > (OS_NESTING_CTR)0u)
{
*p_err = OS_ERR_SCHED_LOCKED;
return;
}
```
the code goes in even ifOSSch... |
Resolved: I find it, the interrupt function was running automatically (5 interrupts in 1 sec) when i was going manual step by step, somehow the varaibles were taking others values (interrupt -> ISR -> put some data in the stuck -> back to my Function -> wierd values :)). 10x to a you all
|
For example, the difference between these two statements:
```
if ( ucNum++ >= 3 ) // ucNum incremented after comparing its value to 3, correct?
{
ucNum = 0;
}
```
vs.
```
ucNum++ >= 3 ? ucNum = 0 : 1; // does incrementing it happen somewhere in the middle of the inline?
```
Perhaps it is compiler specific. Whe... |
The rules are that the condition is evaluated before choosing which alternative to evaluate. Since part of the evaluation is the++, the increment will occur before the assignment (if the assignment occurs at all).
As @caf comments, there is a sequence point after the controlling expression. So, while (as David Thornl... |
I have the filedescriptor and like to get the real path. Currently i call sys_readlink/proc/self/fd/<fd>which works sometimes, but often i get an error -14 (-EFAULT).
Here some Code:
```
fs = get_fs();
set_fs(KERNEL_DS);
err = sys_readlink(path, buf, size-1);
set_fs(fs);
```
Is there an alternative (probably better... |
Get it from the filep in the task struct, e.g. something like
```
struct task_struct *task;
struct files_struct *files;
struct file *file;
char buf[buflen], *realpath;
task = current /* or some other task */;
get_task_struct(task);
files = get_files_struct(task);
put_task_struct(task);
spin_lock(&files->file_lock);
... |
I'm writing some C code and use the Windows API. I was wondering if it was in any way good practice to cast the types that are obviously the same, but have a different name? For example, when passing aTCHAR *tostrcmp(), which expects aconst char *. Should I do, assuming I want to write strict and in every way correct ... |
Don't. But also don't usestrcmp()but rather_tcscmp()(or even the safe alternatives).
_tcs*denotes a whole set of C runtime (string) functions that will behave correctly depending on howTCHARgets translated by the preprocessor.
Concerning safe alternatives, look up functions with a trailing_sand otherwise named as th... |
I need some help at RPC Programming. I really want understand how works the RPCGEN and the MAKEFILE structure. I would like a recommendation of a good introductory book at RPC. I found some examples but I dont know how to compile/integrate the files. More specifically i have a Client source code (one file), a Server s... |
Here are a few resources you might find helpful.
Tutorial of RPC programmingHow RPC works -pdf link
|
The code below compiles well
```
int a=5,b=4,c;
a>b?30:40;
```
Also does,
```
int a=5,b=4,c;
a>b?c=30:40;
```
But why this does not work?
```
int a=5,b=4,c;
a>b?c=30:c=40;
```
|
You are being bitten by precedence.?:has very low precedence, but not as low as=or,(see theoperator precedence table).
Your code is parsed as:
```
(a>b ? c=30 : c) = 40;
```
Rather than:
```
a>b ? c=30 : (c=40);
```
You don't need parenthesis aroundc=30because?and:act like parentheses to the expression within.
... |
How can I, in C, output a value from a syscall to the Linux console so that it will be visible after admesg? What method do I use for printing?
|
You're looking for theprintk()function; some documentation on the types that it supports is found inDocumentation/printk-formats.txt. It is defined inkernel/printk.c.
|
```
class app {
public int x = 3;
static void Main(string[] args)
{
}
}
```
it's possible get the memory address allocated byxvariable?
the example can be inC,C++,C#orD.
I hope it is clear
Thanks in advance
|
The ampersand (&) is the "address-of" operator in most C-like languages:
```
int x;
printf("Address of x is %p\n", &x);
```
The return value of&is effectively apointerto its operand.
|
I can pass struct into pthread_create as thread argument.
But is it possible to modify this struct within the thread so that when the thread terminates, the main program can access this struct to obtain modified data?
If so, do I need to cast the struct back to void in the thread?
|
Yes - assuming the thread function is passed the structure by pointer, you can modify the structure it points at.
No - there is no need to cast the struct back to void in the thread; indeed, I'm not quite sure what you're thinking of, but there's no need for it. The thread function gets avoid *argument. It will cas... |
I'm using Netbeans to write a C program. Where do I need to paste my input.txt file for the program to read it if I don't want to specify a directory in the program?
|
In the currentworking directorywhere the program executes. You'll have to see where exactly Netbeans causes the binary to be output, but most likely, you will want your input.txt file to be in that same directory. Possibly abinsubdirectory of wherever your source is.
|
```
const char* returnStr()
{
char time[40] = {"France"};
char* time1;
time1 = time;
return time1;
}
int main(int argc, char* argv[]) {
printf ("return String is %s\n",returnStr());
}
```
This code returns some junk characters. Won't theconst char*not enough to return the local char pointer?... |
Do I have to use the static too in the function?
Yes. Theconstis just a qualifier on the return value, signaling to callers ofreturnStrthat they shouldn't modify the result of the function. It doesn't changetime's temporary character.
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
+1 for reading it. It's a brilliant, concise book, brilliantly written.
|
Is there a way to get send() to wait until all the data that has been sent has been ACK-ed (or return -1 if the timeout for an ACK has been reached), or is there some other mechanism to wait for the ACK after the send() but before doing something else?
I am using the standard Unix Berkeley sockets API.
I know I coul... |
AFAIK there is no way.
Also, it wouldn't be reliable, the ACK means only that the kernel received the data, in the meantime the client or its machine could have crashed. You would think the client received the data, but actually it never processed it.
|
I am using system() to launch evince on Linux, it works fine until I load a document and try to close it. When I try to close the document system() never returns:
My code:
```
char systemString[MAXPATHLEN];
sprintf( systemString, "%s", "evince" );
int ret = system( systemString );
if ( ret == -1 )
{
perror( "sys... |
I found its because SIGTERM is being blocked but the program. This is a large legacy program.
|
The Names array of char* is located in file1.cpp
```
char* Names[] = {
"name1",
"name2",
...
"nameN"
};
```
How do I declare it as "extern" in file2.cpp in order to get the values?
|
```
extern char *Names[];
```
This should probably go in file1.h.
|
I'm documenting code C with doxygen but this function can´t
```
/**
* @fn void myApp_StartReporting( void )
*
* @brief bla bla....
*
* @see myAccReportPeriod
*
* @return none
*/
static void myApp_StartReporting( void );
```
If remove static the documentation is ok.
Thank you very much.
|
By default doxygen skips static functions. Did you set theEXTRACT_STATIC = YESoption in your Doxyfile?
Also a style note (which was my first guess on what's wrong):
If the documentation block is placed immediately before the entity that it describes the@fntag is not needed.
|
I am working on MicroC on Atom 32bit.
I declared 2 tasks with 0x100 stack size (more than enough for my tasks). When I call a function in one of my task, and I check itsifcondition:
```
if (OSSchedLockNestingCtr > (OS_NESTING_CTR)0u)
{
*p_err = OS_ERR_SCHED_LOCKED;
return;
}
```
the code goes in even ifOSSch... |
Resolved: I find it, the interrupt function was running automatically (5 interrupts in 1 sec) when i was going manual step by step, somehow the varaibles were taking others values (interrupt -> ISR -> put some data in the stuck -> back to my Function -> wierd values :)). 10x to a you all
|
For example, the difference between these two statements:
```
if ( ucNum++ >= 3 ) // ucNum incremented after comparing its value to 3, correct?
{
ucNum = 0;
}
```
vs.
```
ucNum++ >= 3 ? ucNum = 0 : 1; // does incrementing it happen somewhere in the middle of the inline?
```
Perhaps it is compiler specific. Whe... |
The rules are that the condition is evaluated before choosing which alternative to evaluate. Since part of the evaluation is the++, the increment will occur before the assignment (if the assignment occurs at all).
As @caf comments, there is a sequence point after the controlling expression. So, while (as David Thornl... |
I have the filedescriptor and like to get the real path. Currently i call sys_readlink/proc/self/fd/<fd>which works sometimes, but often i get an error -14 (-EFAULT).
Here some Code:
```
fs = get_fs();
set_fs(KERNEL_DS);
err = sys_readlink(path, buf, size-1);
set_fs(fs);
```
Is there an alternative (probably better... |
Get it from the filep in the task struct, e.g. something like
```
struct task_struct *task;
struct files_struct *files;
struct file *file;
char buf[buflen], *realpath;
task = current /* or some other task */;
get_task_struct(task);
files = get_files_struct(task);
put_task_struct(task);
spin_lock(&files->file_lock);
... |
I'm writing some C code and use the Windows API. I was wondering if it was in any way good practice to cast the types that are obviously the same, but have a different name? For example, when passing aTCHAR *tostrcmp(), which expects aconst char *. Should I do, assuming I want to write strict and in every way correct ... |
Don't. But also don't usestrcmp()but rather_tcscmp()(or even the safe alternatives).
_tcs*denotes a whole set of C runtime (string) functions that will behave correctly depending on howTCHARgets translated by the preprocessor.
Concerning safe alternatives, look up functions with a trailing_sand otherwise named as th... |
```
const char* returnStr()
{
char time[40] = {"France"};
char* time1;
time1 = time;
return time1;
}
int main(int argc, char* argv[]) {
printf ("return String is %s\n",returnStr());
}
```
This code returns some junk characters. Won't theconst char*not enough to return the local char pointer?... |
Do I have to use the static too in the function?
Yes. Theconstis just a qualifier on the return value, signaling to callers ofreturnStrthat they shouldn't modify the result of the function. It doesn't changetime's temporary character.
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
+1 for reading it. It's a brilliant, concise book, brilliantly written.
|
Is there a way to get send() to wait until all the data that has been sent has been ACK-ed (or return -1 if the timeout for an ACK has been reached), or is there some other mechanism to wait for the ACK after the send() but before doing something else?
I am using the standard Unix Berkeley sockets API.
I know I coul... |
AFAIK there is no way.
Also, it wouldn't be reliable, the ACK means only that the kernel received the data, in the meantime the client or its machine could have crashed. You would think the client received the data, but actually it never processed it.
|
I am using system() to launch evince on Linux, it works fine until I load a document and try to close it. When I try to close the document system() never returns:
My code:
```
char systemString[MAXPATHLEN];
sprintf( systemString, "%s", "evince" );
int ret = system( systemString );
if ( ret == -1 )
{
perror( "sys... |
I found its because SIGTERM is being blocked but the program. This is a large legacy program.
|
The Names array of char* is located in file1.cpp
```
char* Names[] = {
"name1",
"name2",
...
"nameN"
};
```
How do I declare it as "extern" in file2.cpp in order to get the values?
|
```
extern char *Names[];
```
This should probably go in file1.h.
|
I'm documenting code C with doxygen but this function can´t
```
/**
* @fn void myApp_StartReporting( void )
*
* @brief bla bla....
*
* @see myAccReportPeriod
*
* @return none
*/
static void myApp_StartReporting( void );
```
If remove static the documentation is ok.
Thank you very much.
|
By default doxygen skips static functions. Did you set theEXTRACT_STATIC = YESoption in your Doxyfile?
Also a style note (which was my first guess on what's wrong):
If the documentation block is placed immediately before the entity that it describes the@fntag is not needed.
|
I am working on MicroC on Atom 32bit.
I declared 2 tasks with 0x100 stack size (more than enough for my tasks). When I call a function in one of my task, and I check itsifcondition:
```
if (OSSchedLockNestingCtr > (OS_NESTING_CTR)0u)
{
*p_err = OS_ERR_SCHED_LOCKED;
return;
}
```
the code goes in even ifOSSch... |
Resolved: I find it, the interrupt function was running automatically (5 interrupts in 1 sec) when i was going manual step by step, somehow the varaibles were taking others values (interrupt -> ISR -> put some data in the stuck -> back to my Function -> wierd values :)). 10x to a you all
|
For example, the difference between these two statements:
```
if ( ucNum++ >= 3 ) // ucNum incremented after comparing its value to 3, correct?
{
ucNum = 0;
}
```
vs.
```
ucNum++ >= 3 ? ucNum = 0 : 1; // does incrementing it happen somewhere in the middle of the inline?
```
Perhaps it is compiler specific. Whe... |
The rules are that the condition is evaluated before choosing which alternative to evaluate. Since part of the evaluation is the++, the increment will occur before the assignment (if the assignment occurs at all).
As @caf comments, there is a sequence point after the controlling expression. So, while (as David Thornl... |
I have the filedescriptor and like to get the real path. Currently i call sys_readlink/proc/self/fd/<fd>which works sometimes, but often i get an error -14 (-EFAULT).
Here some Code:
```
fs = get_fs();
set_fs(KERNEL_DS);
err = sys_readlink(path, buf, size-1);
set_fs(fs);
```
Is there an alternative (probably better... |
Get it from the filep in the task struct, e.g. something like
```
struct task_struct *task;
struct files_struct *files;
struct file *file;
char buf[buflen], *realpath;
task = current /* or some other task */;
get_task_struct(task);
files = get_files_struct(task);
put_task_struct(task);
spin_lock(&files->file_lock);
... |
I'm writing some C code and use the Windows API. I was wondering if it was in any way good practice to cast the types that are obviously the same, but have a different name? For example, when passing aTCHAR *tostrcmp(), which expects aconst char *. Should I do, assuming I want to write strict and in every way correct ... |
Don't. But also don't usestrcmp()but rather_tcscmp()(or even the safe alternatives).
_tcs*denotes a whole set of C runtime (string) functions that will behave correctly depending on howTCHARgets translated by the preprocessor.
Concerning safe alternatives, look up functions with a trailing_sand otherwise named as th... |
On which factors do I have to pay attention when copying strings in C? And what can go wrong?
I can think of I need to reserve sufficient memory before copying a string and have to make sure I have enough privileges to write to the memory (try to avoid General Protection Faults), but is there anything else I have to ... |
Make sure that you have sufficient buffer space in the destination (i.e. know ahead how many bytes you're copying). This also means making sure that the source string is properly terminated (by a null character, i.e.0='\0').Make sure that the destination string gets properly terminated.If your application is character... |
What happens if you try to free a memory which is not allocated usingmalloc/calloc?
Here is what I mean :
```
void main()
{
int temp = 0;
int *ptr = &temp;
free(ptr);
}
```
I thoughtfree()would return some error code butfree()does not have a return value.
|
If you callfree()on the pointer which wasn't allocated before, it will trigger undefined behavior.
FromLinux man pages:
The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called... |
Looking at man 2 write:
```
"On error, -1 is returned, and errno is set appropriately."
```
But if write(2) just fail, it makes nonsense to write an error message right after...
maybe i should write an error message on stderr or maybe just exit() on the first write error?
What do you think?
|
In a typical command line program, error messages shouldalwaysbe written tostderr, that's what it's for.
|
Here is a simple one line program usingprintf:
```
void main()
{
printf("%d%d",printf("Cis"),printf("good"));
}
```
Output :
```
goodCis34
```
How can this output be explained ??
|
The reason whygoodandCisare printed first is because the parameters need to be evaluated before the top-levelprintf()can be called.
Then the return values are printed out.
Note that C does not specify the order of evaluation of the parameters.There are no sequence points within the statement. Therefore the order is ... |
I want to print a string ofint double double double double double doublein a table made of ASCII characters. What ways are there to keep the values aligned with the table headers and ensure they don't 'overflow'?
My table header looks something like this:
```
+---------+------+------+------+---------+---------+-----... |
```
printf("%10f %10f\n", double_val0, double_val1);
```
That would print the two doubles with 10 characters width max.
|
I want to get Screen Position from World Position in DirectX.
I can get my ball's world position. But I can't know how can I convert it to screen position.
|
You have a view/eye transform V (the one that "places" your "camera") and a projection transform P.
Clip space coordinates are reached by
```
clip_position = P * V * world_space_position
```
From clip space you reach NDC space by dividing the clip space coordinates by the 4th clip space coordinate w, i.e.
```
ndc_... |
my question is on execution what will happen to parent stack?
```
main()
{
f();
g();
}
f()
{
vfork();
}
g()
{
int blast[100],i;
for(i=0;i<100;i++)
blast[i]=i;
}
```
|
The behavior is undefined as perhttp://pubs.opengroup.org/onlinepubs/009695399/functions/vfork.html
the behavior is undefined if the process created by vfork() [...] returns from the function in which vfork() was called [...]
|
```
#define q(k)main(){return!puts(#k"\nq("#k")");}
q(#define q(k)main(){return!puts(#k"\nq("#k")");})
```
This code can print itself on the screen,however,I have a difficulty in reading it,especially that two #K,how does it work?I know how #define q(k) 2*k works,but I really have no idea about this code.Please help... |
Simplify the call and use your compiler's preprocessor to see what is going on:
```
#define q(k)main(){puts(#k"hello("#k")");}
q(argument)
```
Runninggcc -Eon that gives you:
```
main(){puts("argument""hello(""argument"")");}
```
As you can see, what happens is that the argument to theqmacro gets transformed into ... |
I have this cellphone which runs Android OS 2.6. Due to some reasons, I want to write code directly on my cellphone just as what we do in front of our PC.
So,
Can we make the Android cellphone a develop-platform? I mean write/compile/run C code on Android cellphones?If we can, how?
|
Yes you can,for C/C++(but sorry, not free). I don't use python, don't know if it have similar one or not. Anyway, this is just-for-fun compiler, I don't think it can compile real code with such low processing power and memory.
If you didn't like this app or don't have money, try to compiletiny Cfor android.
|
When I use C Api for Mysql, I heard that I need to compile with gcc like
gcc $(mysql_config --cflags --libs) source.c
but it is tired using this awkward whenever compile c file using mysql.
isn't there any good ways to compile like
gcc source.c
when using Mysql C api.
please help me!
|
Learn how to write a smallMakefile, and you'll simply typemaketo compile your program.
|
I'm reading the contents of file into a 9 element array. I need to check if there are any duplicates in this array. I need to do this without reordering or changing the any of the contents of the array.
How would I go about doing this?
|
Use brute force.
You've only got 9 elements in the array, so it'll only take 36 comparisons to find any duplicates:
```
int count = sizeof(array) / sizeof(array[0]);
for (int i = 0; i < count - 1; i++) { // read comment by @nbro
for (int j = i + 1; j < count; j++) {
if (array[i] == array[j]) {
... |
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago.
In C/C++ Language... areforloops in... |
Yes, usually, basically. A for loop, written
```
for (a; b; c) { ... }
```
can be rewritten as
```
a;
while (b) { ...; c; }
```
Note that this doesn't take into account scoping and such issues, because when you translate a for to a while, scoping can't be written precisely in C++ syntax.
However, underneath, a fo... |
In my CGI library, I'm using a converter in order to convert from a IANA-registered charset to native wide unicode (UTF-16/32, depending on platform). With ICU, are all the sets and aliases listed inhttp://www.iana.org/assignments/character-setsallowed for input toucnv_openor is a manual cross-reference mapping needed... |
RTFMing the HTML specs,accept-charset="..."does the job, hence this is useless overhead.
|
I'm working on software which downloads a file and shows transfer speed via an SDL window.
My problem is that when I launch a download, the window is immediately identified by windows as a crashed program. As soon as the download is completed, everything is okay.
My program didn't crash and I think that it's because i... |
To prevent those freeze, you need to put, in the main thread an event manager (SDL_PoolEvent + SDL_Delay to not overuse CPU)
|
I have an input like
```
char *input="00112233FFAA";
uint8_t output[6];
```
What is the easiest way to convertinputintooutputwithsscanf? (prefer 1 line with no loop) The solution I have in mind doesn't scale to 20+ hex string.
```
sscanf(input, "%x%x%x%x%x",output[0], output[1]....output[5]);
```
|
Whyscanfif this can be easily written by hand:
```
const size_t numdigits = strlen(input) / 2;
uint8_t * const output = malloc(numdigits);
for (size_t i = 0; i != numdigits; ++i)
{
output[i] = 16 * toInt(input[2*i]) + toInt(intput[2*i+1]);
}
unsigned int toInt(char c)
{
if (c >= '0' && c <= '9') return c ... |
I have a mysterious problem!
In the main.c I have the following:
```
#include "jogo.h"
int main(){
int i;
sef_startup();
vg_init(0x105);
batalha_naval();
sleep(5);
vg_exit();
return 0;
}
```
In the jogo.h I have:
```
#ifndef __JOGO_H
#define __JOGO_H
void batalha_naval(void);
#endif
```
... |
Your jogo.h appears correct.
You need it if you wish to use function "batalha_naval()" in multiple compilation units.You should '#include "jogo.h"' in main.c, and in jogo.c.You must include both main and jogo in your link command.
|
Suppose I had a nxn grid of doubles stored in plain text, columns separated by a single space, rows separated by line breaks, for example:
```
1.01 2.22 6.10
-22.10 -15.0 1.0
2.3 -4.4 5.5
```
All I know is the numbers will be doubles, the program must parse nxn doubles (i.e a square matrix) into a 2-d array, but wil... |
Read the lines, usestrtok(s, " \t")to tokenize them, then callstrtodon the results and store them. Add sanity checks to ensure that what you got is ann×nmatrix.
Better yet, usestrsepinstead ofstrtokif your platform has it.
Alternatively, callscanfn×ntimes and check its return value each time and finally check whethe... |
What does the term context mean in context-free and context-sensitive languages? Can a variable have multiple contexts? If I need to store a particular value in a particular memory address how does does affect the context of the memory address? And if I want to update a variable how does the context of the variable ch... |
A context-sensitive grammar, productions have the general form
```
aBc -> ab'c
```
where upper-case symbols are non-terminals and lower-case symbols are sequences of terminals and non-terminals.
In the above example,aandbwould be the context of the non-terminalBand indicate thatBmay "expand" tob'only when surrounde... |
I have a character pointer ,char *buf;I have a array of integers ,int console_buffer[256];I need to copy theconsole_buffercontents to character buf.
How do I do this? Thebufandconsole_bufferare part of different structures.
|
Going by your comment,
```
buf = malloc(256); // 257 if console_buffer may be full without EOF
/* if you want to allocate just as much space as needed, locate the EOF in console_buffer first */
for(int i = 0; i < 256 && console_buffer[i] != -1; ++i){
buf[i] = (char)console_buffer[i];
}
```
|
I have added a resource in my project. Its size is 4.096 byte.
i need to assign it to DWORD because 3rd argument of WriteFile() needs it.
```
WriteFile(hFile, pExeResource,size, &bytesWritten, NULL);
```
So i cast it like this:
UPDATE2: DWORD bootsize = 4096; //and still warns me
But i get this warning. can you p... |
I think this is a combination of regional/language differences along with C-syntax.
I assume you mean4.096to be4,096with a comma separator. (Due to regional/language differences, you probably use.instead of,.)
In C/C++, you don't use the separators. Just do this instead:
```
DWORD bootsize = (DWORD)4096;
```
|
Why can we omit the first dimension of a multidimensional array when we are passing it to a function?
In my programming class, we were told what when passing a multidimensional array to a function we can omit first dimension, for example,a[10][15][20]can be passed asa[][15][20].
Why?
|
Because the array will decay to pointer and to calculate offset to the elements of the array you do not need to know the innermost dimension. Offset toa[i][j][k]isi*nj*nk+j*nk+k(wherenjandnkare corresponding dimensions).
|
I am trying to build my own zend module (.so)
We have multiple functionality that can be done in our own module which will improve our performance on a high traffic website (50k+ visits a day).
These are simple module but I was wondering is the language used by zend is similar toC?
How easy is to translate current ... |
maybe this can help:http://devzone.zend.com/303/extension-writing-part-i-introduction-to-php-and-zend/
Of course what you see is very similar to c ;-)
|
I am quite anxious about strings in C. Do I need to set the last char \0 or it does it by it self? If I don't do it manually then when I try to debug code and when I access string1[257] it is not null. I am having problems with freeing allocated memory of an array of strings so I thought it was a reason.
```
char str... |
String literals like"Hello World!"are null-terminated, butchararrays are not automatically null terminated.
The general principle I've always taken is to be extra cautious and assign'\0'to the the end of the string unless that causes a performance problem. In those cases, I'm extra careful about which library functi... |
Is it possible to view structure definitions using man pages the way we can see function definitions in UNIX?
For instance, for network programming, we use a structure calledstruct sockaddr_in. Is there anyway to see how sockaddr_in has been defined in the library using man pages?
Any help will be appreciated! Thank... |
For any given header:
```
echo '#include <netinet/in.h>' | gcc -E - | less
```
Which generates of relevant interest:
```
# 225 "/usr/include/netinet/in.h" 3 4
struct sockaddr_in
{
sa_family_t sin_family;
in_port_t sin_port;
struct in_addr sin_addr;
unsigned char sin_zero[sizeof (struct sockaddr)... |
I need a way using the Win32 API to force shutdown my machine.
I am currently using Windows 7 but O'd really like if the code would work for Vista and XP.
|
Isn'tExitWindowsEx()enough for your needs?
|
I have a C program that invokes a java program but I have a problem:
my java program returns an int [], how can I use JNI to get the result of it in C, since JNI only has CallIntMethod?
|
Arrays are objects, so you can useCallObjectMethod(). UseGetIntArrayElements()to access the array elements.
|
I want to print a string ofint double double double double double doublein a table made of ASCII characters. What ways are there to keep the values aligned with the table headers and ensure they don't 'overflow'?
My table header looks something like this:
```
+---------+------+------+------+---------+---------+-----... |
```
printf("%10f %10f\n", double_val0, double_val1);
```
That would print the two doubles with 10 characters width max.
|
I want to get Screen Position from World Position in DirectX.
I can get my ball's world position. But I can't know how can I convert it to screen position.
|
You have a view/eye transform V (the one that "places" your "camera") and a projection transform P.
Clip space coordinates are reached by
```
clip_position = P * V * world_space_position
```
From clip space you reach NDC space by dividing the clip space coordinates by the 4th clip space coordinate w, i.e.
```
ndc_... |
my question is on execution what will happen to parent stack?
```
main()
{
f();
g();
}
f()
{
vfork();
}
g()
{
int blast[100],i;
for(i=0;i<100;i++)
blast[i]=i;
}
```
|
The behavior is undefined as perhttp://pubs.opengroup.org/onlinepubs/009695399/functions/vfork.html
the behavior is undefined if the process created by vfork() [...] returns from the function in which vfork() was called [...]
|
```
#define q(k)main(){return!puts(#k"\nq("#k")");}
q(#define q(k)main(){return!puts(#k"\nq("#k")");})
```
This code can print itself on the screen,however,I have a difficulty in reading it,especially that two #K,how does it work?I know how #define q(k) 2*k works,but I really have no idea about this code.Please help... |
Simplify the call and use your compiler's preprocessor to see what is going on:
```
#define q(k)main(){puts(#k"hello("#k")");}
q(argument)
```
Runninggcc -Eon that gives you:
```
main(){puts("argument""hello(""argument"")");}
```
As you can see, what happens is that the argument to theqmacro gets transformed into ... |
I have this cellphone which runs Android OS 2.6. Due to some reasons, I want to write code directly on my cellphone just as what we do in front of our PC.
So,
Can we make the Android cellphone a develop-platform? I mean write/compile/run C code on Android cellphones?If we can, how?
|
Yes you can,for C/C++(but sorry, not free). I don't use python, don't know if it have similar one or not. Anyway, this is just-for-fun compiler, I don't think it can compile real code with such low processing power and memory.
If you didn't like this app or don't have money, try to compiletiny Cfor android.
|
When I use C Api for Mysql, I heard that I need to compile with gcc like
gcc $(mysql_config --cflags --libs) source.c
but it is tired using this awkward whenever compile c file using mysql.
isn't there any good ways to compile like
gcc source.c
when using Mysql C api.
please help me!
|
Learn how to write a smallMakefile, and you'll simply typemaketo compile your program.
|
I have a character pointer ,char *buf;I have a array of integers ,int console_buffer[256];I need to copy theconsole_buffercontents to character buf.
How do I do this? Thebufandconsole_bufferare part of different structures.
|
Going by your comment,
```
buf = malloc(256); // 257 if console_buffer may be full without EOF
/* if you want to allocate just as much space as needed, locate the EOF in console_buffer first */
for(int i = 0; i < 256 && console_buffer[i] != -1; ++i){
buf[i] = (char)console_buffer[i];
}
```
|
I have a C file that looks like this:
```
#include <stdio.h>
int main(void)
{
printf("Hello world\n");
while (1);
return 0;
}
```
And I would like to see "Hello world" printed in a new file. But it doesn't work when I try to redirect the standard output like this:
```
./hello_world >> logfile &
```
And t... |
You need to flush stdout before the loop:
```
#include <stdio.h>
int main(void)
{
printf("Hello world\n");
fflush(stdout);
while (1);
return 0;
}
```
|
As the title, I don't know how to parse a string including the alphabetic characters and the special characters from other languages in C. Anyone please help me how to distinguish them in C?. Do I need to install some optional components to help C accept the characters?(I'm in linux environment). Thanks very much for ... |
At a minimum you need to decide whatcharacter encoding(s)you are going to use or support. After that you will need to decide if you will keep the international strings in their native forms, or convert them using something likelibiconvinto a single encoding in your application.
So first, as Laurent pointed out in a ... |
Hi i have two clutter_actors . when i shift the focus from actor_1 to actor_2 for the first time it works. but later it does not shift back. I use the following statements.
```
clutter_stage_set_key_focus (CLUTTER_STAGE(stage), actor_2);
g_signal_connect (actor_1, "key-press-event", G_CALLBACK (button_key_press), NUL... |
I solved it.
It was very easy. Its the same code i have used which i have given in the question.
Actually i was giving the key focus to actor_2 when i wanted to shift the focus from actor_2 to actor_1 . It was a logical error from my side.
|
I have a string which has this:
```
((12+41)*30)
```
here12,41and30are all characters. How do I do arithmetic operations on them ?
Also when I have a number20how can I get a string which reads 20?
|
In order to calculate expressions like that you need create a tree of the tokens 12, +, 41, 30
```
*
/ \
[+] 30
/ \
12 41
```
this can be done for instance by converting your infix expression to a postfix expression, by doing so the correct operator prece... |
I'm trying to get user input and allowing them to only input a whole number which is also positive.
I'm trying to figure out this task
```
printf("Enter the first and second number in whole number: ");
scanf("%d,%d", &first, &second);
if (input != '\n') //notice this line I'm trying to check if is a character//
... |
Read a whole line (withgetline), then convert it to a number, perhaps usingstrtol(and testing the end pointer).
Or use the%nformat forscanfand test the number (of successful conversions) returned byscanf
|
I have to make sure that a string passed as argument does not cause an overflow. I'm doing this by using strncpy, but the ending '\0', allocating the right amount of memory and so on gives me some troubles...
My solution is this:
```
l = strlen(argv[optind]);
if(l<MAX_LENGTH) {
msg = malloc((l+1) * sizeof(char))... |
I think this is about the simplest you can get:
```
size_t l;
char* msg;
...
l = strlen(argv[optind]);
if (l > MAX_LENGTH) l = MAX_LENGTH;
msg = malloc(l + 1);
if (msg == NULL) /* handle the error as appropriate*/;
memcpy(msg, argv[optind], l);
msg[l] = '\0';
```
|
I have wery little code:
```
// prototype
bool Foo();
int main( ... )
{
if( Foo() == false )
return 1;
return 0;
}
bool Foo()
{
return true;
}
```
What is wrong with this? The compiler (VS 2010) shows a lot of syntax error with ")" and ";" and im not doing it right with my prototype?
|
I think your problem is that bool is not defined.
It depends how your compiler is set but bool is a type that is frequently not supported without defining it yourself or including it.
I found this :
http://msdn.microsoft.com/en-us/library/tf4dy80a.aspx
Cheers
Jason
|
is there a way to find out programmatically which paths are searched by dlopen() for shared objects? I always thought dlopen() would only look in /lib and /usr/lib but now I've seen that on Linux Mint several core components like libglib-2.0.so are in a wholly different folders, namely in /rofs/lib/i386-gnu-linux and ... |
look at theldconfigman page, and the file:/etc/ld.so.conf
|
I am trying to link my library with some other librarylib1usingCMAKE 2.8. It should be said it's on Windows.
InCMakeLists.txtI have:
```
add_library(mylib ${sources})
include_directories(${CMAKE_SOURCE_DIR}/lib1/include)
target_link_libraries(mylib ${lib1_path})
```
But compiler says that some#include <lib1/foo.h>i... |
Check the following:
Does the path${CMAKE_SOURCE_DIR}/lib1/include/lib1/foo.hexist?Quote (") the path passed toinclude_directories, otherwise you may be passing several paths when it is split by spacesTry runningmake VERBOSE=1to see exactly what options are being passed to gcc
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:What's the difference between a file descriptor and file pointer?
If I open file like this:
```
FILE *fp = fopen("mr32.txr","r");
```
thenfpis file pointer or file descriptor? What is difference between them?
|
fp is a FILE pointer
File pointer:
It is high level interfacePassed to fread() and fwrite() functionsIncludes buffering,error indication and EOF detection,etc.Provides higher portability and efficiency.
File descriptor:
Low/Kernel level handlerpasse to read() and write() of UNIX System CallsDoesn't include bufferi... |
I'm working in Xilinx Platform Studio, and what I essentially want to do, is have a VHDL module output some values, and then I would like to be able to read that value from another program written in C.
I figure what I want to do is map a specific port in my VHDL module to a spot in memory, and then read from that sp... |
Is this a microblaze or power pc processor? The simplest way would probably be a gpio peripheral.
http://www.xilinx.com/support/documentation/ip_documentation/plb_gpio.pdf
If you need more speed you could use an FSL Link.
http://www.xilinx.com/support/documentation/ip_documentation/plb2fsl_bridge.pdf
Other ideas ... |
When I try to use exec:
```
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
int main()
{
exec("echo `Hello World`");
return 0;
}
```
I get this error:
```
code.c:11: error: implicit declaration of function ‘exec’
make: *** [code.o] Error 1
```
I have to use std=c99 and I... |
Based on your includes, it appears like you're using a Unix of some kind. There is noexeccall. There isexecl,exexlp, and others with names depending on the exact types of parameters. Check the man page for 'exec' for details.
|
Alright so my question is, how can I make a program that basically executes the rest of the program at for example 12pm. For example some non realistic code:
```
#include <stdio.h>
#include <time.h>
int main()
{
Get_time() //Gets system time
if(time() == 254pm ){ //if time is 2:54pm
printf(... |
Uselocaltimeto get the current time.
```
#include <stdio.h>
#include <time.h>
int main ()
{
// Get system time
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
// Check
if(timeinfo->tm_hour == 14 && timeinfo->tm_min == 54)
{
printf(... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:Weird use of void
I was reading C code and came across the following. Can somebody please explain what this does?
```
static int do_spawn(const char *filename)
{
(void)filename;
// todo: fill this in
return -1;
}
```
Specifically, ... |
Compilers sometimes complain about unused parameters; the(void)"cast" is simply a way to use the variable in a void, non-side-effect context so that the compiler won't complain about it being "unused".
EDIT: As rodrigo points out below, the compiler warning can be suppressed without the(void)prefix, but then another ... |
I call my program and it is to read a bunch fo integers from the standard input
```
int main() {
int* s;
derp(s);
return 0;
}
void derp(int *size) {
scanf("%d", size);
}
```
why is this code causing a segmentation fault?
|
```
int* s;
derp(s);
```
What doesspoint to? To random garbage memory since its not initialized. You should do this instead:
```
int s;
derp(&s);
```
or you could allocate storage space usingmalloc:
```
int* s = malloc( sizeof(int) );
derp(s);
free(s);
```
|
What does a0xprefix on a number mean?
```
const int shared_segment_size = 0x6400;
```
It's from a C program. I can't recall what it amounts to and particularly what the letterxmeans.
|
Literals that start with0xare hexadecimal integers. (base 16)
The number0x6400is25600.
```
6 * 16^3 + 4 * 16^2 = 25600
```
For an example including letters (also used in hexadecimal notation where A = 10, B = 11 ... F = 15)
The number0x6BF0is27632.
```
6 * 16^3 + 11 * 16^2 + 15 * 16^1 = 27632
24576 + 2816 ... |
I have a program that defines a variableint data
The program usesscanf("%d",&data)to read data from stdin.
If the data from stdin is not an integer, I have to print error message.
I triedif(scanf("%d",&data) ==EOF){ printf("error");return 1;}
It didn`t works for me. So, how can I determine if scanf failed or succee... |
scanf's return value is an integer, telling you how many items were succesfully read. If your single integer was read successfully,scanfwill return 1.
e.g.
```
int items_read = scanf("%d", &data);
if (items_read != 1) {
//It was not a proper integer
}
```
There is a great discussion on reading integershere, on... |
Why this does not work, filetest.c:
```
#include <event.h>
int main(void)
{
event_init();
return 0;
}
```
Then:gcc -o test.o -c test.cruns OK, but
Link:g++ -o test -levent test.oproduces
```
test.o: In function `main':
test.c:(.text+0x5): undefined reference to `event_init'
collect2: ld returned 1 exit sta... |
This question has been asked many times. On Linux, youshouldputlibraries after object and sourcefiles in the compilation command. So try
```
g++ -Wall -g -c mytest.cc
g++ -Wall -g mytest.o -levent -o mytest
```
Avoid calling your test programtestwhich is an existing utility or shell builtin.
As a newbie, remember ... |
What's the reason fortypedefsnot being strongly typed? Is there any benefit I can't see or is it due to backward compatibility? See this example:
```
typedef int Velocity;
void foo(Velocity v) {
//do anything;
}
int main() {
int i=4;
foo(i); //Should result in compile error if strongly typed.
return 0... |
Because C is not strongly typed and typedef has its origin in that thinking
typedef is just for convenience and readability, it doesn't create a new type.
|
I'm having problem with a simple C program. Even if I enter a year between 1000 and 1999 it still displays invalid year. Please tell me what's happening??
```
#include <stdio.h>
main()
{
int year;
c:
printf("\n\nEnter a Year: ");
scanf("%d", year);
if ((year < 1000) || (year > 1999))
{
p... |
You need to pass an address toscanf, i.e.:
```
scanf("%d", &year);
```
Note the ampersand.
|
I work on a library to parse connection information from a satellite modem. It sends this information as an UDP package over the network, which I receive withrecvfrom().
What information do I get via thebufferparameter ofrecvfrom()? Is it only the UDP message field, or do I get more information about the UDP package?... |
The buffer will only receive the payload data of the packet. Headers are not included.
|
input is like this
```
5 // is # of vertices
1 1 0 1 // 1<->2 1<->3 1<->4 1<->5
0 0 0 // 2<->3 2<->4 2<->5
0 1 // 3<->4 3<->5
1 // 4<->5
```
I want to make adjacency matrix, when that input is inserted. how to do that?
I made already matrix like this
```
array = (int)malloc(sizeof(int)*numVetex);
```
|
There are many ways to do this. Here is one of them:
```
int **array;
int numVertex;
int i,j;
scanf("%d",&numVertex);
array = malloc(sizeof(int*) * numVertex);
for(i=0;i<numVertex;i++) {
array[i] = malloc(sizeof(int) * numVertex);
}
for(i=0;i<numVertex-1;i++) {
for... |
I am coding in C for a device that is using ARM architecture. I want to check for memory leaks in my application. As in my device in which iam working (ARM architecture ) does not support Valgrind .. so what other options I can use for checking for memory leaks in my application. Is there any way to check for memory l... |
Valgrind actually does support ARM nowdays (it even supports NEON SIMD instructions). If running debian or ubuntu, you should be able to install valgrind via apt. You may have to enable testing/unstable repositories, but the package exists.
Or you could of course compile it yourself (I have tried and it works).
|
I'm developing an embedded software based on standard specification.
The software is big and I need a design of my software before start coding.
the UML is an object-oriented language and could be a solution but I don't know how to use it for C softwares.
are there any document which help to use UML for C programming... |
Yes, you can, mostly because of two reasons:
You can actually do Object Oriented Programming with C (although it is tedious and not completely advisable), there a fewbookson the subject that you can read.You can still use class diagrams to model data structures and static methods. But UML is not just about class diag... |
Do signal handlers have a separate stack, (like each thread have separate stacks)?
This is in Linux/C context.
|
From the Linux manual pagesignal(7):
```
By default, the signal handler is invoked on the normal process stack.
It is possible to arrange that the signal handler uses an alternate stack;
see sigaltstack(2) for a discussion of how to do this and when it might
be useful.
```
|
```
char *s = "hello";
```
The code above allocates 6 bytes in read-only section of a program (I've forgot the name of the section) to store the stringhello. Then,sis initialized to point to the first character of the stringhello. Modifying the string"hello"is undefined behavior. Besides,"hello"itself is constant in ... |
In C, "hello" has typechar[]. This is not C++. Seethis question.
|
I'm a C newbie.
I want to my string "aaaabbbbbbb" to a kind of map
```
array1[0][0] = (a,4)
array1[1][0] = (b,7)
```
and compare this string "4444bbbbbbb" and make the other map and find same element and count between two maps
```
array2[0][1] = (b,7)
array2[1][1] = (4,4)
```
so we can findarray1[1][0] == array2[... |
One way might be to
Find the longest common subsequence of both strings (seehttp://rosettacode.org/wiki/Longest_common_subsequence)Remove this subsequence from both stringsGoto 1
|
I want to convert number from char * format to 32 bit integer int32_t, but strtol() returns long.
I don't know length of long on my machine. It could be 32 or 64 bit or something else in the future.
What is the correct and bulletproof way to convert string to 32 bit integer int32_t? Or to convert long to int32_t.
I... |
Usesscanfwith one of the format specifier macros from<inttypes.h>, e.g.SCNd32orSCNi32:
```
int32_t i;
sscanf(str, "%"SCNd32, &i);
```
These are available since C99.
|
scala can make mapping (ADT) so we can mapping like this ('A', 3) = (Char, Int)
how about in C?
I want to mapping and check all the relations and comparing between two maps
'a' = 1, 'b' = 3, 'c' = 4 is mapping by abbbcccc
and 'e' = 1 , 'b' = 3, 'g' = 4 is mapping by bbbegggg
I want to find these relation ('a' , 1... |
Not in plain C, no.
You could implement one with an array or two, but you would have to implement either a hashing algorithm, or some kind of comparison and search algorithm. Alternatively you could use some kind of search tree to implement it.
If you don't want to write a map data type, you will have to use a libra... |
Suppose I have a pointer to image data which has 3 channels (RGB), 8 bits per channel and I want to display the value of a pixel like #000000, which is a 24 bit number. The data is stored like RGB RGB RGB ... so I really need to read the first three bytes.
```
typedef unsigned char uchar;
uchar* data = get_image_data... |
You can bit-shift right by 8 bits to achive this.
```
uint32_t value = *((uint32_t*) data) >> 8;
printf("Value is %0X", value);
```
Example wheredatais two pixels of value#1177ff:
```
data = 11 77 ff 11 77 ff
value = 11 77 ff 11
value >> 8 = 00 11 77 ff
```
|
I have found the contours using cvfindcontour, and, now I want to access first and second contour and find the euclidean distance between them. Could anybody help me with its code?
```
CvPoint *contourPoint, *contourPoint2;
contourPoint = (CvPoint *)CV_GET_SEQ_ELEM(CvPoint,contours,1);
contourPoint2 = (CvPoint *)CV_G... |
I would usecvMomentsto compute the centroid of each contour, and then compute theEuclidean distancebetween the two centroids.Hereis a post on openframeworks about it.Hereis a post from the opencv mailing-list.
Hope that helps!
|
I have a number for example:2.4444444. I need to get first digit after the dot -- in my case it's4. How to implement it?
|
How about
```
( (int)(floor( fabs( num ) * 10 ) ) ) % 10
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.