question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I'm having some trouble with c code from a library that I use with Android NDK.
It works on the emulator, but not on a real device. It gives me a "libc - Fatal signal 11" (SIGSEGV)
I have traced the problem to a piece of code in the library, but I'm having trouble understanding what the second line does.
Here is th... |
The second line is invoking a function, via a function pointer namedtab. The function has the signature:
```
const char* f(const char*);
```
Suggest checking thatkeyandtab()are not NULL prior to callingtab().
|
What does this line of code will do.
pcm->card->number,pcm->deviceboth areint.
```
char str[16];
sprintf(str, "pcmC%iD%ip", pcm->card->number, pcm->device);
```
it is taken form android/kernel/sound/core/pcm.c.
|
As ofthe description ofsprintf()andfprintf(),%iis
The int argument is converted to a signed decimal in the style [-]dddd. The precision
specifies the minimum number of digits to appear; if the value being converted can be
represented in fewer digits, it will be expanded with leading zeros. The default precision
... |
When learning C I see thatprintfcan receive many arguments as it is passed.
And I don't know how C can implement a function like this, where the user can type as many parameters as the user wants. I have thought about pointers, too but still have no bright idea. If anyone has any ideas about this type of function, pl... |
You need to use va_args, va_list and the like.
Have a look at this tutorial.http://www.cprogramming.com/tutorial/c/lesson17.html
That should be helpful.
|
```
#include<stdio.h>
void main(){
int x,y,z;
x=y=z=1;
z=++x||++y&&++z;
printf("%d %d %d \n",x,y,z);
getch();
}
```
the output is coming as 2 1 1 ! i'm not able to get why...if we go by the precedence of the operators this can't be explained. Please help
|
Logicalor(||) introduces a sequence point. Its left side is evaluated. Then, if and only if that produced 0/false, the right side is evaluated.
In this case,++xcomes out to 2, so the right side is never evaluated. That, in turn, meansyandzremain as1.
|
Say I have attached gdb to a process and within the its memory layout there is a file and line number which I would like the memory address of. How can I get the memory address of line n in file x? This is on Linux x86.
|
```
(gdb) info line test.c:56
Line 56 of "test.c" starts at address 0x4005ae <main+37>
and ends at 0x4005ba <main+49>.
```
additionally with python you may be able to use the 'last' attribute fromSymbol-Tables-In-Pythonthis currently requires a very recent version of gdb from cvs, but i imagine will have general a... |
I was happily using VS2010 Premium version for a C/C++ coding project, and needed to add the C# components (long, irrelevant explanation on that). When I tried to go back and open up my existing C/C++ solution, i received the following VS2010 error: cannot open projectName.vcxproj because "it is not supported by this... |
I went back to repair/reinstall VS2010, and discovered the error: When I added the C# component, I did not want to re-download all of the other components already installed. But by leaving those items unchecked, apparently they were uninstalled, or at least made inaccessible. There is also the possibility that thos... |
I've written several very helpful excel add-ins using VBA. I'm using Excel for Mac 2011 Version 14.2.2 (120421). I'd like to sell the add-ins via a web site. Can I write the add-ins in Xcode or do I have to use C#?
|
FromMicrosoft Support:
In Office 2011 for Mac, there is no concept of add-ins. So using Excel Add-In is not possible...
You'll need to use VBA or AppleScript to emulate the same behavior.
|
I am new to graph theory, and so far I have learned only BFS and Disjoint sets in graph theory. If there is a cycle in a given, undirected, connected graph, can I find it using BFS
? My intention is to print all the vertices in the cycle. Thanks in advance.
|
Yes, if the graph is undirected, but it is very inefficient compared to DFS.
If a graph was a directed graph, you'd have to remember if you visited the node or not, and also how you got there. BFS, which searches by "levels" from the origin will not be compatible with these parameters.
|
This question already has answers here:Segmentation Fault when attempting to print value in C(3 answers)Closed3 years ago.
I'm very new to C, but have no idea why this program breaks. The program compiles and runs if I remove the lines that have to do withi, but if I assigni, I can no longer assign anything to*ptrwit... |
You leave the pointer with uninitialized value. So when you dereference it (*ptr), you access arbitrary place in memory, resulting in a segmentation fault.
Pointptrat something by assigning toptritself (not*ptr) an address of a variable (like&i) or some freshly allocated memory (likemalloc(sizeof(int))).
|
So I know that C++ has an Operator Precedence and that
```
int x = ++i + i++;
```
is undefined because pre++ and post++ are at the same level and thus there is no way to tell which one will get calculated first. But what I was wondering is if
```
int i = 1/2/3;
```
is undefined. The reason I ask is because there a... |
If you look at the C++operator precedence andassociativity, you'll see that the division operator is Left-to-right associative, which means this will be evaluated as(1/2)/3, since:
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same precedence, in ... |
I'm working on a C program which will be run in Linux and from inside Visual Studio 2010, and I'm looking for a regex library. GNU comes with a POSIX-compatible regex library, but Visual Studio, despite having C++ std::regex, doesn't have a C-compatible library. GNU has a Windows version of their library (http://gnu... |
The one library I've found that compiles with basically no effort, and is also the smallest, is:https://code.google.com/p/slre/. It's pretty basic but is good enough for my purposes. Thanks for the help, though.
|
I understand that Cocoa requires that windows be created/managed on the main thread. So, I'd like to have two or three windows with unique contexts, but I'd really prefer to draw to each of them from separate threads. Plus, a little bit of Google searching seems to indicate that rapidly context-switching on one thread... |
You might want to look at theCGLinterface for fast context switching, specifically:CGLSetCurrentContext. However, it may be more consistent to use themakeCurrentContextmethod forNSOpenGLContextin a Cocoa application.
|
I learned the ASCII value of '\0' is 0, and the ASCII value of 0 is 0x30, but when I try to print their ASCII value using printf, I get the same output:
```
printf("\'\\0\' : %d\n", '\0');
printf("\'\\0\' in hex : %x\n", '\0');
printf("0 : %d\n", 0);
printf("0 in hex: %x\n", 0);
```
output:
```
'\0' : 0
'\0' in hex... |
The ASCII character'0'is different than the number0. You are printing the integer0in your second pair ofprintfs instead of'0'.
Try this:
```
printf("'\\0' : %d\n", '\0');
printf("'\\0' in hex : %x\n", '\0');
printf("'0' : %d\n", '0');
printf("'0' in hex: %x\n", '0');
```
Also, you don't need to escape'inside string... |
Assume that I have some C code for a portable, non-visual library. The code relies mostly on CRT (there is no QT/DirectX/WinAPI etc. dependencies).
Is there a way I could use this code in a C# application? I know about Managed C++ and that'snotan acceptable way for me.
I thought of a C/C++ to C# converter that I cou... |
Why not temporarily compile the C++ as managed C++, to get a .net assembly, then use Reflector to decompile it into pure C#?
|
can anyone suggest a openCV method which extract connected components in a 8bit single channel frame? is it cvBlobs suitable for this?
In addition to this i want to use it in C code.
|
It seems thatcvFindContoursfunction can help you.
|
I have this code:
```
if(S_ISDIR(fileStat.st_mode)){
(*ls)[count++] = strdup(ep->d_name);
ep = readdir(dp);
} else{
(*ls)[count++] = strdup(ep->d_name);
ep = readdir(dp);
}
```
How can i append the string "DIR" to obtain something like:
```
if(S_ISDIR(fileStat.st_mode)){
(*ls)[count++] = "DIR "strdup(... |
There are several ways of achieving this: you could usestrcat, or if you need to make multiple modifications you could usesnprintf.
```
size_t len = strlen(ep->d_name);
// You need five characters for "DIR: ", and one more for the terminating zero:
(*ls)[count] = malloc(len+6);
strcpy((*ls)[count], "DIR: "); // ... |
I'm implementing right now some syscalls from unistd.h and fcntl.h (open, read, close, e.t.c)
Some of the require special flags and macros (O_CREAT, O_RDWR)
Is there a way to include only the flags and macros without the function definitions
from unistd.h and fcntl.h?
Thanks
|
Perhaps the-imacrosoption togccis what you are looking for.
-imacros FILEExactly like `-include`, except that any output produced by
scanning FILE is thrown away. Macros it defines remain defined.
This allows you to acquire all the macros from a header without
also processing its declarations.
|
Given an arbritary unix socket address, am I able to get the number of connections on it via a POSIX api call?
Or would I have to walk though the /proc filesystem?
|
I'll assume you mean the number of current connections on a port, not the total connection count over the lifetime of a socket fd which was my first thought. I'm afraid the most portable method is popen("netstat -n", "r") and try to parse it. POSIX gives us very little in the area of system/network administration tool... |
Is there a way to set all system processes other than my own process' threads to their own CPU without manually setting each pid.
I am using C on Fedora and would like to set this on program start not before.
|
cgroups(control groups) are aneffective way of partitioning system resources(even more than just CPUs). Also, another effective way of getting exclusive CPU access for a process is to leverage the scheduler -- give it higher priority than anything else.
If those aren't what you want, and you've decided that you real... |
Consider this code:
```
if(initscr() == NULL) ERROR("Cannot start ncurses mode.\n");
keypad(stdscr, TRUE);
cbreak();
int reply = getch();
if(reply == 'y')
printw("yes!\n");
else if(reply == 'n')
printw("no!\n");
else
printw("invalid answer!\n");
refresh();
... |
You callprintw()to print one of three messages, thenrefresh()to cause the message to be displayed. So far, so good.
You then immediately callendwin(), which (depending on your termcap/terminfo settings) will likely clear the screen.
Chances are the message is actually displayed; it just doesn't stay on the screen lo... |
I'm surprised string plus boolean has similar effect of ternary operation:
```
int apple = 2;
printf("apple%s\n", "s" + (apple <= 1));
```
Ifapple <= 1, it will print apple. Why does this work?
|
Because the condition evaluates to either 0 or 1, and the string"s"contains exactly one character before the 0-terminator. So"s" + boolwill evaluate to the address of"s"ifboolis false, and to one character behind that, the address of the 0-terminator if true.
It's a cool hack, but don't ever use code like that in ear... |
The following C code returns a "segmentation fault" error. I do not understand why it does not return the value 20. What is my error?
```
#include <stdio.h>
int main()
{
int* n;
*n = 20;
printf("%i\n",*n);
return 0;
}
```
|
You haven't allocated memory ton, so
```
*n = 20;
```
attempts to write unspecified memory.
Try
```
#include <stdlib.h>
int *n = malloc(sizeof *n);
/* use n */
free(n);
```
|
I need to compare an integer in a loop to the quotient of alongand along. in order to not do integer division, if I understand correctly do I need to convert one of the longs into a double?
```
long prime = primes[d];
int i = 1;
// "inputNumber / prime" should not be integer division, while it is now.
// How do I ... |
Why notwhile((i * prime) < inputNumber)instead? Alongmultiplied by anintresults in along...
|
I have the following code:
```
int i=1;
printf((i==1)?" ":" " "hello");
printf(" " "hello");
```
And I am astonished to see that the firstprintfonly gives a space as output and the secondprintfoutputs a space followed by the stringhello. I was expecting output like second one in case of first one. But is t... |
String literal joining is a lexical feature, which means this:
```
(i==1) ? " " : " " "hello"
```
is the same as this:
```
(i==1) ? " " : " hello"
```
It should now be pretty obvious why you get the result you get.
|
So we know that the standard doesn't force pointer sizes to be equal. (hereandhere) (and not talking about function pointers)
I was wondering how in reality that can be an issue. We know thatvoid *can hold anything, so if the pointer sizes are different, that would be the biggest size. Given that, assigning avoid **t... |
void *andchar *are guaranteed to have the same size.
void **is not guaranteed to have the same size aschar **(but very likey on your implementation they will).
(C99, 6.2.5p27) "A pointer to void shall have the same representation and alignment requirements as a pointer to a character type [...] Pointers to other t... |
For learning purposes, I wrote the following code snippet:
```
for(int i=0;i<10;i++)
{
for(int j = 0;j<5;j++)
{
//(i==j && i==3)? (goto found) : printf("stya here\n");
if(i==j && i==3){goto found;} else {printf("stay here\n");}
}
}
found:
printf("yes I am here");
```
But I wondered w... |
The?:operator is not replacement forif. It works only for expressions:condition ? expr1 : expr2where both sub-expressionsexpr1andexpr2are of the same type (and the whole expression then is of the same type).
gotois not expression, it is a statement.
|
in C or bash,
I was wondering how, if possible, do you obtain from inside an ssh session, the file descriptor to the pseudo terminal master responsible for getting input to that's session's slave(pts).
|
The shell process has no master file descriptor, only slave.
The shell's parent process (be it sshd or xterm or screen or whatever) creates a new master by callinggetpt(3)orposix_openpt(3). The function returns the master file descriptor. The parent process then obtains the slave file descriptor by calling a combinat... |
I compiled the following program with "gcc -fprofile-arcs -ftest-coverage test.c":
```
int main() {
int a = 1;
int b = 1;
a && b;
}
```
After running the program, an invocation of "gcov -bc test.c" reports that 50% of 4 branches were taken at least once. Why does gcov say the program has four branches, instead... |
Apparentlygcovis consideringa&&bto be the following:
```
if(a) { // branch 1
if(b) { // branch 2
1;
} else { // branch 3
0;
}
} else { // branch 4
0;
}
```
Though I'm fairly certain the actual CPU instructions will translate to a single branch.
|
I've got to parse a .txt file like this
```
autore: sempronio, caio; titolo: ; editore: ; luogo_pubblicazione: ; anno: 0; prestito: 0-1-1900; collocazione: ; descrizione_fisica: ; nota: ;
```
withfscanfin C code.
I tried with some formats infscanfcall, but none of them worked...
EDIT:
a = fscanf(fp, "autore: %s");... |
Generally speaking, trying to parse input withfscanfis not a good idea, as it is difficult to recover gracefully if the input does not match expectations. It is generally better to read the input into an internal buffer (withfreadorfgets), and parse it there (withsscanf,strtok,strtoletc.). Details on which functions a... |
I am trying out a C/C++ program, I want to know how much memory i am using due to heap and some other data structures. So how can I find out the amount of memory used by my various data structures?
I think that malloc operator should be overridden but I am not sure about the same.I am working on Linux and on Netbeans... |
You can use memory profilers for c++ like Valgrind as recommended in similar questions.
seethis
For netbeans IDE look atthis.
|
I've just read this snippet fromanother answer:
When you create a block with the^{}syntax...
I understand this syntax, and use it regularly, however I inferred from this that there might be other syntaxes that can be used for creating blocks. Are there? If there are, are there any advantages of the different syntaxe... |
If your question is about block literal syntax (the one used for anonymous functions), here is the general form
^ return type (arguments list) {expressions}
Based on the that, you can omit the return type
^ (arguments list) {expressions}
since it can be inferred from the return type. If there is no return value,vo... |
The following line of code is supposed to read a string, an int and two doubles separated by commas and store them in variables.
```
fscanf(f,"%[^,],%d,%Lf,%Lf",name,&id,&east, &north);
```
It works on my Visual Studio 2010 compiler and reads the right values. I've run the program on another machine on which I've go... |
%Lfis for typelong double, notdouble. On Microsoft compilers,long doublehas the same size and representation asdouble, so it happens to work, but your code is nonetheless invoking undefined behavior by using a mismatching format specifier. Use%lfwithdouble, or change the type tolong doubleif you want to use%Lf, and it... |
I have this function in C:
```
static Node* newNode(void* e){
Node n={e,NULL,NULL};
return &n;
}
```
And while compiling I get the following warning that I would like to understand why it happens:
```
warning: function returns address of local variable [enabled by default]
```
What kind of dangers are lurking behi... |
Local variables are destroyed when you return from a function. Accessing them after the function returned is undefined behavior, don't do this.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:How to find the sizeof(a pointer pointing to an array)Sizeof array passed as parameter
I have this code:
```
class total {
public:
void display(int []);
};
void total::display(int *arr)
{
int len = sizeof(arr)/sizeof(int);
c... |
sizeofof an array operand yields the size of the array butsizeofof a pointer operand yields the size of the pointer. Pointer and arrays are not the same in C/C++.
|
according documentation:
On success, the function returns the converted integral number as a
long int value. If no valid conversion could be performed, a zero
value is returned. If the correct value is out of the range of
representable values, LONG_MAX or LONG_MIN is returned, and the global
variable errno ... |
You need to pass a real pointer address if you want error checking, so you can distinguish 0 values arising from"0"and similar from 0 values arising from"pqr":
```
char *endptr;
errno = 0;
long result = strtol(str, &endptr, 10);
if (endptr == str)
{
// nothing parsed from the string, handle errors or exit
}
if ((... |
Is it valid C to declare a struct and define values enclosed in {}?
```
struct name new_name[] {
{"value1"},
{"value2"},
{"value3"},
}
```
Where:
```
struct name {
union {
char *value1;
} n_u;
char *value2;
}
```
|
What you've posted is invalid because it's missing an equals sign before the initializer (and also trailing semicolons). Otherwise, it's legal but somewhat hard to read because it doesn't initialize every field, and doesn't use a full set of braces. In a fully-braced initializer, you'll have a pair of braces around th... |
Is there a way to detect in compilation-time, if a function is built-in on compiler?
e.g, something like this:
```
#ifndef ITOA_FUNCTION
#define itoa myitoaimplementation
#endif
```
Thanks in advance.
|
No, there's not anything direct. About the best you can do is guess from things like the platform, compiler version, etc.
In most cases, I'd prefer one of two other routes though. One is to just give your own implementation a name different from what the compilers use, and always use it whether the compiler provides ... |
Is there a way to set all system processes other than my own process' threads to their own CPU without manually setting each pid.
I am using C on Fedora and would like to set this on program start not before.
|
cgroups(control groups) are aneffective way of partitioning system resources(even more than just CPUs). Also, another effective way of getting exclusive CPU access for a process is to leverage the scheduler -- give it higher priority than anything else.
If those aren't what you want, and you've decided that you real... |
Consider this code:
```
if(initscr() == NULL) ERROR("Cannot start ncurses mode.\n");
keypad(stdscr, TRUE);
cbreak();
int reply = getch();
if(reply == 'y')
printw("yes!\n");
else if(reply == 'n')
printw("no!\n");
else
printw("invalid answer!\n");
refresh();
... |
You callprintw()to print one of three messages, thenrefresh()to cause the message to be displayed. So far, so good.
You then immediately callendwin(), which (depending on your termcap/terminfo settings) will likely clear the screen.
Chances are the message is actually displayed; it just doesn't stay on the screen lo... |
I'm surprised string plus boolean has similar effect of ternary operation:
```
int apple = 2;
printf("apple%s\n", "s" + (apple <= 1));
```
Ifapple <= 1, it will print apple. Why does this work?
|
Because the condition evaluates to either 0 or 1, and the string"s"contains exactly one character before the 0-terminator. So"s" + boolwill evaluate to the address of"s"ifboolis false, and to one character behind that, the address of the 0-terminator if true.
It's a cool hack, but don't ever use code like that in ear... |
The following C code returns a "segmentation fault" error. I do not understand why it does not return the value 20. What is my error?
```
#include <stdio.h>
int main()
{
int* n;
*n = 20;
printf("%i\n",*n);
return 0;
}
```
|
You haven't allocated memory ton, so
```
*n = 20;
```
attempts to write unspecified memory.
Try
```
#include <stdlib.h>
int *n = malloc(sizeof *n);
/* use n */
free(n);
```
|
I need to compare an integer in a loop to the quotient of alongand along. in order to not do integer division, if I understand correctly do I need to convert one of the longs into a double?
```
long prime = primes[d];
int i = 1;
// "inputNumber / prime" should not be integer division, while it is now.
// How do I ... |
Why notwhile((i * prime) < inputNumber)instead? Alongmultiplied by anintresults in along...
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Why doesn't a+++++b work in C?3 Plus between two variables in c
I tried searching for this but couldn't find any results.
A code withc=a+++++bfails to compile (gcc) whereas forc=a++ + ++b, it compiles successfully.c=a+++ ++balso works.c=a... |
Since++is a token, the parser interpretsa+++++bthe same asa ++ ++ + b, which is not the same asa ++ + ++ b!
|
I have a binary file, that was written in C, which contains a long stream of numbers.
First it contains subsequently 4 times an int (so the first 16 bytes are 4 ints) and then it contains doubles (I assume every 8 bytes a new double).
There are no spaces at any point or anything else. Now I need to read the data with... |
```
using (BinaryReader br = new BinaryReader(File.Open("file", FileMode.Open)))
{
int a = br.ReadInt32();
int b = br.ReadInt32();
int c = br.ReadInt32();
int d = br.ReadInt32();
double e = br.ReadDouble();
double f = br.ReadDouble();
...
}
```
|
My scenario is as follows:(C++)
In char a[10], the array a[] has elements (numbers) like '1','2','3' etc....
Say a[0] = '1';a[1] = '2';a[2] = '3';
Now a[] is storing 3 characters '1', '2' and '3'.I want to store this into an int as 123 (An integer 123).
How to achieve this in C++ ?
|
a[3] = 0is a must. If your string isn't null-terminated, most methods won't work.
After that, it's a simplenumber = atoi(a)
|
I am new to Gtk and want to do simple drawing of shapes like circles and rectangles. I was looking at thegnome tutorialand the hello word example. However the curves section is undocumented. I was wondering if someone could point me in the right direction as to what should I look at, and maybe if I need to include som... |
The preferred drawing API in GTK 2 and 3 is Cairo. But if you need to develop a diagram program, with nodes that can react to events, you will need also to use a canvas, likeGooCanvas.
|
in the following code:
```
void fusioneArray(int v[], int vL, int w[], int wL[], int *fusione)
{
int i,j,temp;
int k=0;
printf("%d",wL+vL);
for(i=0;i<vL;i++)
{
fusione[k]=v[i];
k++;
}
for(j=0;j<wL;j++)
{
fusione[k]=w[j];
k++;
}
}
int main()
{
int v[5]={1,2... |
BecausewLis a pointer in your code, thus you're doing pointer arithmetics instead of a standard integer arithmetics :
wL+vL = wL + vL*sizeof(int)
Since aintis 4-bytes on most platforms yourwL+vLbecomes5+5*4 = 25, which is the result you get. Simply replaceint wL[]with the correctint wLand you'll have the desired beh... |
Is there any command ingdbby which one can apply breakpoint at the start of each function in a.Cfile.
I need this as i have a very bigCfile which i need to debug and it contains more than 100 functions and i need to find all the functions called during run time.
|
```
rbreak file:regex
```
If you look at this page :http://sourceware.org/gdb/download/onlinedocs/gdb/Set-Breaks.html#Set-Breaks
Look also at the past thread :gdb, set breakpoint on all functions in a file
|
I am using Ubuntu 10.10 as VM and am new to it. Until recently i could easily compile C programs from the terminal. However, as i try to compile them now it gives a message as:
```
/usr/bin/ld: cannot find -lc
collect2: ld returned 1 exit status
```
I have searched for it over the net but could not figure out what ... |
Installing the necessary tools should solve your problem. Try:
```
sudo apt-get install build-essential
```
|
i got some legacy code using:nonblockingsocket,selectfor timeout,read(2) andwrite(2).
Now it occasionally failed due to select/1024 fd limits. so i need to replace the select.
It seems RCVTIMEO and SNDTIMEO can also check timeout but they work for blocking mode, and it impacts too much to change from non-blocking to ... |
poll()is essentially a drop-in replacement for usingselect(), but does not have the 1024 file descriptor limit. You will have to change your code slightly to create an array ofstruct pollfdstructures instead of usingfd_sets, but the overall structure of the code should not have to change.
|
Suppose I have a program written in C/C++ and I'd like to find out how much of memory was used for data (heap, stack) and how much of memory was used for code (libs, executable files, etc).
I have once measured the dynamic memory space used using 'valgrind' but I don't think is has a feature to profile memory footpri... |
Your development environment should have some sort of linker options. Generally in such you can instruct it to create a link map. The information you are looking for is likely to be in the link map, or calculable based on the information in the link map.
|
I'm porting some (working) code from Linux to Windows 8. I'm using DDK.
```
typedef struct {
unsigned int test1;
unsigned int test2;
} settings;
const settings vp_settings = {
.test1 = 1,
.test2 = 1
};
```
What is different about the Windows DDK compiler and GCC that makes this invalid? The error I'... |
Q: What's wrong with (vanilla):
```
const settings vp_settings = {
1, /* test1 */
1 /* test2 */
};
```
PS:
How to rewrite C-struct designated initializers to C89 (resp MSVC C compiler)
This looks like a C99 thing ... and AFAIK MSVS doesnotfully support C99...
|
Withprintf(), I can use%hhuforunsigned char,%hifor ashort int,%zufor asize_t,%txfor aptrdiff_t, etc.
What conversion format specifier do I use for a_Bool? Does one exist in the standard?
Or do I have to cast it like this:
```
_Bool foo = 1;
printf("foo: %i\n", (int)foo);
```
|
There is no specific conversion length modifier for_Booltype.
_Boolis anunsignedinteger type large enough to store the values0and1. You can print a_Boolthis way:
```
_Bool b = 1;
printf("%d\n", b);
```
Because of the integer promotions rules,_Boolis guaranteed to promote toint.
|
My program contains the following code.
```
pthread_t PThreadTable[32];
for (i=1; i<P; i++) // Checked with P = 4
{
long i, Error;
printf( "pthread_create %d!\n", i );
Error = pthread_create(&PThreadTable[i], NULL,
(void * (*)(void *))(SlaveStart), NULL);
if (Erro... |
Its because you redeclare variableiinside the loop. The variable inside the loop is being used and it contains garbage value. That is why, the expression&PThreadTable[i]points to a wrong address and you get a segmentation fault.
|
Here is the normal code :
```
if(a==b)
printf("equal");
else if(a>b)
printf("bigger");
else
printf("smaller");
```
My teacher want to change if/else to this structure:
```
printf("%s",a>b?"bigger":"smaller")
```
of course, this just a simple and standard. and I d... |
It's not generally a good idea to use nested conditional operators, but it can be done:
```
printf("%s", a==b ? "equal" : (a > b ? "bigger" : "smaller"));
```
|
Why do I get error in this code?Even if i do not link but only compile still it gives an error.why does not compiler consider the possibility of it being present in another file?
Could anyone explain how typedef statement is treated by compiler.
Thanks in advance
```
typedef struct p* q;
int main()
{
... |
The “struct p” outside main and the “struct p” inside main are different types because they are defined in different scopes. If you put both declarations outside main or both inside main, the compiler will accept it.
When you define something inside a function, you are saying “Here is a definition I am using just ins... |
I have a very simple piece of code and it reads characters from files. If the indexyiterates from low to high, everything works. But, if it iterates from high to low (the commented line), it gives me the seg fault problem. Could someone explain why this happens? Thank you!
```
void read_ct_from_file( unsigned char** ... |
size_tis unsigned, so your loop will aftery = 0continue withmax_unsignedwhich is >= 0.
|
I am trying to train a Hidden Markov Model (HMM) using theGHMM library. So far, I have been able to train both a discrete model, and a continuous model using a single Gaussian for each of the states.
There are really good examples on how to do ithere.
However, I would like to train a continuous HMM with asinglecovar... |
So, I have found this great package in C that has an HMM implementation exactly the way I wanted:Queen Mary Digital Signal Processing Library. More specifically, the HMM implementation is inthese files. So, no need to use GHMM lib anymore.
|
pthread_self()is to get your own thread id. It doesn't seem like you can get the thread id of the thread which spawned you unless it was given to you during spawning. Or is there a way?
|
No, all threads are equal in POSIX threads, there is no hierarchy. Even the thread that executesmainhas no special role and can be terminated without effecting the others.
|
I am trying to do the following:
```
#define mkstr(str) #str
#define cat(x,y) mkstr(x ## y)
int main()
{
puts(cat(\,n));
puts(cat(\,t))
return 0;
}
```
both of theputsstatements cause error. As\nandnboth are preprocessor tokens I expected output them correctly in thoseputsstatements, but Bloodshed/DevC++ ... |
The preprocessor uses a tokenizer which will require C-ish input. So even when stringifying you cannot pass random garbage to a macro. ==> Don't make your preprocessor sad - it will eat kittens if you do so too often.
Actually, there is no way to create"\n"via compile-time concatenation since"\\" "n"is a string consi... |
in Linux kernel source code, I find below code:
```
h++;
pending >>= 1;
```
It is part of__do_softirq(void). But what does ">>=" mean? Why isn't it ">>" as I remember?
Thanks!
|
It simply does
```
pending = pending >>1;
```
In short it divides by 2 an unsigned int.
That's the same construct than+=,/=, etc.
It's not justpending >>1as you remember because that wouldn't store the result of the shift operation in the variable.
|
Using (I think) Visual basic / studio I want to make a bar to go at the top of my screen which would display a webpage.
Before I start trying to code it, is this concept possible (that the bar would dock at the top of the screen and other windows would change to fit around it.)
Thanks - Ryan
|
Sure, you would probably need to create it as a Windows Shell plugin.
|
Okay so let's say I have class A...
CLASS Ahas a method that gets called as soon as the user makes an in app purchase.
```
-(void) didMakePurchase { ... }
```
(VIEW CONTROLLER) CLASS Bis the View Controller for the current scene. Inside class B I have a function that creates a UIAlertView that basically thanks the... |
Post anNSNotificationin class A, and in class B add an observer to this notification
|
How do I compile and executeRedis ziplist.cas individual executable ?
I want to execute ziplist.c main function ONLY.
|
You can use the following command:
```
gcc -std=c99 -O2 -DZIPLIST_TEST_MAIN ziplist.c zmalloc.c util.c sds.c adlist.c
```
Note: it will use the default system allocator.
|
Suppose I have a program written in C/C++ and I'd like to find out how much of memory was used for data (heap, stack) and how much of memory was used for code (libs, executable files, etc).
I have once measured the dynamic memory space used using 'valgrind' but I don't think is has a feature to profile memory footpri... |
Your development environment should have some sort of linker options. Generally in such you can instruct it to create a link map. The information you are looking for is likely to be in the link map, or calculable based on the information in the link map.
|
I'm porting some (working) code from Linux to Windows 8. I'm using DDK.
```
typedef struct {
unsigned int test1;
unsigned int test2;
} settings;
const settings vp_settings = {
.test1 = 1,
.test2 = 1
};
```
What is different about the Windows DDK compiler and GCC that makes this invalid? The error I'... |
Q: What's wrong with (vanilla):
```
const settings vp_settings = {
1, /* test1 */
1 /* test2 */
};
```
PS:
How to rewrite C-struct designated initializers to C89 (resp MSVC C compiler)
This looks like a C99 thing ... and AFAIK MSVS doesnotfully support C99...
|
Withprintf(), I can use%hhuforunsigned char,%hifor ashort int,%zufor asize_t,%txfor aptrdiff_t, etc.
What conversion format specifier do I use for a_Bool? Does one exist in the standard?
Or do I have to cast it like this:
```
_Bool foo = 1;
printf("foo: %i\n", (int)foo);
```
|
There is no specific conversion length modifier for_Booltype.
_Boolis anunsignedinteger type large enough to store the values0and1. You can print a_Boolthis way:
```
_Bool b = 1;
printf("%d\n", b);
```
Because of the integer promotions rules,_Boolis guaranteed to promote toint.
|
My program contains the following code.
```
pthread_t PThreadTable[32];
for (i=1; i<P; i++) // Checked with P = 4
{
long i, Error;
printf( "pthread_create %d!\n", i );
Error = pthread_create(&PThreadTable[i], NULL,
(void * (*)(void *))(SlaveStart), NULL);
if (Erro... |
Its because you redeclare variableiinside the loop. The variable inside the loop is being used and it contains garbage value. That is why, the expression&PThreadTable[i]points to a wrong address and you get a segmentation fault.
|
Here is the normal code :
```
if(a==b)
printf("equal");
else if(a>b)
printf("bigger");
else
printf("smaller");
```
My teacher want to change if/else to this structure:
```
printf("%s",a>b?"bigger":"smaller")
```
of course, this just a simple and standard. and I d... |
It's not generally a good idea to use nested conditional operators, but it can be done:
```
printf("%s", a==b ? "equal" : (a > b ? "bigger" : "smaller"));
```
|
Why do I get error in this code?Even if i do not link but only compile still it gives an error.why does not compiler consider the possibility of it being present in another file?
Could anyone explain how typedef statement is treated by compiler.
Thanks in advance
```
typedef struct p* q;
int main()
{
... |
The “struct p” outside main and the “struct p” inside main are different types because they are defined in different scopes. If you put both declarations outside main or both inside main, the compiler will accept it.
When you define something inside a function, you are saying “Here is a definition I am using just ins... |
I have a very simple piece of code and it reads characters from files. If the indexyiterates from low to high, everything works. But, if it iterates from high to low (the commented line), it gives me the seg fault problem. Could someone explain why this happens? Thank you!
```
void read_ct_from_file( unsigned char** ... |
size_tis unsigned, so your loop will aftery = 0continue withmax_unsignedwhich is >= 0.
|
I am trying to train a Hidden Markov Model (HMM) using theGHMM library. So far, I have been able to train both a discrete model, and a continuous model using a single Gaussian for each of the states.
There are really good examples on how to do ithere.
However, I would like to train a continuous HMM with asinglecovar... |
So, I have found this great package in C that has an HMM implementation exactly the way I wanted:Queen Mary Digital Signal Processing Library. More specifically, the HMM implementation is inthese files. So, no need to use GHMM lib anymore.
|
pthread_self()is to get your own thread id. It doesn't seem like you can get the thread id of the thread which spawned you unless it was given to you during spawning. Or is there a way?
|
No, all threads are equal in POSIX threads, there is no hierarchy. Even the thread that executesmainhas no special role and can be terminated without effecting the others.
|
I am trying to do the following:
```
#define mkstr(str) #str
#define cat(x,y) mkstr(x ## y)
int main()
{
puts(cat(\,n));
puts(cat(\,t))
return 0;
}
```
both of theputsstatements cause error. As\nandnboth are preprocessor tokens I expected output them correctly in thoseputsstatements, but Bloodshed/DevC++ ... |
The preprocessor uses a tokenizer which will require C-ish input. So even when stringifying you cannot pass random garbage to a macro. ==> Don't make your preprocessor sad - it will eat kittens if you do so too often.
Actually, there is no way to create"\n"via compile-time concatenation since"\\" "n"is a string consi... |
in Linux kernel source code, I find below code:
```
h++;
pending >>= 1;
```
It is part of__do_softirq(void). But what does ">>=" mean? Why isn't it ">>" as I remember?
Thanks!
|
It simply does
```
pending = pending >>1;
```
In short it divides by 2 an unsigned int.
That's the same construct than+=,/=, etc.
It's not justpending >>1as you remember because that wouldn't store the result of the shift operation in the variable.
|
Using (I think) Visual basic / studio I want to make a bar to go at the top of my screen which would display a webpage.
Before I start trying to code it, is this concept possible (that the bar would dock at the top of the screen and other windows would change to fit around it.)
Thanks - Ryan
|
Sure, you would probably need to create it as a Windows Shell plugin.
|
Okay so let's say I have class A...
CLASS Ahas a method that gets called as soon as the user makes an in app purchase.
```
-(void) didMakePurchase { ... }
```
(VIEW CONTROLLER) CLASS Bis the View Controller for the current scene. Inside class B I have a function that creates a UIAlertView that basically thanks the... |
Post anNSNotificationin class A, and in class B add an observer to this notification
|
How do I compile and executeRedis ziplist.cas individual executable ?
I want to execute ziplist.c main function ONLY.
|
You can use the following command:
```
gcc -std=c99 -O2 -DZIPLIST_TEST_MAIN ziplist.c zmalloc.c util.c sds.c adlist.c
```
Note: it will use the default system allocator.
|
```
static struct ipv6_devconf ipv6_devconf_dflt __read_mostly = {
.forwarding = 0,
.hop_limit = IPV6_DEFAULT_HOPLIMIT,
.mtu6 = IPV6_MIN_MTU,
};
static int __net_init addrconf_init_net(struct net *net)
{
struct ipv6_devconf *dflt;
dflt = &ipv6_devconf_dflt;
kfree(dflt);
}
``... |
No—it doesn't make sense to free memory outside the heap, becausekfree()only works to free up memory in the context ofkmalloc()ed chunks!
Timeline:
Committed in January 2008when the IPv6 devconfs for namespaces came into being.Noticed on linux-netdev in August 2008, to no fanfare.Pointed out again on the LKML in 201... |
I have a Windows process that runs in the background and periodically backs up files. The backup is done by uploading the file to a server.
During the backup, I don't want to lock any other application out of writing to or reading from the file; if another applications wants to change the file, I should stop the uplo... |
You may be interested inVolume Shadow Copy.
|
I use fread to read into a char buffer.
```
char buffer[50];
int nbytes = fread(buffer, 1, 50, fp);
```
The file I read from contains exactly the wordHello, i.e. 5 bytes.
In the above example,nbytesequals 6. Why?
Additionally, reading from a zero-byte file (i.e. it's empty) returns 0.
|
My guess is that whatever wrote to the file you are reading either included a newline (if it's a text file) or a 0 byte after the string. If you are on unix, run the following command:
```
od -c filename
```
Which will print the entire contents of the file including non-printables.
You can also run:
```
wc --byte... |
When I try to compile my program on ubuntu using gcc, i get these errors:
main.c:(.text+0x162): undefined reference tojson_parse'
main.c:(.text+0x182): undefined reference tojson_value_free'
However, these functions are included in a file called json.h, which I import in main.c and which I include in my gcc comman... |
You should not compile the "json.h" header. The undefined reference isnota compiler error, it's alinker error. It means you have either not compiled the file containing json_value_free to your code, or haven't linked to the library containing it. You should do either action instead of trying to compile the header file... |
In C I want a function like this:
```
bool RemoveFirstIndex(char* inArray[])
```
which goes in and takes out the very first element in that array.
e.g.
```
inArray = "Hello\o", "How\o", "Are\o"
RemoveFirstIndex(inArray)
inArray = "How\o", "Are\o"
```
Not sure how to go about it.
I get the idea that I would have ... |
Why remove the first element or create a new array?
Just can just increment your pointer so it points to the next item in the array.
```
char **newArray = inArray + 1;
```
newArrayis valid as long asinArrayis.
|
Probably I'm just too dump for googling, but I always thought char arrays get only null terminated by an literal initialization (char x[]="asdf";) and got a bit surprised when I saw that this seems not to be the case.
```
int main()
{
char x[2];
printf("%d", x[2]);
return 0;
}
```
Output: 0
Shouldn't an... |
You are accessing an uninitialized array outside its bounds. That's doubleundefined behavior, anything could happen, even getting0as output.
In answer to your real question: Only string literals getnull-terminated, and that means thatchar x[]="asdf"is an array of5elements.
|
suppose my app code looks like this:
```
#include <stdio.h>
int global_var;
void change_var(){
global_var++;
}
int main(void){
change_var();
retrun 0;
}
```
Now, can You please tell me, if there is any possibilty to accessglobal_varin dtrace script and print it ?
Best regards
|
You can, but you have to know the variable's address. Your D would resemble
```
self->kp = (int *) copyin(<address>, sizeof (int));
printf("global_var = 0x%d\n", *self->kp)
```
|
I'm using freopen for a GUI application using my shared library such that I can redirect debug msgs from stdout to a file
I have been using code based on a snippet from the C++ reference site:
```
/* freopen example: redirecting stdout */
#include <stdio.h>
int main ()
{
freopen ("myfile.txt","w",stdout);
print... |
No, not in pure C. If you can assume a specific system (e.g. POSIX) there probably are options.
But frankly,freopenis IMO a hack, only needed to be compatible with prewritten code. If you're writing new code you should instead pass theFILE *to the relevant functions and usefprintfinstead ofprintf.
|
Doesprintfoccupy memory in the stack?
```
printf("Hello world");
```
Does"Hello world"have a constant address?
Please help me understand.
EDIT:
Is the argument we are passing for theprintfis stored in a local pointer variable.
If I use an array to store a 50 string literals it takes stack memory but if Ii use the... |
String literals, which is what"Hello world"is, occupy memory, but not on the stack, but in a read-only static segment. Other thanread-only memory, the rest are implementation details.
It's not necessary that identical string literals occupy the same memory (so the address is not guaranteed to be constant), but they m... |
In C, a pointer contains the memory location of another variable. Are pointer variables stored on the stack or on the heap?
|
A pointer is just a variable. Think of it as an integer that holds a memory location, so if you have:
```
int main(...) {
char *ptr = malloc( 100 );
...
}
```
thenptris a four- or eight-byte value on the stack that contains the memory location of a 100-byte buffer allocated from the heap. Thememoryitself is ... |
Given two sorted arrays of integers,aandb, and an integerc, I have to findi,jsuch that:
```
a[i] + b[j] <= c
```
anda[i] + b[j]is large as possible.
The best solution I can think of is inO(nlogn) time, taking every integer from first array and finding the lower bound of "c-a[i]".Can anyone suggest me a better way t... |
Thinking a bit about it, then you could ask yourself:"Is it necessary, each time, to search in the sorted b-array for successive values from a[]?"
|
```
void say(char msg[])
{ // using pointer to print out the first char of string
printf("%c\n", *msg);
}
void say(char msg[])
{ // using pointer to print out the memory address of the first char of string
printf("%p\n", msg);
}
void say(char msg[])
{ // using pointer to print out the whole str... |
%swill interpret the address ofmsgas the base addresss of a C string, which is a NULL terminated ('\0') sequence of bytes, and therefore the printf with the%swill take the base address ofmsgand print the character equivalent of each byte starting frommsgand proceeding until it does not encounter a NULL character.
|
I'm writing an application which check for my usb device and if the device is avialable make a dial-up connection. I useRasdialto establish the connection. Unfortunately if I remove the USB cable the connection is not getting disconnected or notified to the user. So here
I'm in a situation to check for thedevice remo... |
Your window can handle theWM_DEVICECHANGEbroadcast message to tell when something has changed. If you need more detailed information, useRegisterDeviceNotification().
Using the system notification area has no bearing on your ability to use these methods. They all require a window to send the notifications to, but it ... |
I am working on an embedded system. Our platform is 32-bit sotime_tsize is 32-bit.
For now I want to send a struct to a Windows 7 computer as achararray.
One of fields of my struct istime_t.
I can't change struct.
So I must send time value to Windows Machine with a 32-bit variable and when char array arrived I must ... |
see:time, _time32, _time64 documentation
Both start at January 1, 1970. You only have to worry about endianness when sending it as chars.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Alternative to itoa() for converting integer to string C++?How to convert a number to string and vice versa in C++Append an int to a std::string
I want to convert integer to string, any one help me for these conversion?
```
itoa(*data->us... |
For C++, usestd::stringstreaminstead.
```
#include <sstream>
//...
std::stringstream ss;
ss << *data->userid;
std::string userId = ss.str();
```
orstd::to_stringif you have access to a C++11 compiler.
|
How do I setup SDL to work in C?
What I mean is without classes, in pure C. I have seen few projects in C that use SDL, but when I try to set it up or download, there is only C++ version. Could you please guide me how to install SDL for C in Mac (Xcode) or Windows environment?
Edit: I know that SDL is written in C, ... |
SDL is a C library, so yes, you can use it with 'pure C'.
|
I'm trying to understand the "events" pointer in epoll_wait. When epoll_wait returns, does this pointer point to some memory (not allocated by the user) where all the events structures are present? Or do we have to allocate memory to this pointer and then pass the pointer so that the events will get filled up in that ... |
Have you looked at the example in e.g. theepoll(7)manual page? You need to provide the actual event array, either as a proper array as in the example, or by allocating of the heap (and freeing it later).
|
I need to write a program that takes input line at a time and outputonly the linesthat have two tokens. Assume input is no longer than 50 bytes. I used fgets to capture one line at a time and used sscanf to grab token at a time and see if it returns 2. However, it doesn't seem to work. Can someone suggest how to d... |
Do this -
```
number = sscanf(buff, "%s %s", token, token);
```
|
I'm just starting playing with some programming for OSX, and trying to create a simple command line app but I can't seem to find a good guide. Basically I want to know how to get some user input for example ask the user their age etc.
|
You're in luck; OS X provides a manual page on all (nearly all?) standard C functions; the only trouble is knowing which function provides the services you're looking for. Thefgets()functionis probably best for reading a line-at-a-time. You'll use it something like this:
```
char buffer[MAXLINE];
if (fgets(buffer, MA... |
Almost every pseudorandom generator in C/C++ (Mersenne, ...) uses some kind of internal state, usually a short vector of bytes. My question is, when such a random generator is used and shared in a multithreaded environment is it "much" better to have it thread-safe or letting "race conditions" to occur can only increa... |
Letting "race conditions" occur can mess up everything. Technically, adata raceis undefined behaviour, so it could order pizza.
But even if that doesn't happen, the internal state is likely to get corrupted and all important properties of the random sequence will just be lost. You can no longer guarantee uniformity, ... |
I am using the GCC compiler but I want the to code the actually run after compilation. Is there a flag I can use for this? Right now I am just doing
```
gcc code.c
```
There is no code.exe being generated...
|
The file created by default is called a.out. If you want to name it code.exe, the correct line should begcc -o code.exe code.c
|
I am a little bit confused about the difference between
```
leal -4(%ebp), %eax
```
and
```
movl -4(%ebp), %eax
```
Can someone explain this to me?
|
LEA(load effective address) just computes theaddressof the operand, it does not actually dereference it. Most of the time, it's just doing a calculation like a combined multiply-and-add for, say, array indexing.
In this case, it's doing a simple numeric subtraction:leal -4(%ebp), %eaxjust assigns to the%eaxregister ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.