question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
Consider this little program:
```
#include <stdio.h>
int main()
{
char c = 0xFF;
printf("%d\n", c);
return 0;
}
```
Its output is-1, as expected (consideringcharis signed in my
system). What I'm trying to do is to make it print255. This is of
course a simplification of the real situation, where I can't ... |
cis being promoted using signed promotion rules. Castcto unsigned to use unsigned promotion.
```
printf("%u\n", (unsigned char)c);
```
Unsigned char will be promoted to unsigned int.
|
What is the difference between
```
char *a[10];
```
and
```
char *(a[10]);
```
I've always used the first for an array of char pointers, but now I've found code used the second.As I was not sure if it was the same thing, I printed sizeof() both and both return 80 (64bit OS) so I'm inclined to believe both are the ... |
The two are equivalent and stand for a 10-element array of pointers tochar.
Contrast withchar (*a)[10], which is a pointer to a 10-element array ofchar.
If in doubt, one could usecdeclto unscramble C declarations. On Unix it's usually available as a command-line tool. There's also anonline version.
|
What happens when I use different succesive calloc functions over the same pointer?
```
int *ptr;
ptr = (int *) calloc(X, sizeof(int));
ptr = (int *) calloc(Y, sizeof(int));
ptr = (int *) calloc(Z, sizeof(int));
```
Where X,Y,Z are three distinct values.
|
You will lose the connection to the previously allocated memory and you will no longer be able to free it - a memory leak
|
I have a issue with basic typecasting.
```
#include<stdio.h>
int main()
{
printf("%.22f",0.30);
return 1;
}
```
The output I am getting is 0.2999999999999999888978
Why is 0.3 converted to a lesser value
Any help much appreciated
Nandish
|
This is because0.30cannot be exactly represented in binary floating-point.
Internally, only an approximation to0.30can be stored. Therefore, when you print it all out, you'll get a slightly different number.
http://en.wikipedia.org/wiki/Floating_point
|
I need a simple (LRU) cache which should run in-process. I found memcached, which looks great but there does not seem to be an easy way to host it in-process. I don't need a distributed cache, just a simple key/value store and some kind of LRU behaviour and some nice allocator to limit fragmentation, as the entry size... |
I hate to answer this way, but it would be fairly simple to implement yourself.
Allocator. Usemallocandfree. Theydowork, and they work well. This also makes it easier to interface with the rest of your program.Mutex -> hash table, tree, or trie. You can use a linked list to track LRU. Don't try to do fancy lockl... |
Please note that, I don't have any control over the target file. Some other process is writing that file. I just want to copy the file when other process completes the write operation.
I was wondering, how i can check the write operation on a file ?
Thanks !
|
TryF_NOTIFYargument tofcntl.
Or you can tryinotifyif you know that you have a Linux kernel >= 2.6.13. I found anarticle in Linux Journalwhich describes how to use it.
|
I have a C string that I want to use to open that file. How do I determine if the file exists?
|
Use the function called access()
```
if(access(file_path, F_OK)==0)
//file exists
else
// file does not exists
```
|
How is it possible to use Windows thread pools from plainC, or isC++required? Is it OK to use them with MinGW?
|
TheThread Pool APIis a C API, it can be used either in C or C++. Yes, it's ok to use them with MinGW—MinGW uses the same C runtime library that Microsoft's compilers use (unlike Cygwin, which uses the GNU C library).
|
I know the syntax for writing a case break statement, but I'm wondering if this is allowed:
CODE:
```
case 'p':
{
printf("Give number: ");
scanf("%d, &int_1);
if int_1=5;{
printf("Played: you win");
}
break;
}
```
Basically I'm just wondering if this is something that's possible to d... |
Yes it's allowed. But you also forgot the(parentheses)around yourif:
```
if int_1=5;{
```
should be:
```
if (int_1 == 5){
```
So if it wasn't compiling, this is the reason.
|
I saw the snippet below somewhere online. The following program doesnt print "hello-out". The reason I feel is because before it is actually flushed to the console from the buffer,
```
#include <stdio.h>
#include <unistd.h>
int main()
{
while(1)
{
fprintf(stdout,"hello-out"... |
You should put\nat the end of the string to have it flushed, or usefflushto force it out.
|
I want to perform a HTTP POST and/or PUT (using libcurl) with the request being compressed using GZIP. I haven't been able to find any native support for this in libcurl, and am wondering if I just haven't found the correct documentation or if there really is no support for this? (ie. Will I have to implement my own ... |
HTTP has no "automatic" or negotiated compression for requests, you need to do them explicitly by yourself before sending the data.
Also, I disagree with Aditya who provided another answer (judging my bias it's not that strange) but would say that libcurl is one of the best possible options for you to do HTTP request... |
I have a function that accepts a variable length array of 80 character strings. I defined the function like so:
```
void foo (char namelist[][80] ...
```
in main() I do the following:
```
char **names = (char **)malloc(numNames * 80);
foo(names);
```
The type of names here is not correct. What is the appropriate w... |
namesshould be declared as:
```
char (*names)[80];
```
This declaresnamesas a pointer to an array of 80 chars.
By the way, there's no need to cast the return value ofmallocin C and many people consider it bad practice. See:1,2.
|
I have a simple doubt inchararrays. I have a structure:
```
struct abc {
char *charptr;
int a;
}
void func1()
{
func2("hello");
}
void func (char *name)
{
strcpy(abc.charptr, name); // This is wrong.
}
```
Thisstrcpywill result in a crash since I do not have any memory allocated to thecharptr.
The questio... |
If you were to usemalloc()you need to remember to make room for the null-terminator. So usemalloc(strlen(name)+1)before callingstrcpy().
But in this case you should just usestrdup()which does the allocation and copying in one go:
```
abc.charptr = strdup(name);
```
The memory returned bystrdup()has been allocated w... |
I have the following line in a function to count the number of 'G' and 'C' in a sequence:
```
count += (seq[i] == 'G' || seq[i] == 'C');
```
Are compilers smart enough to do nothing when they see 'count += 0' or do they actually lose time 'adding' 0 ?
|
Generally
```
x += y;
```
is faster than
```
if (y != 0) { x += y; }
```
Even ify = 0, because there is no branch in the first option. If its really important, you'll have to check the compiler output, but don't assume your way is faster because it sometimes doesn't do an add.
|
If I have the following snippet:
```
size_t num = -1;
switch(num) {
case -1:
printf("Minus one!\n");
break;
default:
printf("Not minus one!\n");
}
```
Why is it that the program printsMinus One!? Isnumcasted to asize_tin theswitchstatement? Is this behavior defined?
|
From the C standard on switch:
6.8.4.2 The switch statement...Semantics...5 The integer promotions are performed on the controlling expression. The constant
expression in each case label is converted to the promoted type of the controlling
expression. If a converted value matches that of the promoted controlling ... |
Do all popular iconv implementations support conversion from UTF-16BE (i.e. UTF-16 with big-endian byte order)? GNU iconv supports this encoding, but what about the other implementations in common use? Specifically, what do mingw and the *BSDs support?
Should I rather do this conversion myself?
|
If it's a big deal for you, you have an easy way out. Just write an autoconf test for UTF-16BE support, and then make the configuration script fail with an error message if it's not present.
Then you can take your time to sift through the standards, or, just forget about the whole issue.
Since libiconv is LGPL and ... |
I am writing a program in C that calculates this formula:
(source:crewtonramoneshouseofmath.com)
here is the line of code (I am just using + instead of the +-):
```
x = ((-1 * b) + (sqrt(pow(b, 2) - 4 * a * c)))/(4 * a);
```
I am not getting the correct root. For example if a = 1, b=-2, and c=-2 it SHOULD be 2.73.... |
x = (...) / (4 * a)
Shouldn't this be2 * a?
|
I'm using two different variable to divide in the calculation with the variable fromintanddouble. These work fine when I use something like:
```
int cost
cost = 40;
cost = (cost / 400) * 20 * 2;
```
For this the method works fine and I get the right result which is4, but when I use the variablecostand put it in the ... |
You are doing integer division - which rounds down.
Therefore:
```
cost / 400
```
is returning zero becausecost = 40and40 / 400rounds down to zero.
What you should do is use a floating-point type likedouble.
EDIT:
```
double cost
cost = 40;
cost = (cost / 400) * 20 * 2;
```
and
```
#define cost 40
double total... |
I am writing a shell that needs to be able to restart a stopped process if the user inputs a certain command.
My question is: which system call do I use to be able to give the signal of SIGCONT to the proper pid/pgid?
|
kill(pid, SIGCONT)
|
I'm writing a shell and I want to useexecv()and search for the right directory through the$PATHenvironment variable (Yes, I know I can useexecvp()and just pass the name of the file to it).
What I'm thinking about doing is getting a string fromgetenv("PATH"), breaking it down to separate paths then trying each one. Bu... |
What you described is exactly howexecvp()searches the PATH. I don't think there's much point in reimplementing this yourself.
|
I am reading about libraries in C but I have not yet found an explanation on what an object file is. What's the real difference between any other compiled file and an object file?I would be glad if someone could explain in human language.
|
An object file is the real output from the compilation phase. It's mostly machine code, but has info that allows a linker to see what symbols are in it as well as symbols it requires in order to work. (For reference, "symbols" are basically names of global objects, functions, etc.)
A linker takes all these object f... |
I was told that(i >> 3) is faster than (i/8)but I can't find any information on what>>is. Can anyone point me to a link that explains it?
The same person told me "int k = i/8, followed byk*8is better accomplished by(i&0xfffffff8);" but again Google didn't help m...
Thanks for any links!
|
As explainedherethe>>operator is simply a bitwise shift of the bits ofi. So shiftingi1 bit to the right results in an integer-division by 2 and shifting by 3 bits results in a division by 2^3=8.
But nowadays this optimization for division by a power of two should not really be done anymore, as compilers should be sma... |
I'm trying to do some calculation program using C what am I getting error is
error: lvalue required as left operand of assignment
This error cause from define a value on the header and then I assign using=in the main body.
If I put that value which it is in the header instead put them in theintordoublethen it will ... |
You can't assign to a define! After the preprocessor is done, to the compiler the code looks like this:
```
50 = 50 * 2 + total;
```
|
Im trying to figure out how to use callbacks with parameters in C. The following isnt working. What is the best way to archieve it? (passing arguments for the callback function)
```
#include <stdio.h>
void caller(int (*cc)(int a)) {
cc(a);
}
int blub(int a) {
printf("%i", a);
return 1;
}
int main(int ... |
You are doing the call before passing the function, not passing the callback function itself. Try this:
```
#include <stdio.h>
void caller(int (*cc)(int ),int a) {
cc(a);
}
int blub(int a) {
printf("%i", a);
return 1;
}
int main(int argc, char** argv)
{
caller(blub, 1000);
return 1;
}
```
|
The Question
1.)Is it possible to declare a pointer variable to reference to the memory address of a constant??I've tried this beforept = &20;(**pt is a pointer variable) but it's not working , so does it mean we can't do it??By the way if it's possible how am i going to work it out??
|
No. You must do this:
```
const int x = 20;
const int* p = &x;
```
|
Are there any size limitations for C structures?
|
From the C standard:
5.2.4.1 Translation limits1 The implementation shall be able to translate and execute at least
one program that contains at least one instance of every one of the
following limits:...
— 65535 bytes in an object (in a hosted environment only)...
— 1023 members in a single structure or uni... |
I have the following code example (in windows):
```
int fd = _dup(fileno(stdout));
freopen("tmp","w",stdout);
printf("1111");
close(stdout);
char buf[100];
FILE *fp;
fp = fopen("tmp","r");//in this line fd turns to be 0
if(NULL == fp) return -1;
if(fgets(buf,100 , fp) != NULL );
else return -1
fclose(fp);
```
... |
I bet that either buf is declared smaller than 100 or the fgets call is in fact with a number larger than 100.
|
So I'm working on an assignment for my computer science course, We have to take an algorithm thats written in C and replicate it in assembly (SPARC). My issue is that I know very little C code since I specialize in java. Can anyone help me look at this code and give me its Java equivalent? If you guys have any tips on... |
The syntax of C is really close to the syntax of Java.
Especially concerning this snipped so you shouldn't have any trouble to understand it.
Anyway I don't think that"and"exists in C.
Are you sure or your snippet?
What don't you understand in this code?
|
I would like to write some basic disk scanner utility. Basically I would like to be able to read raw bytes of a certain file(s) as written to the disk in the way system's disk utilities (like error checking and defragmentation in windows) do it. I would like to do it in C.
What should be my first steps? Obviously fop... |
The following resources might be of use:
http://support.microsoft.com/kb/100027http://www.codeproject.com/KB/system/rawsectorio.aspx
|
I have the following line in a function to count the number of 'G' and 'C' in a sequence:
```
count += (seq[i] == 'G' || seq[i] == 'C');
```
Are compilers smart enough to do nothing when they see 'count += 0' or do they actually lose time 'adding' 0 ?
|
Generally
```
x += y;
```
is faster than
```
if (y != 0) { x += y; }
```
Even ify = 0, because there is no branch in the first option. If its really important, you'll have to check the compiler output, but don't assume your way is faster because it sometimes doesn't do an add.
|
If I have the following snippet:
```
size_t num = -1;
switch(num) {
case -1:
printf("Minus one!\n");
break;
default:
printf("Not minus one!\n");
}
```
Why is it that the program printsMinus One!? Isnumcasted to asize_tin theswitchstatement? Is this behavior defined?
|
From the C standard on switch:
6.8.4.2 The switch statement...Semantics...5 The integer promotions are performed on the controlling expression. The constant
expression in each case label is converted to the promoted type of the controlling
expression. If a converted value matches that of the promoted controlling ... |
Do all popular iconv implementations support conversion from UTF-16BE (i.e. UTF-16 with big-endian byte order)? GNU iconv supports this encoding, but what about the other implementations in common use? Specifically, what do mingw and the *BSDs support?
Should I rather do this conversion myself?
|
If it's a big deal for you, you have an easy way out. Just write an autoconf test for UTF-16BE support, and then make the configuration script fail with an error message if it's not present.
Then you can take your time to sift through the standards, or, just forget about the whole issue.
Since libiconv is LGPL and ... |
I am writing a program in C that calculates this formula:
(source:crewtonramoneshouseofmath.com)
here is the line of code (I am just using + instead of the +-):
```
x = ((-1 * b) + (sqrt(pow(b, 2) - 4 * a * c)))/(4 * a);
```
I am not getting the correct root. For example if a = 1, b=-2, and c=-2 it SHOULD be 2.73.... |
x = (...) / (4 * a)
Shouldn't this be2 * a?
|
I'm using two different variable to divide in the calculation with the variable fromintanddouble. These work fine when I use something like:
```
int cost
cost = 40;
cost = (cost / 400) * 20 * 2;
```
For this the method works fine and I get the right result which is4, but when I use the variablecostand put it in the ... |
You are doing integer division - which rounds down.
Therefore:
```
cost / 400
```
is returning zero becausecost = 40and40 / 400rounds down to zero.
What you should do is use a floating-point type likedouble.
EDIT:
```
double cost
cost = 40;
cost = (cost / 400) * 20 * 2;
```
and
```
#define cost 40
double total... |
I am writing a shell that needs to be able to restart a stopped process if the user inputs a certain command.
My question is: which system call do I use to be able to give the signal of SIGCONT to the proper pid/pgid?
|
kill(pid, SIGCONT)
|
I'm trying to sign a xml document (http://www.w3.org/TR/xmldsig-core/) with an enveloped signature, I managed to calculate the signed info part but I'm struggling to get a meaningful result from the cryptoapi, unfortunately I have to stick to the crypto api (no external libs, no XmlXec). The signature method is rsa-sh... |
There is an article in the MSDN about XML signatures:http://msdn.microsoft.com/en-us/library/ms757845(v=VS.85).aspx
|
Say I have a custom GTK+ widget obtained from a third party library. It has an accelerator, e.g it hides itself when I press 'h' or click it, and shows itself when I press 'h' again or double-click it. I want disable thisparticularfunctionality of the GTK+ widget. How can I do this without changing the source code of ... |
I'm guessing now, but how about gtk_widget_can_activate_accel () ?
http://developer.gnome.org/gtk/2.24/GtkWidget.html#gtk-widget-can-activate-accel
|
I have a problems in OpenGL with blending (in result of antialiasing or textured painting). See problem illustration:
I have the following setup code
```
// Antialiasing
glEnable(GL_POINT_SMOOTH);
glEnable(GL_LINE_SMOOTH);
// Blending
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
// Textur... |
OpenGL blends in a linear RGB color space, but your monitor is not linear. This causes the apparent alpha to change depending on whether the background is light or dark. Try using theGL_EXT_framebuffer_sRGBextension.
|
I am doing static code analysis (Using Gimpel PC- Lint) of my source code. In code analysis, i am getting a warning 'Suspicious Truncation in arithmetic expression combining with pointer'.
Here is the what analysis report says::
source\interp.cpp(142): error 679: (Warning -- Suspicious Truncation in arithmetic expre... |
It may be because your adding an int to an unsigned long withulIndex+1Try
```
py[ulIndex] = y[ulIndex+UL1]-y[ulIndex];
```
Or it could depend on how you've defined py and y arrays.
|
hello every one I have written code
```
char sentence[100];
scanf("%s" ,sentence);
char * ptrs = sentence ;
printf("%d", strlen(ptrs));
```
suppose I enter
```
john is a boy
```
thestrlen()function is giving me value 4 it stops counting after space what I should do
thanks
|
That scanf will read only one word, if you do aprintfyou will see it. So there is nothing wrong withstrlen.
Usefgetswhich reads a whole line:
```
if (! fgets(sentence, sizeof(sentence), stdin)) {
fprintf(stderr, "error or end of file while no characters have been read\n");
return;
}
```
|
I have this#definestatement in legacy code I'm inspecting inC.
```
#define STEP(x) case x: STEP ## x : WPAN_Startup_Step = x;
```
This is a macro to replace cases in a very big switch state machine.
I can't understand what's going on in this macro. What does it expand to ?
|
##does a concatenation, this means that the result will be something like this:
```
STEP(1)
case 1: STEP1: WPAN_Startup_Step = 1;
```
or another example:
```
STEP(v)
case v: STEPv: WPAN_Startup_Step = v;
```
this macro does not make to much sense to me, since it generatesx: STEPx:maybe a usage example would clar... |
I have more of a cosmetic question:
I have a memory stream (void *) which i use in the sample as "cur_ptr".
Now i want to read the first bytes into a int ("version") of a struct ("a_struct").
My code that works:
```
int *version;
version = cur_ptr;
a_struct->version = *version;
```
How can i write it without the he... |
First cast cur_ptr to int* then get it's value ;)
```
*((int*)cur_ptr);
```
|
I want to read a string entered by the user. I don't know the length of the string. As there are no strings in C I declared a pointer:
```
char * word;
```
and usedscanfto read input from the keyboard:
```
scanf("%s" , word) ;
```
but I got a segmentation fault.
How can I read input from the keyboard in C when th... |
You have no storage allocated forword- it's just adangling pointer.
Change:
```
char * word;
```
to:
```
char word[256];
```
Note that 256 is an arbitrary choice here - the size of this buffer needs to be greater than the largest possible string that you might encounter.
Note also thatfgetsis a better (safer) op... |
When I am debugging a program in Xcode, I can pause execution in there debugger console. Is there any way to do this using gdb from the command line?
I'd like to do this so I can modify breakpoints after the program has started.
|
You can just press Ctrl+C and will be able to do what you ask, although it might not always work (see comments below).
|
Is there any difference with the atom defined inXA_WM_NAMEdefined inXatom.hand the one got usingXInternAtom(display, "_NET_WM_NAME", False)?
Edit: I made a little program which prints the integer value of both and I got:_NET_WM_NAME: 312, XA_WM_NAME: 39, so, they represent different atoms. What are the differences?
... |
They are different atoms, but they both represent the title of the window.
_NET_WM_NAMEis part of the newerXDG/freedesktop.org window manager spec.
Like other XDG string properties, it's defined as a UTF-8 encoded string, whereas the "legacy"WM_NAMEuses the X "compound text" encoding.
Window managers that respect th... |
With "opendir" and "readdir" i do read a directories content.
During that process i do some strings manipulation / allocation:
something like that:
```
int stringlength = strlen(cur_dir)+strlen(ep->d_name)+2;
char *file_with_path = xmalloc(stringlength); //xmalloc is a malloc wrapper with some tests (like no more mem... |
strlen()counts the bytes in the string, it doesn't care if the contained bytes represent UTF-8 encoded Unicode characters. So, for example,strlen()of a string containing an UTF-8 encoding of "aöü" would return5, since the string is encoded as"a\xc3\xb6\xc3\xbc".
|
When I want to call some Windows function, like MessageBox I can import it from user32.dll and call (with LoadLibrary and GetProcAddress). But there is also a static library that Visual C++ uses, so I don't need to manually load DLLs and functions. How do they work? Do they contain wrappers that call LoadLibrary/GetPr... |
The "static library" that you're referring to is actually animport library. This type of library contains records that tell the linker which library each function actually exists in, and doesn't contain any code itself. The linker creates import records in the executable, which the loader resolves at load time. This f... |
I have a textbook exercise right after looping and using char values (meaning that I can't use arrays and strings).
As per the exercise, I'll (the user) will have to make the user enter a set of chars
For example "IamaDinosaur" and then find the letter with the highest ASCII value.
How do I go about looping ascanf(... |
You could usegetcmaybe ?
```
int ch;
int max = EOF;
while ((ch = getc(stdin)) != EOF && ch != '\n')
if (max < ch)
max = ch;
```
Obviously you could go thescanf("%c")route.
|
I have data format below
```
int : int \t string
```
for example,
```
11:11 long long long description.
```
I use
```
sscanf(line, "%d:%d\t%s\n", &num1, &num2, &description)
```
but it only cuts the first word from the description.How should I proceed the data from line to receive all characters in descripti... |
The format specification%swill read a string, until a whitespace character is found. If you want to read all characters up to\nyou can do%[^\n]. That says read characters as long as the character is not in the set that contains the newline character. Note that the trailing \n is not read by it. So the final solution w... |
I know that Gdk-Pixbuf supports png and jpg, but I cannot find anexact listof all the completely (or partially) supported image formats anywhere on the internet. It is necessary for my current project, since I need to check the extension of every file in a directory and determine whether it is supported or not by gdk-... |
I know this is 5+ years old but I had trouble finding this for PyGI / PyGObject (3.22.0).
```
import gi.repository.GdkPixbuf as pixbuf
```
Then we can get all the formats using:
```
for f in pixbuf.Pixbuf.get_formats():
print f.get_name()
```
On my system (might be different on yours if you installed other loa... |
I want to move a Window (HWND) in a second monitor. The thing is that I tried many things like double the resolution or putting negative values and it never was able to put the window on my second monitor.
Any clue of how to do that in C/C++/c#
|
Screen and the Form.StartPosition should get you there.
See the first answer to this post (for C#/WinForms solution):How do I ensure a form displays on the "additional" monitor in a dual monitor scenario?
|
I'm trying to write a simple program where it ask user to enter a bunch of positive integers, and calculate the average of all the number entered. Program will terminate when user enter a non positive number like 0 or -1.
Here is my code. For some reason I get an error right when I try to enter the first input, can s... |
You need to passthe address of the variabletoscanf.Try this:
```
scanf("%d", &input);
^
```
Also see theC FAQ: Why doesn't the callscanf("%d", i)work?
|
Just started to learn C language.
I have a pointer array int *parr and I need to fill it with random numbers and then do some other things with it.
But I even don't understand how to fill it with random numbers. I tried something like this, but it hangs the program:
```
for(i=0 ; i<R ; i++)
{
for(j=0 ; j<C; j++)
... |
The way you initialize it, you probably have tomallocmemory like this:
```
parr = malloc(R * C * sizeof(*parr));
```
|
I have more of a cosmetic question:
I have a memory stream (void *) which i use in the sample as "cur_ptr".
Now i want to read the first bytes into a int ("version") of a struct ("a_struct").
My code that works:
```
int *version;
version = cur_ptr;
a_struct->version = *version;
```
How can i write it without the he... |
First cast cur_ptr to int* then get it's value ;)
```
*((int*)cur_ptr);
```
|
I want to read a string entered by the user. I don't know the length of the string. As there are no strings in C I declared a pointer:
```
char * word;
```
and usedscanfto read input from the keyboard:
```
scanf("%s" , word) ;
```
but I got a segmentation fault.
How can I read input from the keyboard in C when th... |
You have no storage allocated forword- it's just adangling pointer.
Change:
```
char * word;
```
to:
```
char word[256];
```
Note that 256 is an arbitrary choice here - the size of this buffer needs to be greater than the largest possible string that you might encounter.
Note also thatfgetsis a better (safer) op... |
When I am debugging a program in Xcode, I can pause execution in there debugger console. Is there any way to do this using gdb from the command line?
I'd like to do this so I can modify breakpoints after the program has started.
|
You can just press Ctrl+C and will be able to do what you ask, although it might not always work (see comments below).
|
Is there any difference with the atom defined inXA_WM_NAMEdefined inXatom.hand the one got usingXInternAtom(display, "_NET_WM_NAME", False)?
Edit: I made a little program which prints the integer value of both and I got:_NET_WM_NAME: 312, XA_WM_NAME: 39, so, they represent different atoms. What are the differences?
... |
They are different atoms, but they both represent the title of the window.
_NET_WM_NAMEis part of the newerXDG/freedesktop.org window manager spec.
Like other XDG string properties, it's defined as a UTF-8 encoded string, whereas the "legacy"WM_NAMEuses the X "compound text" encoding.
Window managers that respect th... |
With "opendir" and "readdir" i do read a directories content.
During that process i do some strings manipulation / allocation:
something like that:
```
int stringlength = strlen(cur_dir)+strlen(ep->d_name)+2;
char *file_with_path = xmalloc(stringlength); //xmalloc is a malloc wrapper with some tests (like no more mem... |
strlen()counts the bytes in the string, it doesn't care if the contained bytes represent UTF-8 encoded Unicode characters. So, for example,strlen()of a string containing an UTF-8 encoding of "aöü" would return5, since the string is encoded as"a\xc3\xb6\xc3\xbc".
|
When I want to call some Windows function, like MessageBox I can import it from user32.dll and call (with LoadLibrary and GetProcAddress). But there is also a static library that Visual C++ uses, so I don't need to manually load DLLs and functions. How do they work? Do they contain wrappers that call LoadLibrary/GetPr... |
The "static library" that you're referring to is actually animport library. This type of library contains records that tell the linker which library each function actually exists in, and doesn't contain any code itself. The linker creates import records in the executable, which the loader resolves at load time. This f... |
I have a textbook exercise right after looping and using char values (meaning that I can't use arrays and strings).
As per the exercise, I'll (the user) will have to make the user enter a set of chars
For example "IamaDinosaur" and then find the letter with the highest ASCII value.
How do I go about looping ascanf(... |
You could usegetcmaybe ?
```
int ch;
int max = EOF;
while ((ch = getc(stdin)) != EOF && ch != '\n')
if (max < ch)
max = ch;
```
Obviously you could go thescanf("%c")route.
|
I have data format below
```
int : int \t string
```
for example,
```
11:11 long long long description.
```
I use
```
sscanf(line, "%d:%d\t%s\n", &num1, &num2, &description)
```
but it only cuts the first word from the description.How should I proceed the data from line to receive all characters in descripti... |
The format specification%swill read a string, until a whitespace character is found. If you want to read all characters up to\nyou can do%[^\n]. That says read characters as long as the character is not in the set that contains the newline character. Note that the trailing \n is not read by it. So the final solution w... |
I know that Gdk-Pixbuf supports png and jpg, but I cannot find anexact listof all the completely (or partially) supported image formats anywhere on the internet. It is necessary for my current project, since I need to check the extension of every file in a directory and determine whether it is supported or not by gdk-... |
I know this is 5+ years old but I had trouble finding this for PyGI / PyGObject (3.22.0).
```
import gi.repository.GdkPixbuf as pixbuf
```
Then we can get all the formats using:
```
for f in pixbuf.Pixbuf.get_formats():
print f.get_name()
```
On my system (might be different on yours if you installed other loa... |
I want to move a Window (HWND) in a second monitor. The thing is that I tried many things like double the resolution or putting negative values and it never was able to put the window on my second monitor.
Any clue of how to do that in C/C++/c#
|
Screen and the Form.StartPosition should get you there.
See the first answer to this post (for C#/WinForms solution):How do I ensure a form displays on the "additional" monitor in a dual monitor scenario?
|
I'm trying to write a simple program where it ask user to enter a bunch of positive integers, and calculate the average of all the number entered. Program will terminate when user enter a non positive number like 0 or -1.
Here is my code. For some reason I get an error right when I try to enter the first input, can s... |
You need to passthe address of the variabletoscanf.Try this:
```
scanf("%d", &input);
^
```
Also see theC FAQ: Why doesn't the callscanf("%d", i)work?
|
Just started to learn C language.
I have a pointer array int *parr and I need to fill it with random numbers and then do some other things with it.
But I even don't understand how to fill it with random numbers. I tried something like this, but it hangs the program:
```
for(i=0 ; i<R ; i++)
{
for(j=0 ; j<C; j++)
... |
The way you initialize it, you probably have tomallocmemory like this:
```
parr = malloc(R * C * sizeof(*parr));
```
|
I cannot figure out how to use GLib (GIO?) to list all the files (file-names?) in a given directory. There is no good doc or tutorial. Any code snippets are welcome. If it is not possible (or too troublesome) to do this using GLib, Is there any good C or C++ third party library to do this. EXCEPT Boost.FileSystem as I... |
If you are looking for aglibexample, here you go.
```
GDir *dir;
GError *error;
const gchar *filename;
dir = g_dir_open(".", 0, &error);
while ((filename = g_dir_read_name(dir)))
printf("%s\n", filename);
```
|
I have a header file that looks like
header.h
```
int TOS;
```
This file is being included by just one code file
code.c
```
#include "header.h"
TOS=0;
```
When compiling code.c GCC issues a warning
code.c:3:1: warning: data definition has no type or storage class [enabled by default]
code.c:3:1: warning: type d... |
It is because you defineTOSin the global scope, which need you to define the type ofTOS(it is an declaration), if no type was given, by default it isint.
This will cause anconflicting type error,
```
char x;
x = 0;
```
|
We would like to build a shared library withCMAKEsystem. It's something like:
```
lib/
CMakeLists.txt
src/
CMakeLists.txt
module/
CMakeLists.txt
module1.c
foo.c
```
module1.cneeds some standard shared library likelibrt. We have
```
add_library(module module1.c)
target_link_libraries(modu... |
If librt is linked with -lrt, then in CMake you can link it in this way:
```
target_link_libraries(module -lrt)
```
|
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
So if I had an int, say0000100101101001, it should be turned to an array like{0,3,5,6,8,11}. I am using a c... |
How about this (should work for unsigned integers):
```
while (x) {
/* Store rightmost 1-bit in your array. */
arr[i++] = x & (-x);
/* Turn off rightmost 1-bit. */
x = x & (x - 1);
}
```
I suspect there are better ways to do it.
|
I'm making a program and one of the things it needs to do is transfer files. I would like to be able to check before I start moving files if the File system supports files of size X. What is the best way of going about this?
|
Go on with using a function likeftruncateto create a file of the desired size in advance, before the moving, and do the appropriate error-handling in case it fails.
|
I want to ask that is there a way through which I can convert some part of int array to int variable
for example
```
// my integer array contain 3,4,5,2,7
int array[] = {3,4,5 ,7,1,5,5,} ;
```
and i want a variable int to contain only first 3 member of array that is my variable should be like this
`
```
int ... |
Something like this maybe ?
```
int var = 0;
for (i = 0; i < 3; i++) {
var *= 10;
var += array[i];
}
```
|
I am trying to send/receive some data across 2 computers (mac, ubuntu) using a UDP connection and they are connected with an ethernet cable. When I run the server to receive some data from a client, I get the data but if I send it back, the client does not receive it. On further investigation, I found out that the cl... |
Make sure you populatelenbefore callingrecvfrom, it's a value-result argument.
```
len = sizeof(clientAddress);
n = recvfrom(sockfd, msg, 1000, 0, (sockaddr *)&clientAddress, &len);
```
|
How does c store a double decimal in an 8 bit slot?
```
#include "stdio.h"
main(){
double x = 123.456;
printf("\n %d - %e \n",sizeof(x),x);
}
```
outputs:
```
8 - 23.456
```
The value of x is correct being 123.456, but the supposedly it is only 8 bits.
|
That's not 8 bits. It's 8 bytes. And each byte is at least 8 bits (and usually exactly 8 bits).
So it's probably 8 * 8 = 64-bits for adouble.
EDIT:
Thesizeof()operator yields the size of an objectin bytes.
A "byte" is by definition the size of achar. (That's how the C standard defines the word "byte"; it may have... |
Sorry if this question is poorly worded (please edit it if it will make it easier for readers to understand me.)
I'm new to oop and was learning some C code. What does this last line of code mean? Is there a way to paradigmatically(I just made up this word) write it differently?
```
typedef struct _Song {
//some m... |
Songis nothing more than an alias forstruct _Song(that's what thetypedefat the beginning means). There is absolutely no difference between the two, wrt their type.
In C++, the syntactic difference is even more marginal, since_Songis also an alias forstruct _Song.
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed6 years ago.Improve this question
My specific interest is in controlling the Ethernet port's 8 pins to send signals. How ca... |
It's entirely possible (and likely) that the individual outputs are controlled entirely by hardware from a frame buffer (Ethernet frame, not the video kind), and that unless your card has an explicit mode to allow you to use them as GPIO (which is probably rather rare) you're not going to have much luck, even with a c... |
I have an array that is a "NULL-terminated array ofNULL-terminated strings". This is given bychar **args.
I can access individual elements usingargs[0],args[1], etc. I wanted to take the entire array and flatten all the elements into a string. If the array contained:
```
args[0] = "abc"
args[1] = "def"
```
I want a... |
I have an array that is a "NULL-terminated array of NULL-terminated strings".
The array ends withNULL, that is as soon asargs[i] == NULLyou stop your iteration.
|
I did not find any tool created for tracing pthread's threads in linux process. I want something like strace/ltrace, is there something to view calls in real-time?
Thank you
|
strace works for threads as well. Usestrace -fto strace all threads.
To strace only a particular thread, you first have to find its tid (thread id).
Threads have thread id's that's really a pid (process id)
Once you know the pid of the thread, usestrace -p the_pidto strace that thread.
The pids of all the threads ... |
I have used the functionatoito convert character strings tointand it's working fine but when I gave
```
num = atoi (argv[1]) ;
// argv contain 4294967295 maximun value of 32 bit integer
```
it's giving me 2147483647 answer which is basically half of 4294967295
i guess that its because of difference of bytes inchar... |
You've run into the maximum value of an integer. Sinceatoireturns anint, it is limited to the size of an integer on your machine. It looks like your machine uses 32-bitints.
In case you missed it (it's easy to miss), 2147483647 = (2 ^ 31) - 1. Remember thatints can be negative, and the leftmost bit is the sign bit in... |
I've got a C++ server that acts as a mirror. What gets in gets out to a different socket. Right now, it reads the socket into a buffer and writes it into the other socket. I want to improve the throughput.
I'veread stuffaboutsendfile()andsplice(), but it seems limited to "file-to-socket" transfers. Maybe a simplepipe... |
You can setup a named pipe in linux. Multiple processes could read/write from this. Check out this link:http://www.cs.fredonia.edu/zubairi/s2k2/csit431/more_pipes.html.
Also as mentioned above using netcat should do the trick (http://netcat.sourceforge.net/).
|
I would like to know if there is any kind of regular expression expansion within the compiler(GCC) pre processor. Basically more flexible code generation macros.
If there is not a way, how do you suggest i accomplish the same result
|
The C preprocessor can't do that.
You might want to use a template processor (for instanceMustachebut there are many others) that generates what you need before passing it to the compiler.
|
I have been asked to perform some logic on an integer, which I think would be much more easier if I convert it to String. So please suggest me if there is a simple way other than
using "sprintf" function in C
|
The only better way thansprintfissnprintf. For simple integer formatting it probably doesn't matter, butsnprintfwill protect you from disaster if you make a stupid assumption (for example, thatintcan't be more than 10 digits) or even a reasonable one (likeCHAR_BIT==8)...
```
#define INT_DECIMAL_DIGITS (24*sizeof(int)... |
Can I do code such:
```
char *p;
p = User_input;
```
Is it possible to assign a string topat runtime?
|
Sure you can, but there is nostringin c, I think you meanchar *, like
```
char *user_input = malloc(128);
scanf("%s", userinput);
p = user_input;
```
|
How can I separate a string that has white spaces between the 3 shorts and between the rest of the string to 4 different strings.
Example:
```
"123 402 10 aaa bbb cc".
```
What I want is simply
```
short i=123;
short j=402;
short y=10;
char * c="aaa bbb cc".
```
I was trying to usesscanfto do it but I can't se... |
One way to do it could be:
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
const char* str = "123 402 10 aaa bbb cc";
short i,j,y;
char c[256];
if (sscanf(str, "%hd %hd %hd %255[^\n]", &i, &j, &y, c) == 4) {
printf("i=%hd j=%hd y=%hd c=\"%s\"\n", i, j, y, c);
}
return 0;
}
```... |
I have just updated to Lion and now my app is crashing which was working fine in older version. It crash on memset function with no logs.
```
unsigned char *theValue;
add(theValue, someotherValues);
```
I have passed theValue reference to function
```
add(unsigned char *inValue, some other perameter) {
memset(inVal... |
Is there really no code between the declaration oftheValueand the call toadd()? If so, then that's your problem. You are passing a random value as the first parameter tomemset().
For this code to make sense, you have to allocate a block of memory fortheValueand pass its size toadd(), like so:
```
unsigned char *theV... |
I expect it would break some other parse but this is not immediately springing to mind...
E.g. If I say this:
```
#include <stdio.h>
int main()
{
int i = 10 000;
printf("%d\n", i);
return 0;
}
```
My compiler says this:
```
ctest.c:5: error: expected ‘,’ or ‘;’ before numeric constant
```
I'm thinking... |
The language doesn't allow this (an integer literal is one token, the intervening whitespace splits it into two tokens) but there's typically little to no expense incurred by expressing the initializer as an expression that is a calculation of literals:
```
int i = 10 * 1000; /* ten thousand */
```
|
Any idea how to get like this feature in c or c++
password=********
but at the end system gets right password(means real input) but other people see this.
|
To confirm the password of a user, usepam(theofficial pageis hosted on kernel.org and therefore down as of writing), in particularpam_authenticate.
If your application has its own authentication architecture (and most of the time, it shouldn't), executestty -echo, ask for the password, and then executestty echoto res... |
I'm trying to print an integer into a string with snprintf for display on an OLED display from an ARM micro. However, when I use %d or %u the micro locks up and stops executing.
Using %x or %c works fine, but the output isn't much use.
What could cause this behaviour? Unfortunately I don't have access to a JTAG devic... |
This actually turned out to be a stack size issue with the RTOS that I was using. I guess the added complexity of the snprintf call was pushing it over the limit and crashing.
Thanks to all who took a crack at answering this!
|
I am embedding python in a C++ dll (so ultimately I can put it in an xll). When the setup is wrong Py_Initialize is documented as terminally failing - seehttp://docs.python.org/c-api/init.html, "...it is a fatal error if the initialization fails.".
Is it possible to catch this error and how?
Thinking maybe a global ... |
I solved this by creating a separate executable that attempts to initialize python. My primary process will launch it and check the exit code and only call PyInitialize if the child process was successful. So, python is initialized twice, but it is better than an apparent crash to the user.
|
What I am trying to do is have the C preprocessor output#ifdef,#else, and#endifdirectives. That is, I would like to somehow "escape" a directive so that the output of the preprocessor includes the directive were the preprocessor to run on the output.
Is it possible to "escape" a CPP directive so that it is outputted ... |
A slight variant ofMarcelo Cantos's answerworks for me on GNU cpp 4.4.3:
```
#define HASH(x) x
...
HASH(#)ifdef __cplusplus
class foo { };
HASH(#)endif
```
|
Apologies in advance as I'm sure someone must have asked this before but I can't find it.
Just had a surprise, a colleague and I both added the same value in for an enum, and it compiled, e.g.
```
enum MyEnum
{
mine = 1,
his = 1
}
```
Looks like C/C++ supports this also (?). Any reason for this behaviou... |
Let's take a simple example
```
enum PrivilegeLevel
{
None,
Reporter,
Reviewer,
Admin,
DefaultForNewUser = None,
DefaultForProjectOwner = Reviewer,
};
```
|
see i have one jig.c file in that i have statement like
```
mkvFree(jig);
```
Now i have used following command for find and replace
```
find /home/jeegar/jig.c -type f -exec sed -i 's/mkvFree(/mkvFree((void**)&/g' {} \;
```
By this command i want to get output as
```
mkvFree((void**)&jig);
```
But i get output ... |
You need to escape the \& character:
```
find /home/jeegar/jig.c -type f -exec \
sed -i 's/mkvFree(/mkvFree((void**)\&/g' {} \;
```
The&character would substitute the whole matched input for the pattern.
|
I want to have a dynamic webpage that automaticly updates some information, this information should be received from my c/c++ application using HTTP. I have set up a socket and can send HTML and Javascript files to the browser.
I don't know how to move on. How to encapsulate my data into XMLHttpRequest objects? Or ma... |
A server should handle it as any other request. From the servers point of view, it's a normal HTTP request. Return the data that the client asks for! This is usually a HTML fragment, some XML or some JSON.
|
I have in my project the following method:
```
long compare( long* avar, long comp, long exc )
{
return __sync_val_compare_and_swap( avar, comp, exc );
}
```
But if i want to compile my project using gcc of version (older version, 3.4.3 for instance) which doesn't supportAtomicBuiltinsWhat is the alternative pat... |
The only alternative that I would see is that you'd have to implement this through assembler. I think theasmextension of gcc predates the stone age, so any compiler that you might encouter will support this.
Implementing this particular function is not so difficult, and you'd find references easily. You'd have to pro... |
What is the use oftim.tv_secandtim.tv_nsecin the following?
How can I sleep execution for500000microseconds?
```
#include <stdio.h>
#include <time.h>
int main()
{
struct timespec tim, tim2;
tim.tv_sec = 1;
tim.tv_nsec = 500;
if(nanosleep(&tim , &tim2) < 0 )
{
printf("Nano sleep system call ... |
Half a second is 500,000,000 nanoseconds, so your code should read:
```
tim.tv_sec = 0;
tim.tv_nsec = 500000000L;
```
As things stand, you code is sleeping for 1.0000005s (1s + 500ns).
|
It seems that all the major investment banks use C++ in Unix (Linux, Solaris) for their low latency/high frequency server applications. How do people achieve low latency in trading high frequency equity? Any book teach how to achieve this?
|
http://g-wan.com/
http://www.zeromq.orghttp://www.quantnet.com/forum/threads/low-latency-trading-system.3163/check these websites you may get some idea about low latency programming.but be aware that some codes may not be standardized. Which means it will not for longer timeit may creates some bugs in it.
|
I would like to list all Lotus Notes installations on my computer. How can I do that by using C and Win32 API?
|
You may have an easier time searching the registry for Lotus Notes keys. One of the keys tells the version installed
|
I want GtkEntryCompletion to get data from additional source (function or another model, no matter) when there's no match in models data. Is that possible?
|
Make a custom class that implements theGtkTreeModelinterface, and retrieves data preferentially from one model and then another if not found.
|
Does anyone know how to print out memory addresses of UNIX application's memory using C?
I need to print out those information of addresses when I run my code, for instance 'the number of pages of physical memory'
The output i'm looking for this example is something like...
```
Number of pages:
384285
```... |
```
char buf[40];
sprintf(buf, "exec cat /proc/%d/status", getpid());
system(buf);
```
|
I have a rather odd program where I need to load a file into memory, close that file handle, and then use the file image in memory like a file (where i use ReadFile, WriteFile with a HANDLE)... so basically I'm looking at doing the inverse of CreateMapFile... is this possible within the Windows API?
Thanks!
|
When you callCreateFile, you can useFILE_ATTRIBUTE_TEMPORARY. Thisattemptsto hold the data for the file in RAM if possible, but it doesnotguarantee it -- the data could be written out to disk if memory gets low enough.
|
I setup a raw Packet socket using the following:
```
sockFd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL) );
```
Then I am trying to set the socket optionIP_HDRINCLusing:
```
int one = 1;
if (setsockopt (sockFd, IPPROTO_IP, IP_HDRINCL, &one, sizeof(one)) < 0)
LogPrint(LOG_UNKNOWN,"Warning: Cannot set HDRINCL!\... |
PF_PACKETsockets don't have any option that I asked in the question to be set. That option is only available onPF_INETorPF_INET6sockets with typeSOCK_RAW.
If one wants the IP headers to be added by the kernel, the one must use thePF_INETsocket.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.