question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I want to disassemble a simple .c file:
```
#define UPPER 15
const int lower = 12;
int sum = 0;
int main(void) {
int i;
for(i = lower; i < UPPER; i++)
{
sum += i;
}
return sum;
}
```
To get the assemblercode for ARM CPUs on my Mac Mini 10.8.3. There fore i am stuck at:
How do i create the ARM execu... |
To compile(assuming the target is iOS 6.0):
```
xcrun -sdk iphoneos c++ -arch armv7 -marm -march=armv7-a -miphoneos-version-min=6.0 -g -O3 <any other options ...>
```
To disassemble:
```
otool -tdv <your binary>
```
|
Code:
```
char menu_list[] = {'Boiled egg', 'Corn flakes', 'Gobi 65', 'Chicken 65', 'Basandi'};
```
Am a new to c programming i just wanted to make an array of string, but am getting an waring as below. can anyone please tell me why its happening. Its a c program.
```
main_menu.c:226: warning: large integer implici... |
You should use double quotes for string lliteral, and you are wrongly declaring the array.
Perhaps you are looking for thiss.
```
char *menu_list[] = {"Boiled egg", "Corn flakes", "Gobi 65", "Chicken 65", "Basandi"};
```
|
This question already has an answer here:Most complete c++ facebook library [closed](1 answer)Closed10 years ago.
I'm looking to create a desktop app in C/C++, most likely with Qt, that has the ability to connect (read/post) to Facebook. Which got me thinking, how exactly would you go about doing such a task? I know ... |
If you can get a C++ json interpreter you can use the Graph API.https://developers.facebook.com/docs/getting-started/graphapi/. You make queries over HTTPs and get a response in JSON that you can use however you want.
|
If i have a text file with each line of different length, how does the following code work??
```
FILE *ptr;
char str[100];
ptr=fopen("hi.txt","r");
while(fgets(str,100,ptr)!=NULL)
{
........
........
}
```
In this code the 'str' will hold 100 characters which includes some of the characters from 2nd line of text fil... |
fgets will read up to a single line OR the value passed in as the second parameter.
fgets man page
As long as none of your lines are longer than 99 characters (saving one for the NUL terminator, your code will work as expected.
If you call fgets on a line that is longer than N-1, your next read will continue where ... |
Is there a way to to something like:
```
char* a = "Hello";
char* b = NULL;
char* c = a | b;
Result should be c = "Hello";
```
Seems like it does not work with Char*, but is there a way to do something like that?
|
This is nonsense not only because bitwise operators on pointers would have very... interesting... results, but mainly becauseNULL is not guaranteed to be represented by 0.
|
I am looking for a function/system call that can be used in C to manage network interfaces of the Linux machine. E.g., I would like to doip link set wlan0 down(or up) orifconfig wlan0 down, what function can be used for it, apart fromsystem()?
|
To access the functionality provided by the iproute2 tools from software, you can use theLinux rtnetlink API. To make it easier for you, use libraries likelibnl.
In case you encounter trouble, there is already a tag callednetlink
|
I want to write a specific number of bytes to a socket,
```
n=write(sock_fd, buf, len);
```
ifn<len, I would rather no bytes are written into the socket,
is it possible or not?
thanks!
|
If you're using blocking mode, the condition can never arise: send() will block until all the data has been sent. This is not the way the documentation reads, but it's how all known implementations behave.If you're talking about TCP, it doesn't make any difference anyway: it's a byte-steam protocol, not a datagram pro... |
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question
I'm trying to write a piece of code that will display the contents of a txt file. I only have numbers store... |
Problem solved turned out the file in %ebx was in append mode not in write mode
|
I'm trying to understand how exactly memory indirect addressing works in assembly language with AT&T syntax.
```
movl (%eax), %ebx
movl %eax, (%ebx)
```
Here is a similar question that explains aboutmemory indirect addressing
This is what I've understood:
In the first case, youloadthe data pointed to by the regis... |
Basically the syntax is
```
movl source, destination
```
Somovl (%eax), %ebxis indeed copy the value at address pointed to by %eax into %ebx. Andmovl %eax, (%ebx)is copy the value inside register %eax into the address pointed to by %ebx.
So indeed your understanding is correct.
|
I have an existing database which structure is used accross the whole application. Instances of the databases are periodically rotated. I have a database filetemplate.sqlitewhich is used as a template for all newly created databases. I want to use it, not a creation script, so that I have to maintain only one file, th... |
You could use the.dumpcommand of thecommand-line shelldo create a bunch of SQL commands that you can execute.
Alternatively, you can use thebackup APIto copy the template into a new database.
|
Given:
```
#error /*
*/ foo
```
Microsoft C++ outputs an error message of/*and GCC outputsfoo.
Which is correct?
|
GCC is correct.
Replacement of comments (including line-breaks) happens in translation phase 3, pre-processing in translation phase 4 (ISO/IEC 9899:1999, §5.1.1.2).
Hence, the preprocessing part of the compiler does not "see" the line-breaks anymore.
And,#erroris defined like this (§6.10.5):
A preprocessing direct... |
Here is a snippet ofassembly codeinAT&T Syntax.
```
int foo_array[64*1024] __attribute__ ((aligned (8192)));
void
foo()
{
__asm__("movl %0,%%eax"::"r"(&foo_array));
```
I understood thatmovlcopies the data from source operand to destination operand. that is, in my case, it is moving0 to eax.. This is what I ha... |
You should read up onGCC inline assembly constraints.
In short, what that::"r"(&foo_array)says is that you want one input for your assembly code, that the input should be placed in a register, and that its value should be the address offoo_array.The%0in the code is substituted with that input, so the code places the ... |
Compiling this with gcc (4.6.3) yields no warnings and produces -2147483648 as the result.
```
printf ("%d", (1<<31));
```
Compiling this yields "warning: integer overflow in expression [-Woverflow]" and produces 2147483647 as the result.
```
printf ("%d". (1<<31)-1);
```
I am confused why the second expression gi... |
Although1<<31is arguably undefined behaviour for a signed 32 bit integer, it typically results in the maximum negative 32 bit 2's complement integer value (0x80000000 = -2147483648). If you try to subtract 1 from this value then the valueunderflowsand becomes the maximum positive value, hence the compiler warning.
``... |
I am just experimenting , but want to use Dart as a scripting language for a high performance simulation application I've been working on.(think games)
Basically use Dart in lieu of Lua
I have found old resources, but I have heard the are out of date - and haven't really found any tutorials on how to actually utiliz... |
I couldn't find any good article on this, onlythis discussion threadin Dart group. However, there are working demos in theDart's source code.
Take a look atDartHostimplementation in some of these projects - this should give you some idea about how to do it.
|
I have a C library that I'd like to interface to from C++ code without modifying the library. It has a yacc-generated front end that reads fromyyin, which is aFILE *. I'd like to setyyinto some kind ofemulationof aFILE *which reads from memory. Is there any hope of doing this in a portable (Linux, Mac, Windows) manner... |
You can usefmemopen()on Linux. Unfortunately, not only is there no portable way to do this, but then again,fopen()isn't even really portable (it's been broken for a long time on Windows).
However, if your tokenizer is Flex, you can useyy_scan_buffer(). SeeString input to flex lexer.
|
I'm trying to find the distance between two characters in the alphabet. However, it's OK to go from A->Z or Z->A in one step. Given two characters, how do I find the distance?
|
Subtract the two characters from each other making the result positive if it's negative.
From there, the answer is either that value, or if it's more than 13, it's 26 - value.
```
char a = '<SOME LETTER>';
char b = '<SOME LETTER>';
char distance = abs(a-b);
if (distance > 13) {
distance = 26 - distance;
}
```
|
I have a device connected to the computer as "COM8". I'd like to know when it is unplugged from the computer, so I used the following code to detect:
```
m_receiverCom->isWritable();
m_receiverCom->isOpen();
```
However, they still returned trueafter I unplugged the device. How can I detect whether the device is plu... |
You queried the port, not the device. Send some kind of query message to the device that will produce a response message.
|
I am writing a server that usesfork()to spawn handlers for client connections. The server does not need to know about what happens to the forked processes – they work on their own, and when they're done, they should just die instead of becoming zombies. What is an easy way to accomplish this?
|
There are several ways, but usingsigactionwithSA_NOCLDWAITin the parent process is probably the easiest one:
```
struct sigaction sigchld_action = {
.sa_handler = SIG_DFL,
.sa_flags = SA_NOCLDWAIT
};
sigaction(SIGCHLD, &sigchld_action, NULL);
```
|
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.Closed10 years ago.
I was asked this during an intervie... |
Thanks everyone who participated. I think now it seems like the answer will be "there's no reliable way of doing this." Great discussions guys!
|
I'm populating a combo box with data from a database using the DataSource property.
I need the field of the combo box to be initially empty.
I've tried:
```
cbPerson.SelectedIndex = -1;
```
but this doesn't work.
I've tried the solutions here:
http://social.msdn.microsoft.com/Forums/en-US/winformsdatacontrols/thre... |
You would need to have an empty list item at a certain index, generally first (as with the usual "Please select...", and such kinds of defaults you see). You can use theInsertmethod ofItems:
```
cbPerson.Items.Insert("", 0);
```
That might work, depending on which technology you're using, which you failed to specify... |
```
char list_ch[][2] = {
'a', 'A',
'b', 'B',
'c', 'C',
'd', 'D',
'e', 'E',
'f', 'F',
'g', 'G'};
```
According tothistutorial I'm following, this is supposed to create a multidimensional array with 7 elements each containing two other elements that are of... |
It's a warning, because you should write like this instead:
```
char list_ch[][2] = {
{'a', 'A'},
{'b', 'B'},
{'c', 'C'},
{'d', 'D'},
{'e', 'E'},
{'f', 'F'},
{'g', 'G'}};
```
|
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed8 years ago.Improve this question
I made a structure in C and read all data in dat structure using fread function,Actually i confused about t... |
You can easily read a wav file , just follow this document.https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
As for extracting frequencies from the file you would need to apply a Fourier Transform to your data , which would convert your data from Amplitude Time to Frequency time domain.http://en.wikipedia.o... |
There are tons of example of reading unicode file in C, but could not find anything specific to using glib library in a platform independent way. I am totally newbie in this stuff (coming from .net world). My requirement is to read a Unicode file using glib. I am using gcc as compiler.
|
Perhaps you're having trouble because unicode has several different encodings, and reading each one is a bit different. The most popular these days is UTF-8, and you can use something likeg_data_input_stream_read_linefor that. For other encodings you could useg_data_input_stream_read_upto(just pass the byte sequence... |
I would like to know if there is an equivalent offseekandftellwhen I'm working in main.
For example, if I type the name of a file when asked, at end I hit enter. Next I'll ask the user another file name, but there's a'\n'in the buffer that was not read. The user won't be able to type the name of the second file becau... |
The easiest way to do this would be just to say
```
getc(stdin);
```
or even shorter
```
getchar();
```
and ignore the returned character.
|
I've seen definitions in C
```
#define TRUE (1==1)
#define FALSE (!TRUE)
```
Is this necessary? What's the benefit over simply defining TRUE as 1, and FALSE as 0?
|
This approach will use the actualbooleantype (and resolve totrueandfalse) if the compiler supports it. (specifically, C++)
However, it would be better to check whether C++ is in use (via the__cplusplusmacro) and actually usetrueandfalse.
In a C compiler, this is equivalent to0and1.(note that removing the parentheses... |
I want to change directory in unix using code in a C file.I tried this:
```
char command[50];
strcpy( command, "cd newdirectory/" );
system(command);
```
but it didn't work.Other commands using "system" work.
|
To change directory try to usechdir. A related question isHow to change the working directory in C?. About using system seeWhy can't we change directories through system() system call in Linux?andChanging the current directory in Linux using C++.
|
When we do not give the value in a macro substitution.
```
#define YES
printf("%d",YES)
```
The value of YES is not given, is it by default 0 or garbage?
|
You just defined YES tonothing. So the result program after preprocessor should beprintf("%d",)
|
```
int x; //line 1
int x; //line 2
int main()
{
return 0;
}
```
Both line 1 and line 2 declare as well as define the variable x. But the code doesn't give any linker errors. Why is it so?
Compilation fails only when I initialize x in both the lines.
```
int x=3;
int x=3;
int main(){
return 0;
}
```
I thought ... |
It works because the definitions in my code are tentative in nature. So they are initially taken as declarations and upon failing to find any other instance of definition, they are combined into a single definition.
|
I'm trying to understand how exactly memory indirect addressing works in assembly language with AT&T syntax.
```
movl (%eax), %ebx
movl %eax, (%ebx)
```
Here is a similar question that explains aboutmemory indirect addressing
This is what I've understood:
In the first case, youloadthe data pointed to by the regis... |
Basically the syntax is
```
movl source, destination
```
Somovl (%eax), %ebxis indeed copy the value at address pointed to by %eax into %ebx. Andmovl %eax, (%ebx)is copy the value inside register %eax into the address pointed to by %ebx.
So indeed your understanding is correct.
|
I have an existing database which structure is used accross the whole application. Instances of the databases are periodically rotated. I have a database filetemplate.sqlitewhich is used as a template for all newly created databases. I want to use it, not a creation script, so that I have to maintain only one file, th... |
You could use the.dumpcommand of thecommand-line shelldo create a bunch of SQL commands that you can execute.
Alternatively, you can use thebackup APIto copy the template into a new database.
|
Given:
```
#error /*
*/ foo
```
Microsoft C++ outputs an error message of/*and GCC outputsfoo.
Which is correct?
|
GCC is correct.
Replacement of comments (including line-breaks) happens in translation phase 3, pre-processing in translation phase 4 (ISO/IEC 9899:1999, §5.1.1.2).
Hence, the preprocessing part of the compiler does not "see" the line-breaks anymore.
And,#erroris defined like this (§6.10.5):
A preprocessing direct... |
Here is a snippet ofassembly codeinAT&T Syntax.
```
int foo_array[64*1024] __attribute__ ((aligned (8192)));
void
foo()
{
__asm__("movl %0,%%eax"::"r"(&foo_array));
```
I understood thatmovlcopies the data from source operand to destination operand. that is, in my case, it is moving0 to eax.. This is what I ha... |
You should read up onGCC inline assembly constraints.
In short, what that::"r"(&foo_array)says is that you want one input for your assembly code, that the input should be placed in a register, and that its value should be the address offoo_array.The%0in the code is substituted with that input, so the code places the ... |
Compiling this with gcc (4.6.3) yields no warnings and produces -2147483648 as the result.
```
printf ("%d", (1<<31));
```
Compiling this yields "warning: integer overflow in expression [-Woverflow]" and produces 2147483647 as the result.
```
printf ("%d". (1<<31)-1);
```
I am confused why the second expression gi... |
Although1<<31is arguably undefined behaviour for a signed 32 bit integer, it typically results in the maximum negative 32 bit 2's complement integer value (0x80000000 = -2147483648). If you try to subtract 1 from this value then the valueunderflowsand becomes the maximum positive value, hence the compiler warning.
``... |
I am just experimenting , but want to use Dart as a scripting language for a high performance simulation application I've been working on.(think games)
Basically use Dart in lieu of Lua
I have found old resources, but I have heard the are out of date - and haven't really found any tutorials on how to actually utiliz... |
I couldn't find any good article on this, onlythis discussion threadin Dart group. However, there are working demos in theDart's source code.
Take a look atDartHostimplementation in some of these projects - this should give you some idea about how to do it.
|
I have a C library that I'd like to interface to from C++ code without modifying the library. It has a yacc-generated front end that reads fromyyin, which is aFILE *. I'd like to setyyinto some kind ofemulationof aFILE *which reads from memory. Is there any hope of doing this in a portable (Linux, Mac, Windows) manner... |
You can usefmemopen()on Linux. Unfortunately, not only is there no portable way to do this, but then again,fopen()isn't even really portable (it's been broken for a long time on Windows).
However, if your tokenizer is Flex, you can useyy_scan_buffer(). SeeString input to flex lexer.
|
I'm trying to find the distance between two characters in the alphabet. However, it's OK to go from A->Z or Z->A in one step. Given two characters, how do I find the distance?
|
Subtract the two characters from each other making the result positive if it's negative.
From there, the answer is either that value, or if it's more than 13, it's 26 - value.
```
char a = '<SOME LETTER>';
char b = '<SOME LETTER>';
char distance = abs(a-b);
if (distance > 13) {
distance = 26 - distance;
}
```
|
I have a device connected to the computer as "COM8". I'd like to know when it is unplugged from the computer, so I used the following code to detect:
```
m_receiverCom->isWritable();
m_receiverCom->isOpen();
```
However, they still returned trueafter I unplugged the device. How can I detect whether the device is plu... |
You queried the port, not the device. Send some kind of query message to the device that will produce a response message.
|
I am writing a server that usesfork()to spawn handlers for client connections. The server does not need to know about what happens to the forked processes – they work on their own, and when they're done, they should just die instead of becoming zombies. What is an easy way to accomplish this?
|
There are several ways, but usingsigactionwithSA_NOCLDWAITin the parent process is probably the easiest one:
```
struct sigaction sigchld_action = {
.sa_handler = SIG_DFL,
.sa_flags = SA_NOCLDWAIT
};
sigaction(SIGCHLD, &sigchld_action, NULL);
```
|
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.Closed10 years ago.
I was asked this during an intervie... |
Thanks everyone who participated. I think now it seems like the answer will be "there's no reliable way of doing this." Great discussions guys!
|
I'm populating a combo box with data from a database using the DataSource property.
I need the field of the combo box to be initially empty.
I've tried:
```
cbPerson.SelectedIndex = -1;
```
but this doesn't work.
I've tried the solutions here:
http://social.msdn.microsoft.com/Forums/en-US/winformsdatacontrols/thre... |
You would need to have an empty list item at a certain index, generally first (as with the usual "Please select...", and such kinds of defaults you see). You can use theInsertmethod ofItems:
```
cbPerson.Items.Insert("", 0);
```
That might work, depending on which technology you're using, which you failed to specify... |
```
char list_ch[][2] = {
'a', 'A',
'b', 'B',
'c', 'C',
'd', 'D',
'e', 'E',
'f', 'F',
'g', 'G'};
```
According tothistutorial I'm following, this is supposed to create a multidimensional array with 7 elements each containing two other elements that are of... |
It's a warning, because you should write like this instead:
```
char list_ch[][2] = {
{'a', 'A'},
{'b', 'B'},
{'c', 'C'},
{'d', 'D'},
{'e', 'E'},
{'f', 'F'},
{'g', 'G'}};
```
|
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed8 years ago.Improve this question
I made a structure in C and read all data in dat structure using fread function,Actually i confused about t... |
You can easily read a wav file , just follow this document.https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
As for extracting frequencies from the file you would need to apply a Fourier Transform to your data , which would convert your data from Amplitude Time to Frequency time domain.http://en.wikipedia.o... |
There are tons of example of reading unicode file in C, but could not find anything specific to using glib library in a platform independent way. I am totally newbie in this stuff (coming from .net world). My requirement is to read a Unicode file using glib. I am using gcc as compiler.
|
Perhaps you're having trouble because unicode has several different encodings, and reading each one is a bit different. The most popular these days is UTF-8, and you can use something likeg_data_input_stream_read_linefor that. For other encodings you could useg_data_input_stream_read_upto(just pass the byte sequence... |
I would like to know if there is an equivalent offseekandftellwhen I'm working in main.
For example, if I type the name of a file when asked, at end I hit enter. Next I'll ask the user another file name, but there's a'\n'in the buffer that was not read. The user won't be able to type the name of the second file becau... |
The easiest way to do this would be just to say
```
getc(stdin);
```
or even shorter
```
getchar();
```
and ignore the returned character.
|
I've seen definitions in C
```
#define TRUE (1==1)
#define FALSE (!TRUE)
```
Is this necessary? What's the benefit over simply defining TRUE as 1, and FALSE as 0?
|
This approach will use the actualbooleantype (and resolve totrueandfalse) if the compiler supports it. (specifically, C++)
However, it would be better to check whether C++ is in use (via the__cplusplusmacro) and actually usetrueandfalse.
In a C compiler, this is equivalent to0and1.(note that removing the parentheses... |
I want to change directory in unix using code in a C file.I tried this:
```
char command[50];
strcpy( command, "cd newdirectory/" );
system(command);
```
but it didn't work.Other commands using "system" work.
|
To change directory try to usechdir. A related question isHow to change the working directory in C?. About using system seeWhy can't we change directories through system() system call in Linux?andChanging the current directory in Linux using C++.
|
When we do not give the value in a macro substitution.
```
#define YES
printf("%d",YES)
```
The value of YES is not given, is it by default 0 or garbage?
|
You just defined YES tonothing. So the result program after preprocessor should beprintf("%d",)
|
```
int x; //line 1
int x; //line 2
int main()
{
return 0;
}
```
Both line 1 and line 2 declare as well as define the variable x. But the code doesn't give any linker errors. Why is it so?
Compilation fails only when I initialize x in both the lines.
```
int x=3;
int x=3;
int main(){
return 0;
}
```
I thought ... |
It works because the definitions in my code are tentative in nature. So they are initially taken as declarations and upon failing to find any other instance of definition, they are combined into a single definition.
|
This question already has answers here:What is the difference between char s[] and char *s?(14 answers)Closed10 years ago.
In my GCC 32-bit compiler, the following code gives the output
```
char *str1="United";
printf("%s",str1);
```
output:
```
United
```
then should I considerchar *str1="United";the same aschar... |
The two are not the same:char *str1="United"gives you a pointer to a literal string, which must not be modified (else it's undefined behavior). The type of a literal string should really be const but it's non-const for historical reasons. On the other hand,char str1[]="United"gives you a modifiable local string.
|
Is it possible in C to let the user "select" a value from data previously printed on the screen by moving his cursor to the desired value and then pressing theEnterorspacekey to confirm the selection?
To exemplify:
In the following code:
```
int x[10] = {1,2,3,4,5,6,7,8,9,10};
int i;
for(i = 0; i < 10; ++i... |
Use some kind of a programming library that allows the programmer to write text-based user interfaces in a terminal-independent manner. For example,ncurses.
|
i use mingw and msys on windows 7(64 bit) to compile x264.
the following is the error showed:
libx264.a(frame.o):frame.c:(.text+0x2c2d): undefined reference to `__sync_fetch_
and_add_4'
collect2.exe: error:ld reutrn 1
Makefile:182: recipe for target 'x264.exe' failed
make:*[x264.exe] Error 1
|
What is your mingw/gcc version? __sync_fetch_and_add is built-in gcc's function from version 4.0 afaik. May be it is related to this:http://gcc.gnu.org/bugzilla/show_bug.cgi?id=28671Anyway try to update your gcc.
|
Once the program that created the linked list is closed without deleting the dynamic memory and I know that dynamic memory needs to be deleted then how can i get it back to work after reopening the program and if i can't get back the linked list then what is the use of linked list
|
When you exit the programeverythingit has is gone. Including linked and unlinked lists, arrays, solo object and all.
If you want something to persist you must save it, then load it bask. Like in a text editor you use load and save.
There are full libraries to help the issue, you may start withboost::serialization.
|
I need to create a large file (several gbytes) in /dev/shm. which is a RAMdisk on Linux machines. This must be as fast as possible. I'm currently using 5 separate POSIX threads in C to create sequential 100 mbyte segments, then I have another thread which concatenates them onto the main output file.
This is fast, b... |
The fastest way to do this is to just calltruncate()orftruncate()to expand the file to the size you want.
You can thenmmap()the file into the process's memory space, and have each thread write its section into the mapped area.
|
I'm working on some C and TCL libraries which keeps referring to booleans using a convention of addin a p to the end of the variable name, i.e.
```
set is_registered_p 0
# do stuff
if { $is_registered_p } {
#do stuff
}
```
I found this in multiple files and from multiple sources, so I thought it have to be a co... |
The most likely thing is that it stands for “Predicate” (i.e., a condition that can be evaluated to yield a boolean value) but its not a convention that's particularly common among most Tcl programmers.
If someone's using the convention, you might expect to see it with the names of both variables and commands; in the... |
Am I using scanf() in some wrong way?
```
char *input;
scanf("%s", input);
printf("%s\n", input);
```
This fails at the run-time.
|
Declaring achar *only creates a pointer, it does not allocate any memory for the string. You need to allocate memory for input. You can do that dynamically viamalloc(andfreewhen done) or you can declare an array of static size likechar input[100].
|
There is something wrong with the code below... Could someone explain to me whats the problem and why?
```
#include<stdio.h>
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23,34,12,17,204,99,16};
int main()
{
int d;
for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
printf("%d\n",array[d+... |
Usual arithmetic conversions.
In the<=expression theintvalue-1is converted to the unsigned type ofsizeofand becomes a huge value and the<=expression is then false.
Use:
```
for(d=-1;d <= (int) (TOTAL_ELEMENTS-2);d++)
```
|
I am currently solving a program onRussian Peasant algorithmand i am using a recursive code:
My Code:
```
int russian_peasant(int a,int b)
{
static int sum =0;
if(a>=1)
{
if(a%2!=0)
{
sum += (b);
russian_peasant(a/2,b*2);
}
else
{
... |
You probably need a local variable without thestatickeyword.
This way each function call preserves its local copy ofsum.
|
In a makefile, what is the difference in meaning betweenincludeand-include?
Examples:
```
-include $(APPINCLUDES)
include $(CONTIKI)/platform/$(TARGET)/Makefile.$(TARGET)
```
|
The difference is that-includewon't generate an error if the include file doesn't exist.
The-prefix can be used many places in theMakefileto perform actions that you don't mind if they fail.
|
flock()is generally async-signal-safe because it is a system call. Its semantics make it hard to implement it differently. It is not in the POSIX'slistof async-signal-safe functions because it is not in POSIX at all.
Is it possible to useflock()in the sigaction handler without problems?
|
According to@alkanswer in the followingtopic:
We can develop our propertyflock()function (its name could beasync_flock()). we copy in this new function the content of the originlockf()code and then we make the following changes in order to get an async-signal-safe function:
replace__fcntlwithfcntl: necessary to make... |
This question already has answers here:What does | and << mean?(2 answers)Closed10 years ago.
everyone. When learning OC recently, I always come across enum like this.
```
enum {
type1 = 0,
type2 = 1 << 0,
type3 = 1 << 1,
};
```
What does it mean by type = 1 << 0 ? What is it usually used for? Thank... |
Bitwise Shift Left Operator
In Objective-C the bitwise left shift operator is represented by the '<<' sequence, followed by the number of bit positions to be shifted
Source
Also readthis famous postto understand what it does and how
|
I am trying to compile 64-bit GSL on a Windows 7 machine. Here are the steps I took:
Downloaded and untarred the GSL 1.15 source foundhere.Tested that I have a 64-bit version of GCC available in the Cygwin shell, by compiling the minimal program// simple.C
int main() {
;
return 0;
}usingx86_64-w64-mingw32-gc... |
At the cygwin prompt you can use:
```
CC=x86_64-w64-mingw32-gcc CFLAGS=-m64 ./configure
```
and configure will pick it up.
Important Note:
I am surprised that you don't have a wrappergcc... Why don't you try using./configureby itself just as is to begin with and see what it does before overriding the C compiler as... |
Why does right shift have two choices — appending the sign bit (arithmetic right shift) or appending 0 (logical right shift) and why does the implementation get to choose which?
|
The difference is to allow the handling of both signed (two's complement) and unsigned integers.
When right-shifting a signed (two's complement) integer the
most-significant bit is the sign; 0 for positive or zero, and 1 for
negative. In order to retain the sign on the right-shift, one must
duplicate the existing hig... |
This is testing part of the code:
```
float a = 0;
float b = 0;
int c = 0;
int d = 0;
#pragma omp parallel for schedule (dynamic, 1) reduction(+ : a, b, c, d)
for(i=0; i<100; i++) {
a +=1;
b +=1;
c +=1;
d +=1;
}
printf("a: %d, b: %d, c: %d, d: %d\n", a, b,... |
You are using%dformats to print floating point numbers. That causes undefined behaviour. Use:
```
printf("a: %f, b: %f, c: %d, d: %d\n", a, b, c, d);
```
And you'll see you get the right answers.
|
So I am getting this error even though the code I am compiling has no '?' at all.
I am using gcc as my compiler & linker. Any tips on why this is happening?
Also, when I remove the 'l' from the function name the error goes away. Im confused.
Code snippet where the error is showing up:
```
unsigned long htonl(unsign... |
htonl is sometimes defined as a macro in the standard include files for gcc. Use a different name.
|
Is it to check for the WS_CHILD bit:
```
LONG style = GetWindowLong(hwnd, GWL_STYLE);
int isTopLevel = !(style & WS_CHILD);
```
Or is there a better way?
Assume: Straight C calling only existing Windows API code.
|
Way #1: TesthWnd==GetAncestor(hWnd,GA_ROOT)Way #2: UseIsTopLevelWindow(user32 Win7, undocumented)
|
I have a function that gets passed an array of chars, or a string. I use this array for data array and thus has a lot of random characters in it including NULL chars. My problem comes in when I am trying to retrieve this data the compiler sees and the Null char and thinks the string ends. Thereby effectively throwing ... |
A C string and an array ofcharis not the same thing. The first is implemented by means of the second with the additional convention that the string ends where the array has the first0element.
So what you need is just anunsigned char[something]and you'd have to keep track of the length that you want to have separately... |
I have a common header file for multiple source files in a C project. I want a certain struct instance:
```
typedef struct
{
char username[255];
char password[255];
} Configuration;
Configuration config;
```
To be available for all source files, and any changes made to it in any of the source files, should ... |
In your header file you declare the config variable as extern:
```
extern Configuration config;
```
And in one, and only one, source file you define that variable like so:
```
Configuration config;
```
|
I guess usingmemcpyto copypthread_attr_tisn't a good idea as the struct seems private on both Darwin and Linux. What the proper way of copyingpthread_attr_t? There isn't a copy function in pthreads. Doing get/set of all attributes is probably the safest way but it's not future proof.
This is what it looks like on my ... |
Interesting question, but the answer (judging from the Rationale section of thepthread_attr_init()specification) is that you are not supposed to copypthread_attr_tobjects around. You are right thatmemcpy()etc are not reliable mechanisms (and what's wrong with plain old assignment anyway?).
|
Is there a way in C that I can format a string like I would inprintf, but instead store it in a variable? I am trying to use this for system calls, so I can include a variable in the call.
|
You can usesprintf(orsnprintfin C99/C11) to format your string before using it.
```
int sprintf(char *str, const char *format, ...);
int snprintf(char *str, size_t size, const char *format, ...);
```
Example:
```
// Use the value of an integer 'n' as argument in 'perror' (C99).
#include <limits.h>
#include <stdio.... |
I have the followingsigactionhandler function
```
void signal_term_handler(int sig)
{
printf("EXIT :TERM signal Received!\n");
int rc = flock(pid_file, LOCK_UN | LOCK_NB);
if(rc) {
char *piderr = "PID file unlock failed!";
fprintf(stderr, "%s\n", piderr);
printf(piderr);
}
... |
You can usefcntl()as an alternative to flock().
|
Is there a macro to return (ideally as aconst char*or indeedcont char *const) the typename of its parameter or some information on it?
This is atcompile time, not runtime, so C++'s typeinfo will not do. I run with-fno-rttianyway.
|
There isn't.
C++11 does have the__func__identifier inside function definitions, which produces a string variable with the function name. Most C++ compilers have variations on this to have "decorated" function names.
|
I was reviewing a particular code snippet in which function is declared as
```
int fn_xyz()
```
but while referencing the function in another .c file, it is defined as :
```
extern void fn_xyz()
```
while fn_xyz is called, there is no check for the return values ; GCC-4.7.0 never warned on the above mismatch ; is ... |
Each source file (technically, eachtranslation unit) is compiled completely independently of the others. So the compiler never knows that you've declared the same symbol in multiple places. At link time, all type information has been removed, so the linker can't complain either.
This is precisely why you should dec... |
I use the following code below (source) to keep the log files:
```
#include <stdio.h>
#include <unistd.h>
#include <syslog.h>
int main(void) {
openlog("slog", LOG_PID|LOG_CONS, LOG_USER);
syslog(LOG_INFO, "A different kind of Hello world ... ");
closelog();
return 0;
}
```
I run the program on ubuntu and it k... |
During openlog, use a special facility, so that you can modify your syslog.conf file to direct such logs to any log file you specified.
Don't forget to remove such facility from the default syslog - by default all logs goes to syslog.
|
I am using Eclipse IDE on ubuntu to code in C. I use its normal debugging and default compiler ( GCC )
am writing code with OpenMP features. Eclipse just skips the pragmas and compiles the code in serial. So I end up running the program from terminal with the -fopenmp parameters.
I was wondering if there is a way to... |
You need to go toBuild > Settings > Miscellaneous > All optionsand add-fopenmp.
|
I have a function that gets passed an array of chars, or a string. I use this array for data array and thus has a lot of random characters in it including NULL chars. My problem comes in when I am trying to retrieve this data the compiler sees and the Null char and thinks the string ends. Thereby effectively throwing ... |
A C string and an array ofcharis not the same thing. The first is implemented by means of the second with the additional convention that the string ends where the array has the first0element.
So what you need is just anunsigned char[something]and you'd have to keep track of the length that you want to have separately... |
I have a common header file for multiple source files in a C project. I want a certain struct instance:
```
typedef struct
{
char username[255];
char password[255];
} Configuration;
Configuration config;
```
To be available for all source files, and any changes made to it in any of the source files, should ... |
In your header file you declare the config variable as extern:
```
extern Configuration config;
```
And in one, and only one, source file you define that variable like so:
```
Configuration config;
```
|
I guess usingmemcpyto copypthread_attr_tisn't a good idea as the struct seems private on both Darwin and Linux. What the proper way of copyingpthread_attr_t? There isn't a copy function in pthreads. Doing get/set of all attributes is probably the safest way but it's not future proof.
This is what it looks like on my ... |
Interesting question, but the answer (judging from the Rationale section of thepthread_attr_init()specification) is that you are not supposed to copypthread_attr_tobjects around. You are right thatmemcpy()etc are not reliable mechanisms (and what's wrong with plain old assignment anyway?).
|
Is there a way in C that I can format a string like I would inprintf, but instead store it in a variable? I am trying to use this for system calls, so I can include a variable in the call.
|
You can usesprintf(orsnprintfin C99/C11) to format your string before using it.
```
int sprintf(char *str, const char *format, ...);
int snprintf(char *str, size_t size, const char *format, ...);
```
Example:
```
// Use the value of an integer 'n' as argument in 'perror' (C99).
#include <limits.h>
#include <stdio.... |
I have the followingsigactionhandler function
```
void signal_term_handler(int sig)
{
printf("EXIT :TERM signal Received!\n");
int rc = flock(pid_file, LOCK_UN | LOCK_NB);
if(rc) {
char *piderr = "PID file unlock failed!";
fprintf(stderr, "%s\n", piderr);
printf(piderr);
}
... |
You can usefcntl()as an alternative to flock().
|
Is there a macro to return (ideally as aconst char*or indeedcont char *const) the typename of its parameter or some information on it?
This is atcompile time, not runtime, so C++'s typeinfo will not do. I run with-fno-rttianyway.
|
There isn't.
C++11 does have the__func__identifier inside function definitions, which produces a string variable with the function name. Most C++ compilers have variations on this to have "decorated" function names.
|
I was reviewing a particular code snippet in which function is declared as
```
int fn_xyz()
```
but while referencing the function in another .c file, it is defined as :
```
extern void fn_xyz()
```
while fn_xyz is called, there is no check for the return values ; GCC-4.7.0 never warned on the above mismatch ; is ... |
Each source file (technically, eachtranslation unit) is compiled completely independently of the others. So the compiler never knows that you've declared the same symbol in multiple places. At link time, all type information has been removed, so the linker can't complain either.
This is precisely why you should dec... |
I use the following code below (source) to keep the log files:
```
#include <stdio.h>
#include <unistd.h>
#include <syslog.h>
int main(void) {
openlog("slog", LOG_PID|LOG_CONS, LOG_USER);
syslog(LOG_INFO, "A different kind of Hello world ... ");
closelog();
return 0;
}
```
I run the program on ubuntu and it k... |
During openlog, use a special facility, so that you can modify your syslog.conf file to direct such logs to any log file you specified.
Don't forget to remove such facility from the default syslog - by default all logs goes to syslog.
|
I am using Eclipse IDE on ubuntu to code in C. I use its normal debugging and default compiler ( GCC )
am writing code with OpenMP features. Eclipse just skips the pragmas and compiles the code in serial. So I end up running the program from terminal with the -fopenmp parameters.
I was wondering if there is a way to... |
You need to go toBuild > Settings > Miscellaneous > All optionsand add-fopenmp.
|
Im trying to code a C function that has a optional argument, and if that argument isn't "used", then it has a default value.
```
int DumpData(int a, int b, int c=0)
{
if(c != 0)
{
//stuff
}
//banana
}
/* Function Call */
DumpData(1, 2);
```
Is there any way to solve this issue ?
|
No, there's no way to do this in C. The best you can do is to have separate functions:
```
int DumpData(int a, int b)
{
return DumpDataABC(a, b, 0);
}
int DumpDataABC(int a, int b, int c)
{
...
}
```
Or, use C++ instead of C.
|
So I have a textbox and I want to make it go to a new line when it reaches the border. Also, I am new to this w32 API. Here is my code:
```
hEdit=CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "", WS_CHILD|WS_VISIBLE|
WS_BORDER, 10,
10, 160, 420, hwnd, (HMENU)IDC_MAIN_EDIT, GetModu... |
You need to include the ES_MULTILINE style when creating the control.
http://msdn.microsoft.com/en-us/library/windows/desktop/bb775464(v=vs.85).aspx
|
I am using eclipse CDT to test the Intel instructions and below is my program:
```
#define cpuid(func,ax,bx,cx,dx)\
__asm__ __volatile__ ("cpuid":\
"=a" (ax), "=b" (bx), "=c" (cx), "=d" (dx) : "a" (func));
int Check_CPU_support_AES()
{
unsigned int a,b,c,d;
cpuid(1, a,b,c,d);
return (c & 0x2000000);
}
```
When... |
Your program isn't complete. You need to implement the OS-expected entry point. In your case, that looks like it's calledWinMain.
|
Considering that the number can be really large, would it be safe to useunsigned long?
FWIW, I'm adding up all the microseconds from an apache log, thus the number can get really large.
|
Given that the maximum value you can store in anunsigned longon a 32 bits platform is around 4G, these 4G microseconds translate to only 71 minutes.
On a 64 bits platform (beware on Windows long is always 32 bits, even on Windows 64 bits), then you can count microseconds for up to 4G times 71 minutes. This is huge: a... |
I want to detect the kill signal of my program inorder to execute some C instruction before leaving my program. my program is running on linux
Is it possible to do that? If yes how I can do it?
|
You can register asignal handlerusingsigaction(). Note that you cannot handleSIGKILLorSIGSTOPthough.
|
I have a Buffer received as a result of recvfrom(). lets say,
char buffer[12] = "Hello 1";
I want to separate Hello and 1 and store them in different buffers so that one buffer has "Hello" in it and other buffer or an int variable has "1" stored in it.
In other words I want to separate contents of a buffer on the b... |
If there are only 2 words your idea will work. But there is a small error in your code.
Change the sscanf this way
```
sscanf (buffer,"%s %d",buff,&number);
```
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer... |
Tools which may helpErmine,Statifier, andjumpstart.
|
The following is a sample code, not the working one.
I just want to know the difference between*headand(*head)in pointers in C.
```
int insert(struct node **head, int data) {
if(*head == NULL) {
*head = malloc(sizeof(struct node));
// what is the difference between (*head)->next and *head->ne... |
*has lower precedence than->so
```
*head->next
```
would be equivalent to
```
*(head->next)
```
If you want to dereferenceheadyou need to place the dereference operator*inside brackets
```
(*head)->next
```
|
I'm trying to build and run some project from 3rd party sources for bare-metal(no OS)ARM Cortex M3.
I build it with arm-none-eabi-gcc(success) with newlib.
I run it under simulator of TI Code Composer Studio.
The problem:
When I run it, it fails into hard fault (entering into corresponding ISR) on the first call t... |
Are you using both ARM and Thumb? 'BLX label' calls the label, (using link register for return address), and changes to Thumb mode. Are you linking with the correct version of the library?
|
When terminating a string, it seems to me that logicallychar c=0is equivalent tochar c='\0', since the "null" (ASCII 0) byte is0, but usually people tend to do'\0'instead. Is this purely out of preference or should it be a better "practice"?
What is the preferred choice?
EDIT:K&Rsays: "The character constant'\0're... |
http://en.wikipedia.org/wiki/Ascii#ASCII_control_code_chart
```
Binary Oct Dec Hex Abbr Unicode Control char C Escape code Name
0000000 000 0 00 NUL ␀ ^@ \0 Null character
```
There's no difference, but the more idiomatic one is'\0'.
Putting it down ascha... |
My program reciveves a key from the keyboard. I want the shape to move left/right/up according to pressing the arrows on the keyboard.
This is the relevant part of the code:
```
case GLUT_KEY_LEFT :
{
horizon--;
glutPostRedisplay();
break;
}
```
However GLUT_... |
May be you define a callback function for keyboard actions usingglutKeyboardFunc.
To useGLUT_KEY_xxxyou should useglutSpecialFuncto set a callback.
|
My question is: How to printf the "pMessage","aiLength","szDataSize"?
```
EventInfo* pEventInfo
typedef struct {
char* pMessage;
SocketHeader* pSocketHeader;
PipeHeader* pPipeHeader;
} EventInfo;
typedef struct {
apr_uint32_t aiLength;
} PipeHeader;
typedef struct {
apr_uint... |
While I think @pilcrow's answer - using C99 format string conversion specifiers in<inttypes.h>- is probably the most elegant, theunsigned longtype is guaranteed to beat least32 bits, so you could simply use the%luspecifier with a cast:
```
printf("%lu\n", (unsigned long) value);
```
Which doesn't require C99. That's... |
This question already has answers here:Convert timeval to time_t(2 answers)Closed10 years ago.
How do I convert timeval to time_t? I'm trying to convert:
```
struct timeval tv;
time_t tm;
tm = (time_t)tv;
```
This is it?
|
timeval is defined as:
```
struct timeval {
time_t tv_sec; // seconds
suseconds_t tv_usec; // and microseconds
};
```
And time_t is defined as:
```
typedef long time_t;
```
The timeval structure is used to specify a time interval but the time_t is used to specify a time (the number of seconds since t... |
Im trying to code a C function that has a optional argument, and if that argument isn't "used", then it has a default value.
```
int DumpData(int a, int b, int c=0)
{
if(c != 0)
{
//stuff
}
//banana
}
/* Function Call */
DumpData(1, 2);
```
Is there any way to solve this issue ?
|
No, there's no way to do this in C. The best you can do is to have separate functions:
```
int DumpData(int a, int b)
{
return DumpDataABC(a, b, 0);
}
int DumpDataABC(int a, int b, int c)
{
...
}
```
Or, use C++ instead of C.
|
If we assign different handler to say SIGABRT, etc.. We might not be able to kill the process, conspicuously, it's not a good idea unless we can. So, the manual says SIGSTOP and SIGKILL cannot be blocked or ignored, does it mean that it must kill or stop the process no matter what handler you assign?
|
TheSIGSTOPandSIGKILLsignals cannot be caught or ignored. It is possible to set handlers for them usingsignal()orsigaction(), but those handlers will never be called, so there is no point in doing so.
|
```
#include <stdio.h>
double metersToFeet(double meters)
{
return meters / 0.3048;
}
int main()
{
printf("%u\n", (unsigned char)(char)(45.72 / 0.3048));
printf("%u\n", (unsigned char)(char)metersToFeet(45.72));
return 0;
}
```
This program outputs (on both GCC and Clang):
```
127
150
```
Why am I... |
The real answer (150) exceeds the range of achar(on a normal system) if it's signed. This conversion invokesundefined behaviour; the compiler is free to do whatever it likes.
From the C99 standard, 6.3.1.4:
When a finite value of real floating type is converted to an integer type other than _Bool,
the fractional ... |
Division by zero in a C program results in abnormal termination with the error messageFloating point exception (core dumped). This is unsurprising for floating point division, but why does it say this when integer division by zero occurs? Does integer division actually use the FPU under the hood?
(This is all on Linu... |
Does integer division actually use the FPU under the hood?
No, Linux just generates SIGFPE in this case too (it's a legacy name whose usage has now been extended). Indeed, the Single Unix Specificationdefines SIGFPEas "Erroneous arithmetic operation".
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.