question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I wanted to do something using multi-threading and all the stuff encapsulated in functionfoo.
```
filterThread = _beginthread (foo, 0,NULL) ;
```
and I wanted to letfooreturn value:
```
int foo()
{
return iRet;
}
```
but the prototype of _beginthread_CRTIMP uintptr_t __cdecl _beginthread (_In_ void (__cdecl *... |
Use_beginthreadexinstead.This allows you to use a function that returns a value. You can then useGetExitCodeThreadto get the value when the thread completes.
|
I'm wondering if there's a way you can scan an array for a match usingstrcmp. I know the parameters passed tostrcmpare C strings. So something like this wouldn't work:
```
strcmp(arrayofstrings[x], c-string)
```
|
It would work as long as the arguments can be reduced to of typeconst char*.
```
char *a[] = { "Hello", "Hello" }; // Array of pointers to c strings
if ( !strcmp(a[0],a[1]) ){
// true in this case
}
```
|
I have a random set S={3,12,15,24,33,40} and I need to generate subsets of size 3 from this set.Most of the examples and explanations regarding combination involved a set of increasing and ordered values like S1={1,2,3,4,...n}. Using the combination formula,I found that the number of possible combinations is 20 but ca... |
Use the algorithms you have seen that have increasing, ordered values and simply replace those with the values in your list.
For example, the combinations (0-indexed) would be:
```
0, 1, 2
0, 1, 3
0, 1, 4
...
...
```
Then have an array with your numbers
```
int array[] = { ...values... };
```
and change the combi... |
I wrote a piece of c code :
```
struct Res {
int a;
float b;
double c;
};
struct Res ModRes(struct Res rrr)
{
rrr.a=222;
return rrr;
}
int main()
{
struct Res r[10]={1,2,3};
ModRes(r[0]);
return 0;
}
```
whyr[0]is not 222 afterModRes?
|
In C, arguments are passed by value. You could make the function accept astruct Res *rather than astruct Res:
```
struct Res *ModRes(struct Res *rrr)
{
rrr->a=222;
return rrr;
}
int main()
{
struct Res r[10]={1,2,3};
ModRes(&r[0]);
return 0;
}
```
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:C Preprocessor, Stringify the result of a macro
Shortly:
```
#include <iostream>
float pi(){ return 3.14; }
#define PRINT(x) std::cout << #x << std::endl;
#define PI pi()
int main(int argc, char *argv[])
{
PRINT(PI)
PRINT(pi()... |
Add another helper macro:
```
#define QU(x) #x
#define PRINT(x) std::cout << QU(x) << std::endl;
#define PI pi()
```
|
I want to change device description in a FTDI-Chip.
For that, I define first FT_PROGRAM_DATA ftData, call FT_EE_Read, modify the field ftData.Description and finally call FT_EE_Program for writing the data back. The code example is:
```
FT_PROGRAM_DATA ftData;
FT_STATUS ftStatus = FT_EE_Read(ftHandle, &ftData);
strc... |
I've got it. The description seems not to be updated on EE_Program. After re-connection of USB-Cable the desciption changes. There is a function:
```
FT_CyclePort(ftHandle);
```
which simulates re-connection programmatically.
|
I have a simple rule in my grammar which looks for sequence of whitespaces:
```
ws: ws|' ';
```
When bison sees this rule, it complains:
warning: rule useless in parser due to conflicts: ws: ws
Why it is so? Cant I have a simple rule in grammar which looks for a regex?
|
what you are declaring is 'ws is ws or ws is a space', not 'ws is one or more spaces'.
If you want the latter, try something like:
```
ws: ' '
| ' ' ws;
```
See alsohttp://www.gnu.org/software/bison/manual/bison.html#Recursion
|
If I start a terminal, how do I know what mode it starts in? Who decides that? Can I start my terminal in packet mode i.e.TIOCPKT
I came across thisPacket modelink which says:Packet mode is enabled by pushing the pckt module on the master-side.- I do not understand this exactly.
|
The link you refer to is for SCO Unix, which has theSTREAMSI/O subsystem. There is a pretty good overview of STREAMShere(its for Solaris, but same concepts apply to other *nixes).
The manual page tells you that you have to push the pckt module onto the stream, which is done with an ioctl() call with theI_PUSHcommand.... |
I am currently trying to learn C by using the K&R, but I am completely stumped by example 1.5.2. For some reason, after I press Ctrl-Z, instead of printingnc, it printsncmultiplied by 2. I don't know what could be causing this problem (I copied the code exactly how it is in the book). The compiler I am using is Visual... |
Becauseenteris a keystroke.
If your input is:
```
1<enter>
1<enter>
1<enter>
^z
```
it would output:
6
|
man ptysays...
```
The BSD ioctl(2) operations TIOCSTOP, TIOCSTART, TIOCUCNTL, and TIOCREMOTE
have not been implemented under Linux.
```
why so? How is these operations taken care of inlinux?
|
BSD-style PTYshave been deprecated since Linux 2.6.4. System V (UNIX 98)-style PTYs should be used instead.
That's probably the reason why theseioctloperations remain unimplemented to this day.
|
I am creating a linked list program in C and I keep on getting a segmentation fault. I've narrowed the problem down to a few lines of code and I believe it has to do with checking for NULL. How can I fix this? Here's the code:
```
typedef struct node
{
int contents;
struct node *nextNode;
} Node;
deleteNode(... |
Try checking to make sure thatcurrentNodeisn'tNULLat the start ofdeleteNode(). I.e.
```
deleteNode(Node *currentNode)
{
if (currentNode == NULL) return;
// ...
// ...
}
```
|
Ok, this might sound like a strange question but it is an interesting one. I am coding for iOS and have been told that it is always best to multiply rather than divide values as it is faster.
I know that processors these days probably make this a non issue but my curiosity has gotten the better of me and I am wonderi... |
Yes, division is usuallymuchslower than multiplication.
However, when dividing by literals (or anything that can be determined to be a constant at compile-time), the compiler will usually optimize out the division.
|
I am working at an OS independent file manager (using SDL). I am trying to use native functions as much as possible (with the appropriate #ifdefs), and I am having a problem with Windows. When I am using
```
CopyFileEx()
```
for example, if there is a problem it will pop up a modal dialogue, and the user will have t... |
You might want theSetErrorModefunction.
|
I am trying to write a linked list program in C, however I keep on getting an initalization from incompatible pointer type warning/error. How do I get rid of this? And could you explain what is wrong? What follows is a simplified version of my program:
```
typedef struct node
{
int contents;
struct Node *nextNode;... |
I think you wantstruct node *notstruct Node *in yourstruct node:
```
typedef struct node
{
int contents;
struct node *nextNode; /* here */
} Node;
```
And don't cast the return value frommalloc, it is not needed.
|
im trying to compare words of an array using strcmp.Im trying to get each word that appears more than once in the array to print out only once, so i can determine the number of unique words.I know what its doing wrong as when it searches the array it prints out each copy it finds, for example if the word "the" is in t... |
Convert your char arrays tostd::stringand instead of printing them, put them into anstd::set. Then print each element in the set.
|
I'm trying to convert temperature given in Fahrenheit to Celsius. But for some reason its not working properly. I know that a similar question has been asked but my problem is different because I can't even printout what I have scanned (using scanf) from the user.
Code:
```
#include<stdio.h>
#include<conio.h>
void ... |
I'm not sure (because your compiler might behave differently) but perhaps it's caused by this:
You're using5.0and9.0which aredoublevalues as well as32which is anint.
Try changing them to5.0f,9.0fand32.0f.
|
I readhereit is C90 with extensions. How can I know for sure?
|
Try below command and search forstd
```
gcc -v --help | less
```
It will show you all the available options for your gcc.
|
My question is how do I compute 2^(x) in c. I know there is something like shifting that does the same thing. I tried to do total = x << 1, but that didn't work. I know that if i shift one bit it is the same as multiplying it by two. Or something like that.
```
int x;
for(x=0; x<4; x++){
total += x <<1; //
}
```
... |
It's the other way around.1 << xwill give you '2 ^ x'.
|
I have application that has to write to console. Also I call function from dll that writes to stdout too. Now I want to have separate output window to get all output from dll there. (So I will have 2 console windows: one for client app, one for dll) How to make it? I use windows+mingw
|
You can't.stdoutis a single file handle and if both your application code and the dll are writing to it, they're going to go to the same place no matter what you do.
Your best options would be to either:
change your application code to write to something besides stdout (i.e stderr or a file), orchange your applicati... |
I hava a small c-tool in which i execute_popen. I compile the tool for windows and linux, in linux i use instead of_popenthe functionpopen.
These functions work well and i can get the sub-process' output. But if i execute the function on windows (_popen) there's a cmd-window visible. On this window there's no ouput, ... |
You can call CreateProcess with the CREATE_NO_WINDOW
flag. This is obviously non portable but it does get the job done.
|
As I've learned recently, alongin C/C++ is the same length as anint. To put it simply, why? It seems almost pointless to even include the datatype in the language. Does it have any uses specific to it that anintdoesn't have? I know we can declare a 64-bitintlike so:
```
long long x = 0;
```
But why does the lang... |
When writing in C or C++, every datatype is architecture and compiler specific. On one system int is 32, but you can find ones where it is 16 or 64; it's not defined, so it's up to compiler.
As forlongandint, it comes from times, where standard integer was 16bit, wherelongwas 32 bit integer - and it indeedwaslonger t... |
I cannot create a 2D array from 2 variables (egint arr[i][j]not allowed) so how would I create a dynamically sized 2D array?
The dimensions of the array are only known at runtime in my program. The array is to represent a grid. How would I code this in C?
|
First allocate an array of pointers.
```
/* size_x is the width of the array */
int **array = (int**)calloc(size_x, sizeof(int*));
```
Then allocate each column.
```
for(int i = 0; i < size_x; i++)
{
/* size_y is the height */
array[i] = (int*)calloc(size_y, sizeof(int));
}
```
You can access the elements... |
Given the path, is there a way to find out whether the file exists without opening the file?
Thanks
|
The most efficient way isaccesswith theF_OKflag.
statalso works but it's much heavier weight since it has to read the inode contents, not just the directory.
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago.
I wrote below dll called djj.dll it... |
As Aaron Gallagher said,printis a Python keyword. Also it's unusual for a compiled DLL to use the standard Windows calling convention (i.e. windll). It's more likely to usecdecl(i.e. cdll). Here's an approach that should work:
```
djj = ctypes.cdll.LoadLibrary('djj.dll')
my_print = getattr(djj, 'print')
x = my_print(... |
i am reading high quality 16 bit random numbers of type uint16_t from /dev/random
and i am getting numbers as big as: 2936814755. Are these correct
```
int myFile = open("/dev/random", O_RDONLY);
unsigned int rand;
uint16_t randomNum = read(myFile, &rand, sizeof(rand)) ;
printf(" %u ", rand);... |
unsigned int probably isn't 16 bit on your pc architecture. If you want to be sure use uint16_t instead.
```
uint16_t rand;
int ret = read(myFile, &rand, sizeof(rand)) ;
```
I think you were confusing the return value of read (ret that should be int and is the numbers of bytes read) and the generated ran... |
I'm trying to create code which uses pointers to functions as parameteres, and I have to use a typedef.
I'm not a C pro. It feels like I'm getting there, but I can't seem to find a good explanation of the syntax of pointers to function.
I have a function fillArray:
```
long fillArray(long *array, int x, int y) {
//
... |
Your typedef needs to be:
```
typedef long (*fArray)(long *, int, int);
^
```
|
I'm writting application for embedded system. Where i can download gcc version 3.4.3 with glib version 2.3.4 for Cygwin ?
I have download cygwin-gcc-3.3.6-glibc-2.3.2-linux.tar.bz2 but this version isn't suitable for me...
|
Sometimes linux distributions have a 'compat' packages which make older libraries available. Try searching cygwin for the version of libstdc++ you're looking for.
|
For getting the random numbers I have a functiongetrand100()which returns a random number in the range of 1-100.
How can I get a random number between ranges1-20and1-200with the same function?
For 1-20 I can apply:
```
if(num>=1 && num <=20) then accept else reject
```
But what should I do for the1-200range?
|
I would propose
```
1 + getrand100() % 20
```
for the first case (20) and
```
(getrand100()%2)*100 + getrand100()
```
for the latter (200).
|
I have 4 int arrays. They all have the same number of elements. Something like this:
```
int ar1[] = {1,2,3,4};
int ar2[] = {10,12,13,14};
int ar3[] = {8,9,15,16};
int ar4[] = {17,18,19,20};
int big[][] ={ar1,ar2,ar3,ar4}; // I know this is messed up but here is where the question lies
```
Is there a way so th... |
Check this out:Multidimensional arrays in Candthis Wikipedia pagefor the general information on multidimensional arrays in C.
Your code should work with this:
```
int* big[] = {ar1, ar2, ar3, ar4};
```
|
The only thing that I know about the mechanism of how C passes values is that it is done either through a register or the stack.
Register or Stack? Exactly how?
|
Both. And the conventions will vary by platform.
On x86, values are usually passed by stack. On x64, passing by register is preferred.
In all cases, if you have too many parameters, some will have to be passed by stack.
Refer tox86 calling conventions
|
I know the fact that PF_PACKET-family socket requires root privilege,
but I don't know how that is configured on linux.
Anyone knows how, is it hard-coded in the kernel directly?
|
It used to be the case that it was just hard-coded in the kernel.
But starting with version 2.2, Linux has introduced capabilities (seehttp://linux.die.net/man/7/capabilities) and the kernel now checks for the CAP_NET_RAW capability - seenet/packet/af_packet.c.
The root user is still assumed to have all capabilities... |
Is it OK to use loop increment greater than 1?
```
#pragma omp parallel for schedule(dynamic, 1000)
for (int i=0; i<100000; i+=10)
{
// do something that uses i
}
```
Thank you.
|
Yes.
The allowed form for the for loop is:
```
for (init-expr; test-expr; incr-expr) structured-block
```
Where incr_expr is any of:
```
++var
var++
--var
var--
var += incr
var -= incr
var = var + incr
var = incr + var
var = var - incr
```
Seehttp://www.openmp.org/mp-documents/OpenMP3.1.pdfpage 40.
|
Consider the following code segment written in S-expr notation:
```
(lambda (x) (lambda (y) (+ x y)))
```
or in Javascript:
```
function(x) { return function(y) { return x+y; }; }
```
How do I write this in C?
|
This is difficult to do in C, since it relies on closures. With C you have to pass an explicit context, so you might end up with something like this.
```
#include <stdio.h>
struct closure {
int saved_x;
int (*function)(struct closure, int);
};
int second_half_add(struct closure context, int y) {
return ... |
I have the following:
int num=500;
char text[8];
how do I make it so that text ends up being the hex 0x500, or 1280?
edit: i see that its pretty simple to make it text, like in some of the answers. But I need this text to be interpreted as a hex by C. So in reality it should be an unsigned hex int.
|
There is an exercise in K&R, second chapter if I'm not mistaken, that asks to do this very thing. If you are having difficulties I suggest you look up hexadecimal aritmetic on Wikipedia.
|
Is there an interface in Linux to get notification of a network interface carrier change? I know its possible to poll an interface with SIOCETHTOOL, but was wondering if there was any way to get notified or any blocking calls that would return on carrier detection changes?
|
Do you need carrier transition or interface state change? For the interface state you could listen to the NETLINK_ROUTE netlink socket and wait for RTM_NEWLINK and RTM_DELLINK messages
|
I'm developing a texture atlas packer to use with OpenGL, and I'm currently looking for an open-source (it's better if it's a library, but an open-source software would be good as well!) solution that will render the best results for color palette creation / dithering. It really doesn't need to be fast, but needs to a... |
pngquant is available as a pure C library.
ImageMagickuses octtree, which is fast, but not the best quality.
pngquantuses MedianCut with several additional improvements, and is likely to give higher quality.
pngquant has speed/quality trade-off setting which can improve quality a bit further, and also has custom di... |
The second arg in the prototypes for memmove/memcpy/strcpy are similar:
For example:
```
void *memmove(void *dest, const void *src, size_t n); //const void*
char *strcpy(char *dest, const char *src); //const char*
```
But apparently, if dest and src overlap, then src's content will be altered, violating the const vo... |
const void*means that the referand will not be modifiedthrough that pointer.
If there are other, non-const pointers to the same object (also known as "aliasing"), then of course it can still be modified through those. In the scenario you describe, that other pointer isdest.
By the way, in the case ofstrcpy, behavior... |
I have a string which starts with the character\0- it's by design and I know its actual length.
How can I print its representation using escapes like"\0foo\0bar\0", if I know its length?
|
Well, you should be able to print it as an array:
print *str@length
|
I want to know how I can include special characters in C Strings, i.e.:
```
char a[] = "Hello \120"; // This is just an example
```
Thenashould contain"Hello <120th character>".
How can I do this in C?
|
In hex:char a[] = "Hello \x78";
|
I've got a quick question; I have an IPv4 in a C string (say "192.168.0.1") and I want to convert it to an uint32_t. I'm sure there should be some function for that but I havn't found it. Any ideas?
|
The function is calledinet_aton.
```
int inet_aton(const char *cp, struct in_addr *inp);
```
The structure in_addr is defined in<netinet/in.h>as:
```
typedef uint32_t in_addr_t;
struct in_addr {
in_addr_t s_addr;
};
```
Of course you can also use the newer functioninet_pton.
|
Input: BDCAbaxz
OUTPUT: AaBbCDxz
My solution is straight forward and ugly:
Sort the input with quick sort, then we get "ABCDabxz"Alloc a temp array with the same size as the original one, then take the appropriate element from two sub-array(ptr1-->A, ptr2--->a)Copy the temp array back to the original one
Anyfaste... |
Yes.
Define a comparator forqsortthat gives you the ordering you want in the first place (so rather than usingAB...YZab...yzas the sort order, have it enforceAaBb...YyZz).
|
I am modifying an old code, where it uses the deprecatedsys_errlistandsys_nerrwhich are deprecated. Can someone tell me its replacement?
Also it will be great, if someone tells us about its functionality.
Here is the code:
```
37 static const char *
38 stringErrorReport(void)
39 {
40 #if ( defined(sgi) )
41 ... |
This function is a wrapper around strerror(), and tries to supply it's own replacement on systems where it assumes strerror() is not available. If even sys_errlist and sys_nerr are not available, it fails. But it has at least tried ...
|
I have one text field.
Below function is attached to an UI event "editing changed" from txtfield's IB.
The function is recursive as obvious I am changing the textfield so it will call
again and again is there any thing , I can stop the function after calling it once.
So,I want to stop this looping function..
```
... |
My variant
```
-(IBAction) testEvents:(id) sender
{
static BOOL flag = NO;
if (flag) {flag=NO; return;}
flag = YES;
txtEditAmount.text=[txtEditAmount.text substringToIndex:([txtEditAmount.text length]-1)];
}
```
|
```
#include<stdio.h>
int i;
int increment(int i)
{
return ++i;
}
int main()
{
for(i=0;i<10;increment(i))
{
printf("%d",i);
}
return 0;
}
```
Here output is 000000. i.e. infinite lopp occurs.
I want to know that is this occuring due to no-op as we have no variable to store the value of... |
Yes, it's a no-op. The call toincrementdoesn't change anything since the value is passed by value.
The local definition ofishadows the global definition. Therefore, only the local definition ofiis used and the global definition ofiis not affected by the increment which is done on the local copy of the variable.
|
i want to add "/." to a file name, for example,i have file name "abc", i want to get a name "abc/.abc",how to do it in C?
strcpy("/.",name) and strcat("/.",name) returned segmentation fault.
Thanks
|
The first parameter tostrcatmust be amodifiablestring with enough space allocated to hold the resulting string and the terminating zero byte. The first parameter tostrcpymust point to allocated,modifiablememory with sufficient space to hold the resulting copy of the string and the terminating zero byte. In both of you... |
I want to know how I can include special characters in C Strings, i.e.:
```
char a[] = "Hello \120"; // This is just an example
```
Thenashould contain"Hello <120th character>".
How can I do this in C?
|
In hex:char a[] = "Hello \x78";
|
I've got a quick question; I have an IPv4 in a C string (say "192.168.0.1") and I want to convert it to an uint32_t. I'm sure there should be some function for that but I havn't found it. Any ideas?
|
The function is calledinet_aton.
```
int inet_aton(const char *cp, struct in_addr *inp);
```
The structure in_addr is defined in<netinet/in.h>as:
```
typedef uint32_t in_addr_t;
struct in_addr {
in_addr_t s_addr;
};
```
Of course you can also use the newer functioninet_pton.
|
Input: BDCAbaxz
OUTPUT: AaBbCDxz
My solution is straight forward and ugly:
Sort the input with quick sort, then we get "ABCDabxz"Alloc a temp array with the same size as the original one, then take the appropriate element from two sub-array(ptr1-->A, ptr2--->a)Copy the temp array back to the original one
Anyfaste... |
Yes.
Define a comparator forqsortthat gives you the ordering you want in the first place (so rather than usingAB...YZab...yzas the sort order, have it enforceAaBb...YyZz).
|
I am modifying an old code, where it uses the deprecatedsys_errlistandsys_nerrwhich are deprecated. Can someone tell me its replacement?
Also it will be great, if someone tells us about its functionality.
Here is the code:
```
37 static const char *
38 stringErrorReport(void)
39 {
40 #if ( defined(sgi) )
41 ... |
This function is a wrapper around strerror(), and tries to supply it's own replacement on systems where it assumes strerror() is not available. If even sys_errlist and sys_nerr are not available, it fails. But it has at least tried ...
|
I have one text field.
Below function is attached to an UI event "editing changed" from txtfield's IB.
The function is recursive as obvious I am changing the textfield so it will call
again and again is there any thing , I can stop the function after calling it once.
So,I want to stop this looping function..
```
... |
My variant
```
-(IBAction) testEvents:(id) sender
{
static BOOL flag = NO;
if (flag) {flag=NO; return;}
flag = YES;
txtEditAmount.text=[txtEditAmount.text substringToIndex:([txtEditAmount.text length]-1)];
}
```
|
```
#include<stdio.h>
int i;
int increment(int i)
{
return ++i;
}
int main()
{
for(i=0;i<10;increment(i))
{
printf("%d",i);
}
return 0;
}
```
Here output is 000000. i.e. infinite lopp occurs.
I want to know that is this occuring due to no-op as we have no variable to store the value of... |
Yes, it's a no-op. The call toincrementdoesn't change anything since the value is passed by value.
The local definition ofishadows the global definition. Therefore, only the local definition ofiis used and the global definition ofiis not affected by the increment which is done on the local copy of the variable.
|
i want to add "/." to a file name, for example,i have file name "abc", i want to get a name "abc/.abc",how to do it in C?
strcpy("/.",name) and strcat("/.",name) returned segmentation fault.
Thanks
|
The first parameter tostrcatmust be amodifiablestring with enough space allocated to hold the resulting string and the terminating zero byte. The first parameter tostrcpymust point to allocated,modifiablememory with sufficient space to hold the resulting copy of the string and the terminating zero byte. In both of you... |
I'm working on an iPad app that has a several complex tables I think might be best represented as HTML tables, except the data's all dynamic (variable number of columns and rows and cell contents). Since the rest of the app is all in C, is it possible to embed C in UIWebView to generate the dynamic content? Otherwise,... |
You could useloadHTMLString:buffer baseURL:nilto load in dynamically generated HTML. It would only be as difficult as you make it. In the simplest case, for each table you add<table>to the buffer, then for each row add the<tr>tags and for each column within the row add your<td>and print the data for that cell. At the ... |
For some reason I'm getting an error:statement with no effecton this statement.
```
for (j = idx; j < iter; j + increment) {
printf("from loop idx = %i", (int)idx);
punc(ctxt, j);
}
```
|
You probably meant to writej += incrementinstead ofj + increment.
|
There is such code:
```
#include <stdio.h>
int main() {
float d = 1.0;
int i = 2;
printf("%d %d", d, i);
getchar();
return 0;
}
```
And the output is:
```
0 1072693248
```
I know that there is error in printf and first %d should be replaced with %f. But why variable i is printed wrong (1072693248 instea... |
Since you specified%dinstead of%f, what you're really seeing is the binary representation ofdas an integer.
Also, since the datatypes don't match, the code actually has undefined behavior.
EDIT:
Now to explain why you don't see the2:
floatgets promoted todoubleon the stack. Typedoubleis (in this case) 8 bytes long... |
```
#include<stdio.h>
#include<string.h>
int main()
{
char a[]="aaa";
char *b="bbb";
strcpy(a,"cc");
printf("%s",a);
strcpy(b,"dd");
printf("%s",b);
return 0;
}
```
We could not modify the contents of the array but the above program does not show any compile tim... |
Array is not a constant datatype but a literal string like "aaa" is. You cannot modify it's content.
|
```
#include "stdafx.h"
#include<stdio.h>
int aarray[]={1,2,3,4,5,6,7,8};
#define SIZE (sizeof(aarray)/sizeof(int))
int main()
{
printf("%d\n",SIZE);
if(-1<=SIZE)printf("1\n");
else printf("2\n");
return 0;
}
```
Why does this prints 2? The SIZE is 8 which is greater than -1 so it should have printed... |
You are comparing a signed value (-1) and an unsigned value (the value produced bySIZEissize_twhich is unsigned).
Thus-1is promoted to an unsigned and becomes larger thanSIZE.
|
Is it safe to assume that the count returned fromQueryPerformanceCounterrelates to the time since the last system boot? Or could it be reset while the system is running? The MSDN article itself doesn't guarantee this, however I've seen some 3rd party information (such asthis) that says that this is the case.
|
It's meant to be used for relative times. But I don't think it can be used to measure time since boot.
From what I hear, it's implemented using therdtscinstruction which measures "pseudo" CPU cycles since the CPU was powered on. In that case, yes, it probably does give the time since boot, but I don't think this is s... |
My question is whether is it a good idea to mix OpenMP with pthreads. Are there applications out there which combine these two. Is it a good practice to mix these two? Or typical applications normally just use one of the two.
|
Typically it's better to just use one or the other. But for myself at least, I do regularly mix the two and it's safe if it's done correctly.
The most common case I do this is where I have a lower-level library that is threaded using pthreads, but I'm calling it in a user application that uses OpenMP.
There are some... |
I just installedEclipseCDTwithMinGW.
All the environment variables are set, includes, etc. Tried running a hello world and everything seems to be fine.
I tried loading aCproject that I had before in my computer, it seems to load everything fine, yet I get the following error with theNULLsymbol :
```
Symbol 'NULL' co... |
NULL is usually defined in stddef.h. This file is also usually included with stdlib.h and stdio.h.
And, you could always do this:
```
#ifndef NULL
#define NULL ((void *) 0)
#endif
```
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago.
According to the official descripti... |
It is parsed as:
```
b = (a++)++ + a;
```
This is an invalid expression. The increment operator can't be applied twice as(a++)isn't an lvalue.
The tokenizer isn't context-aware and will match the longest token possible, so it is not parsed as the syntactically valida++ + ++a. (That still would be invalid code, thou... |
I want to write a program that checks for the existence of a directory; if that directory does not exist then it creates the directory and a log file inside of it, but if the directory already exists, then it just creates a new log file in that folder.
How would I do this in C with Linux?
|
Look atstatfor checking if the directory exists,
Andmkdir, to create a directory.
```
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
struct stat st = {0};
if (stat("/some/directory", &st) == -1) {
mkdir("/some/directory", 0700);
}
```
You can see the manual of these functions with theman 2 s... |
Anyone please elaborate what is happining here?
```
int main()
{
int **p = 0;
//p=? and why| *p=? and why|**p=? and why
++p;
//p=? and why| *p=? and why|**p=? and why
printf("%d\n", p);
return 1;
}
```
output:-
4 (why?)
|
First of all,pis a pointer to a pointer-to-integer.
int **p = 0;
p= 0,*p= nothing,**p= less than nothing.
++p;
Same as p = p + 1. Means thesize of one pointer to a pointer-to-intfurther. A pointer is basically, at least on your OS, 32 bits length (4 bytes).pnow points 4 bytes after 0. The value ofpis4.
|
What are the benefits of using
variadic functions
```
void fun(int i, ...);
```
instead of passing a pointer to an array?
```
void fun(int i*);
```
When are variadic functions preferred?
|
You have to explicitly create the array first. In addition, it would be problematic if you wanted to specifyparameters of different types.
Variadic functions do not require creating any array and they can deal with different types.
As an example, I could not bare to use theprintf-functions if I always had to create ... |
I want to write a linked list that can have the data field store any build-in or user-define types. In C++ I would just use a template, but how do I accomplish this in C?
Do I have to re-write the linked list struct and a bunch of operations of it for each data type I want it to store? Unions wouldn't work because wh... |
There's a reason people use languages other than C.... :-)
In C, you'd have your data structure operate withvoid*members, and you'd cast wherever you used them to the correct types. Macros can help with some of that noise.
|
I want to create a linked list, but I want the data field to be either int or float. I wrote some code like the following:
```
union int_or_float
{
int int_member;
float float_member;
};
struct node
{
union int_or_float data;
struct node *next;
};
```
I want to write stuff like:
```
typedef struct... |
You don't. The fundamental thing about unions is that it can be whatever data you put into it.
If you write toint_member, then it'll hold an int.
If you write tofloat_member, it'll hold a float. (And if you subsequently read fromint_memberall hell breaks loose.)
|
I'm new to C and I have created the following code, but when run the program crashes. Why? How do I stop it crashing?
```
char *get()
{
char *n;
printf("\n user name : ");
scanf("%s", &n);
return n;
}
int main()
{
char *c = get();
printf("%s", c);
return 0;
}
```
|
In C it is typical for the parent to handle memory allocation since there's no garbage collector to clean up after yourself, so it has to do that anyway:
```
void get(char *n)
{
printf("\n user name : ");
scanf("%s", n);
}
int main()
{
char c[200];
get(c);
printf("%s", c);
return 0;
}
```
h... |
As part of our php data test framework, we start by dropping & creating a test database for the user running the test (let's call him 'foo').
Our template1 does not have a public schema. This is because we need the test db to have 'public' owned by 'foo' (and by default, even if 'foo' creates a db, Postgres will make... |
You could temporarily treatclanguage astrusted languageand install tablefunc as non-superuser:
```
UPDATE pg_language SET lanpltrusted = true WHERE lanname LIKE 'c';
```
See myprevious answerfor more details
|
If I doLoadLibrary("%windir%\\system32\\ole32.dll")does that mean Windows will ONLY load from "c:\windows\system32\ole32.dll" ? Also does LoadLibrary() in C understand the environment variable?
|
as Serge said and carefully tested, LoadLibrary does not do environment variable substitution in path.
however, there is a function in the windows API to replace environment variables in strings:ExpandEnvironmentStrings(). you can perform the required substitution on your path before callingLoadLibrary().
|
I'm converting some legacy embedded-Ingres C code to work against Oracle. I've found references to functions "inquire_ingres()" and "inquire_sql()," which, per the docs athttp://docs.ingres.com/ingres/9.3/sql-reference-guide/2275-inquiresql-function, allow a program to gather runtime information about the status and... |
It looks like the answer is: you have to paw around in the innards ofsqlca. There's a lot of good information buried in that struct though -- check outhttp://infolab.stanford.edu/~ullman/fcdb/oracle/or-proc.html#sqlcafor some details.
|
Is it possible to create thread local data in a linux kernel module?
I need to store some data for each process/thread calling my module.
Is there an easy way of using thread local data, or do I have to resort to
writing a hash map which uses the pid of the current process as a key?
|
Assuming the interface to you kernel module is a character device driver, then you have a private_data field in the file struct (which is analogous to user space file descriptor) exactly for that.
Just allocate and assign a pointer to your structure of choice at the open file operation to it.
It's not exactly thread... |
I want to print doubles in decimal notation with full precision (but without extra zeros at the end of the number). In C++ I can use:
```
std::setprecision(20);
cout << d; // Here d is a double
```
What would be the equivalent C code using printf?
|
You can use the "%.20g" specifier. g is IMHO usually better than f since it doesn't print trailing zeros, and handles large/small values sensibly (changing to e format).
Also note that with the "g" specifier, the precision (the "20" in this case) specifies the number of significant digits rather than the number of di... |
Is there any functionality in Eclipse which would generate empty function implementations by their prototypes in the included headers ?That is say I create some *.c file and write#include something.hin it, and I want Eclipse to suggest/generate empty functions which prototypes are defined in something.h.
Or at least c... |
The closest thing available in current Eclipse is the menu option Source/Implement method.
Which is, admittedly, not all that close. See:
http://wiki.eclipse.org/CDT/C_editor_enhancements/Source/header_synchronization
You could also look at an external tool like
http://www.radwin.org/michael/projects/stubgen/
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do... |
The canonical library to render SVG islibrsvg. You may want to check that out.
|
I have the following single linked list,I always get the length as 1,even if i push 3 elements,and always only one node is created.Please help.Thanks.
```
#include <stdio.h>
struct node
{
int data;
struct node *next;
};
void push(struct node **head,int data)
{
struct node *temp = (struct node*)malloc(s... |
Replaceifbywhilein the length function
|
I am trying to figure out the algorithm to this but all I get with google is doing it with casting. I need to know the details.
So if we have a float x and want to return its binary representation what do we need to do?
I know we need to return the float if its NaN or a infinity but otherwise what are the steps?
ED... |
Alternatively, use a union:
```
typedef union
{
float f_;
int i_;
} FloatBits;
FloatBits fb;
fb.f_ = 1.5;
```
Thenfb.i_contains the float mapped onto anintto allow extraction of the bits. Again, usual assunptions about the size of types - you can verify these usingsizeof.
Using this approach, you can p... |
I am trying to implement an algorithm within an iOS app that will make use of large bitmasks. Each bitmask can be up to 256 bits (32 bytes) in length. I will need to quickly get/set bits at arbitrary locations within the mask, etc.
Are there any built-in language features of C or Objective-C that makes this kind of t... |
Take a look atCFMutableBitVector, which is designed to handle this kind of problem.
|
I'm Loading a certain Exe in My Program and I'm trying to replace It's Version Info Resource.I'm Using UpdateResource() but for some reason It isn't replacing the original resource as it is supposed to do.
```
UpdateResource(hHandle,RT_VERSION,"1",MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),pRsrcMemory,rsrcSize)
```
... |
Resource IDs can be either strings or numbers. Which is the problem here, it is not resource ID "1", it is MAKEINTRESOURCE(1).
Fun puzzler.
|
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
You've misspelled "str_list_element_struct" as "str_list_element_scruct" in the typedef.
|
language is C with gcc compiler
if i make a struct like so
```
struct test {
char item_1[2];
char item_3[4];
char item_4[2];
char item_5[2];
char item_6[4];
};
```
and i do a sizeof(struct test) it returns 14(bytes). which is the expected result.
but if i do
```
struct test {
int16_t it... |
You have mixed 32/16 bit integers.
```
int16_t item_1[2]; // 2 * 2 = 4
int32_t item_3[4]; // 4 * 4 = 16
int16_t item_4[2]; // 2 * 2 = 4
int16_t item_5[2]; // 2 * 2 = 4
int32_t item_6[4]; // 4 * 4 = 16
// sum = 44
```
|
I've been searching to no avail for a set of routines to do conversion between JSON and XML. I have found such routines in Javascript, Java, PHP, and Python, but not in C or C++.
FWIW, my json library is json-spirit. I am currently processing JSON, and would like to add XML support via a conversion layer (convert inc... |
By far, the only specifically designed C++ library that directly converts XML to JSON I found on the Internet isxml2json:https://github.com/Cheedoong/xml2json
You can also convert JSON to XML if following the same rules.
|
I need R header files to compile something. I installed R on ubuntu via:
```
sudo apt-get r-base-dev
```
R works fine. But I can't find the R headers such as Rmath.h. I get this error when I try to compile:
```
gcc -g -std=c99 -I/usr/include -O3 -lRmath -lm -lpthread -o qcpg qcpg.c
In file included from qcpg.c:1:0... |
You also want to do
```
sudo apt-get install r-mathlib
```
which contains, among other things, the file/usr/include/Rmath.h.
|
If I have a program that is using scanf to get user inputted data:
```
scanf("%d",&val);
```
When I run it through lint I get warnings saying that scanf returns a int and it is not being assigned anywhere. What is the c practice to solve this problem? Do I type cast it as void?
```
(void)scanf("%d",&val);
```
|
The C best practice to solve this warnings is simple: Check the resultcode. The scanf function returns in the int if the operation has gone ok or not, and stores the error usually in errno.
The lack of resultcode checks usually results in big errors in certain situations.
|
I have a "generic" linked link in C that takesvoid * datato store the data in a Node.
```
insertNode(linkedList * list, void *data);
//Storing/retrieving a string works fine;
char *str="test";
insertNode(list, str);
char *getback=(char *)node->data;
//Storing/retrieving an Int results a cast warning
int num=1;
ins... |
Useintptr_toruintptr_t. They are integers of the same size as a pointer:
```
#include <stdint.h>
...
intptr_t num = 1;
insertNode(list, (void *) num);
intptr_t getback = (intptr_t) node->data;
```
Of course, the maximum value that you can store depends on the system, but you can examine it at compile time viaINTPTR_... |
I'm trying to make coroutine and continuation with C. I realized I need some kind of spaghetti stack. Is it possible to execute a function within a new call-stack? Of course within single thread. How can I make a new, separated call-stack, and execute some code on it?
|
check out makecontext/swapcontext.
If those aren't available, then you could use setjmp/longjmp, but those are a little more complex.
|
What is the default WindowProc of a list-view control before I change it usingSetWindowLong()?
|
That's determined by the system when it registers the window class. It is presumably implemented in comctl32.
There's nothing special about one of the built-in window classes in this regard. Just as is the case for a user defined class, the default window proc is whatever was specified when the class was registered.
|
The return value of an open() was -1 and on trying to find the error using perror() the output was "File exists".
How do I find the error or the reason for the file not opening.
|
Looks like
EEXISTpathname already exists and O_CREAT and O_EXCL were used.
|
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
Why is it required to initialise the references during its initialisation. If not initialised it throws err... |
In C there are no references. You probably mean address operator:http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Faddre.htm
|
Note that in general,doubleis different fromlong double.
strtodconverts string todouble, but which function should be use to converting string to long double?
|
In C++03, useboost::lexical_cast, or:
```
std::stringstream ss(the_string);
long double ld;
if (ss >> ld) {
// it worked
}
```
In C99, usestrtold.
In C89, usesscanfwith%Lg.
In C++11 usestold.
There may be subtle differences as to exactly which formats each one accepts, so check the details first...
|
I'm looking for some way of splitting the console into distinct zones, a bit likescreendoes.
The idea is to "freeze" the first X lines, so that they display fixed information, only updated from time to time, while the remaining lines keep working like normal. I've seen this in an application running on an ARM Linux d... |
I assume you can make use of theNCurses libraryto achieve the user experience you describe.
|
I need to create three bit masks that end up in three 32-bitunsigned ints(let's call them x, y and z). The masks should end up like this:
```
x: 0000 0001 1111 1111 1111 1111 1111 1111
y: 0000 1110 0000 0000 0000 0000 0000 0000
z: 1111 0000 0000 0000 0000 0000 0000 0000
```
So far I've got this:
```
unsigned int x ... |
```
unsigned int x = 0x01FFFFFF,
y = 0x0E000000,
z = 0xF0000000;
```
Is this readable for you?
|
I am using theandroid/log.hmethods in my native code to write to the android log (__android_log_write(ANDROID_LOG_INFO, ANDROID_DEBUG_TAG, message);). I am also doing logging in the Java code. However, when running, only the log messages from the Java code is displayed in the logger. What could cause these problems?
... |
I'm not sure, but I use__android_log_printin my NDK code and that works fine. I don't know the difference between the two methods off the top of my head, but give that a try (it takes the same arguments).
|
I have a structure like this
```
typedef struct{
int stat;
}dot;
```
And I would like to acces this structure in a procedure like this
```
void change(dot *stat){
stat[5][5].stat = 5;
}
int main(){
dot mydottes[10][10];
mydottes[5][5].stat = 3;
change(&mydottes);
return 0;
}
```
But when I ... |
Change your code as follows:
```
void change(dot stat[][10]){ // <<<
stat[5][5].stat = 5;
}
int main(){
dot mydottes[10][10];
mydottes[5][5].stat = 3;
change(mydottes); // <<<
return 0;
}
```
|
I want to be able to tell when my program's stdout is redirected to a file/device, and when it is left to print normally on the screen. How can this be done in C?
Update 1: From the comments, it seems to be system dependent. If so, then how can this be done with posix-compliant systems?
|
Perhapsisatty(stdout)?
Edit: As Roland and tripleee suggest, a better answer would beisatty(STDOUT_FILENO).
|
What is exactly the difference between commands exec(const char *c) and system(const char *c) in unix based systems ?
Both can be called from a C program to execute system calls. Is there a difference b/w the two ?
|
execreplaces your process with the specified program. Your program is done, and will not continue running.
spawnstarts a new process (probably by first usingfork), and runs the specified program while your program continues executing.
systemstarts a new process (probably by first usingfork), and runs the specified ... |
I use this method for doing malloc over a 2d array, my sources arehttp://c-faq.com/aryptr/dynmuldimary.htmlandModify malloc strategy for 2D Array so malloc succeeds:
```
int
main(int argc, char *argv[])
{
long **array = NULL;
array = malloc(5 * sizeof(long *));
for (int i = 0; i < 5; i++)
array[i... |
You're invoking undefined behaviour. Undefined behaviour, as its name implies, isn't defined to cause a segmentation fault. That code could set the value of that memory to the value you're giving it, it could ignore the assignment completely, or it could order pizza for all we know.
|
I was asked this as interview question. Couldn't answer.
Write a C program to find size of structure without using thesizeofoperator.
|
```
struct XYZ{
int x;
float y;
char z;
};
int main(){
struct XYZ arr[2];
int sz = (char*)&arr[1] - (char*)&arr[0];
printf("%d",sz);
return 0;
}
```
|
I want to connect to oracle database using C language in Windows OS. But I do not how to start with it and what will be pre-requisite?
can any one provide me any help or tutotial or sample code?
Thank you.
|
http://www.dreamincode.net/forums/topic/30799-how-to-connect-c-with-oracle/
Oracle C++ Call Interface (OCCI) is an Application Programming Interface (API) that provides C++ applications access to data in an Oracle database.
To know more about the OCCI refer here
http://www.oracle.com/technetwork/database/features/o... |
I've looked through the docs and it seems that you can only execute an xpath search from axmlDocPtrby creating anxpath context. Is there anyway inlibxml2to xpath search from axmlNodePtr?
|
CallxmlXPathNewContext(), specifying the real top-levelxmlDocPtrfor the document, then set thexmlXPathContext::nodefield to the desiredxmlNodePtrpointer that is a child of thexmlDocPtrdocument.
|
I am trying to understand the for loop better. I have the following variables:
x = 1
y = 10
I want to increment x and double it ten times with a for loop to have the following output: 1, 2, 4, 8, 16, etc.
This is what I have, but it is not quite doing the trick:
```
int x = 1;
int y = 10;
for (int i = 0; i < y;... |
It looks fine to me. If you want it to print at each iteration, you need to move theprintfinto the loop.
Also, your code will only work in C99 or with GCC's default extensions since you haveint iinside theforloop.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.