question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I'm porting a python C module from 2.7.x over to python 3.3. One of the issues I ran into is thatPy_FlushLineisn't defined in the python headers from what I can tell.
How should the following code snippet be modified to work in python 3.3?
```
if (Py_FlushLine()) PyErr_Clear();
```
What's more interesting is that s... |
Py_Flushlineused to look like this:
```
int
Py_FlushLine(void)
{
PyObject *f = PySys_GetObject("stdout");
if (f == NULL)
return 0;
if (!PyFile_SoftSpace(f, 0))
return 0;
return PyFile_WriteString("\n", f);
}
```
Since Py3k no longer has the concept of softspa... |
I'd like to be able to see which header is actually included when I compile. For example, I have two very different check.h files (one is a linux-header thing, the other from the unit test system).
Is there a setting in gcc or some language command/macro that would show where header files are being included from?
|
You can use the-Eflag.
```
gcc -E source.c
```
This will show you the “annotated” preprocessed source, including the absolute paths of headers included using<>and relative paths of headers included using"". Keep in mind that it will be a lot to trudge through, especially if you include a lot of system headers (which... |
Suppose
```
long long b = 5*1024*1024*1024; // 5 gigs, small enough for 64 bits
printf ("%lu\n",sizeof(long long)); // prints 8 (bytes) = 64 bits
```
but the compiler complains:
```
warning: integer overflow in expression [-Woverflow]
```
Why does it overflow, what am I missing?
|
Because the numbers on the right hand side are of typeint, notlong long, sointarithmetic is performed in the expression, leading to an overflow.
If you addLLto one of them, it'll promote them all.
|
I am trying to do some hacks over the glibc, and I wanted to know whether it's possible to redefine function-like macros ?
For example,<tgmath.h>has the following macro:
```
#define expm1(Val) __TGMATH_UNARY_REAL_ONLY (Val, expm1)
```
How to redefineexpm1as :
```
#define expm1(Val) __TGMATH_UNARY_REAL_IMAG (Val, e... |
Exactly. Just undefine it first.
```
#ifdef expm1
#undef expm1
#endif
#define expm1(Val) __TGMATH_UNARY_REAL_IMAG (Val, expm1, cexpm1)
```
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
I suggest you to usencurses(screenshot).
For tutorial, check thisHOW-TO.
|
This question already has answers here:Split string with delimiters in C(25 answers)Closed10 years ago.
I have a program that read File in C. Now I want to put the strings divide by space into an array. How do I do it?
```
#include <stdio.h>
int main()
{
char line[30];
char names[100][20];
int sizes[100];
int i = 0;... |
Have a look at the functionstrtokorstrtok_r
http://www.cplusplus.com/reference/cstring/strtok/?kw=strtok
|
This is purely out of interest. I searched around a bit, knowing that instances ofclassesare calledobjects, but I couldn't find what the correct word is for an instance of astructin C, C++, C#, etc. Do we even have a word for this?
|
It is perfectly valid to call it an object even in C.
C99 Standard §3.15:Para 1:
objectregion of data storage in the execution environment, the contents of which can represent
values
|
Visual C++ hasan intrinsic function called_AddressOfReturnAddresswhich returns theaddressof the current function's return address on the stack.
Notethat this isnotthe same as_ReturnAddress, which only returns acopyof the return address.
Is there any equivalent for_AddressOfReturnAddressin Clang/LLVM?
|
Asrustyxpointed out, Clang/LLVM (and GCC) provides__builtin_return_address()which is equivalent to_ReturnAddress(). Clang/LLVM also provides__builtin_frame_address()which (depending on the particulars of your ABI, architecture, etc.) may be somewhat analogous to_AddressOfReturnAddress().
As an example, the following ... |
This question already has answers here:Using pthread.h on a windows build(3 answers)Closed10 years ago.
Where can I download the pthread.h, semophore.h and their libraries for C?
I need to download for windows. And also please give the linking procedure for VS2010.
|
Windows got its own threading mechanism and is not dependent on pthread etc, similarly it also got semaphores (http://msdn.microsoft.com/en-us/library/windows/desktop/ms686946(v=vs.85).aspx), but there are pthread port for windowshttp://sourceware.org/pthreads-win32/, you can give it a try.
|
Now I'm working on NVAPI.
There is a type "NvAPI_UnicodeString".
It is a unsigned short array.
```
typedef NvU16 NvAPI_UnicodeString[NVAPI_UNICODE_STRING_MAX];
typedef unsigned short NvU16;
```
and there is a type "NvAPI_LPCWSTR", also.
```
typedef const NvU16 *NvAPI_LPCWSTR;
```
I want assign a value to NvAPI... |
You cannot assign an array using the = operator.
You have to use memcpy or memcpy_s
```
NvAPI_UnicodeString wsz;
memcpy_s(wsz, sizeof(wsz), L"Hello", 6*sizeof(wchar_t));
```
|
This question already has answers here:Accessing an array out of bounds gives no error, why?(18 answers)Closed10 years ago.
I have a program which I expect it to crash but it doesn't. Can you please let me know the reason.
```
char a[5];
strncpy(a,"abcdefg",7);
a[7] = '\0';
printf("%s\n",a);
```
Shouldn't the progr... |
Size of a array is fivechar a[5];and your are assigning at 7th location that isbuffer overrunproblem and behavior of your code is Undefined at run time.
```
strncpy(a,"abcdefg",7);
a[7] = '\0';
```
Both are wrong, you need to defined array like:
```
#defined size 9 // greater then > 7
char a[size];
```
notice"abc... |
This question already has answers here:Is short-circuiting logical operators mandated? And evaluation order?(7 answers)Closed6 years ago.
I have a question concerning pre and post increments with logical operators
if I have this code
```
void main()
{int i = - 3 , j = 2 , k = 0 , m ;
m=++i||++j&&++k;
printf("%d %d %... |
This is what you get from short circuiting.++iis -2, and the rest doesn't have to be evaluated (and isn't according to the standard). The left side of||is true because -2 is not 0, so the whole expression is true.
|
Hi I'm having problems displaying a 2d char array.
Below is the functions which generates the data which the function below that will be using. it takes an input and creates a 2d char array of the tokens. From observing in VS2012 this works correctly.
Cheers
|
Further to chris' comment (Refer to:Can a local variable's memory be accessed outside its scope?) , I feel to make your program work, you need to reconsider the allocation oftokensinTokStrfunction.
You could modify this declarationchar *tokens[10];to following piece of code. With this change, your code should work fi... |
This is purely out of interest. I searched around a bit, knowing that instances ofclassesare calledobjects, but I couldn't find what the correct word is for an instance of astructin C, C++, C#, etc. Do we even have a word for this?
|
It is perfectly valid to call it an object even in C.
C99 Standard §3.15:Para 1:
objectregion of data storage in the execution environment, the contents of which can represent
values
|
Visual C++ hasan intrinsic function called_AddressOfReturnAddresswhich returns theaddressof the current function's return address on the stack.
Notethat this isnotthe same as_ReturnAddress, which only returns acopyof the return address.
Is there any equivalent for_AddressOfReturnAddressin Clang/LLVM?
|
Asrustyxpointed out, Clang/LLVM (and GCC) provides__builtin_return_address()which is equivalent to_ReturnAddress(). Clang/LLVM also provides__builtin_frame_address()which (depending on the particulars of your ABI, architecture, etc.) may be somewhat analogous to_AddressOfReturnAddress().
As an example, the following ... |
This question already has answers here:Using pthread.h on a windows build(3 answers)Closed10 years ago.
Where can I download the pthread.h, semophore.h and their libraries for C?
I need to download for windows. And also please give the linking procedure for VS2010.
|
Windows got its own threading mechanism and is not dependent on pthread etc, similarly it also got semaphores (http://msdn.microsoft.com/en-us/library/windows/desktop/ms686946(v=vs.85).aspx), but there are pthread port for windowshttp://sourceware.org/pthreads-win32/, you can give it a try.
|
Now I'm working on NVAPI.
There is a type "NvAPI_UnicodeString".
It is a unsigned short array.
```
typedef NvU16 NvAPI_UnicodeString[NVAPI_UNICODE_STRING_MAX];
typedef unsigned short NvU16;
```
and there is a type "NvAPI_LPCWSTR", also.
```
typedef const NvU16 *NvAPI_LPCWSTR;
```
I want assign a value to NvAPI... |
You cannot assign an array using the = operator.
You have to use memcpy or memcpy_s
```
NvAPI_UnicodeString wsz;
memcpy_s(wsz, sizeof(wsz), L"Hello", 6*sizeof(wchar_t));
```
|
This question already has answers here:Accessing an array out of bounds gives no error, why?(18 answers)Closed10 years ago.
I have a program which I expect it to crash but it doesn't. Can you please let me know the reason.
```
char a[5];
strncpy(a,"abcdefg",7);
a[7] = '\0';
printf("%s\n",a);
```
Shouldn't the progr... |
Size of a array is fivechar a[5];and your are assigning at 7th location that isbuffer overrunproblem and behavior of your code is Undefined at run time.
```
strncpy(a,"abcdefg",7);
a[7] = '\0';
```
Both are wrong, you need to defined array like:
```
#defined size 9 // greater then > 7
char a[size];
```
notice"abc... |
This question already has answers here:Is short-circuiting logical operators mandated? And evaluation order?(7 answers)Closed6 years ago.
I have a question concerning pre and post increments with logical operators
if I have this code
```
void main()
{int i = - 3 , j = 2 , k = 0 , m ;
m=++i||++j&&++k;
printf("%d %d %... |
This is what you get from short circuiting.++iis -2, and the rest doesn't have to be evaluated (and isn't according to the standard). The left side of||is true because -2 is not 0, so the whole expression is true.
|
Hi I'm having problems displaying a 2d char array.
Below is the functions which generates the data which the function below that will be using. it takes an input and creates a 2d char array of the tokens. From observing in VS2012 this works correctly.
Cheers
|
Further to chris' comment (Refer to:Can a local variable's memory be accessed outside its scope?) , I feel to make your program work, you need to reconsider the allocation oftokensinTokStrfunction.
You could modify this declarationchar *tokens[10];to following piece of code. With this change, your code should work fi... |
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.
I am trying to make an exe version ... |
Code blocks passes the arguments to the executable on the command line. In cmd, you must do that manually since the settings in code blocks no longer apply.
|
Let's say I have achar*called code, and it has"0x41"in it.
```
char *code = "0x41";
```
How can I convert that into anunsigned int? (To be exact, I need aWORD, but that's just anunsigned int).
|
```
unsigned int h;
sscanf(code, "%x", &h);
```
EDITtaking account of the remark ofExP:%xcould catch the value in the string"0x41"
|
I have following two questions
Given the statement like char * str = "999999999999"; how does compiler determine how much space to allocate on stack?How can i iterate over the memory pointed by str and determine the value of various bits inside it?
|
"999999999999"is not on the stack. The pointer may be on the stack, the compiler knows how big the pointer should be. The"999999999999"really has a null termination that lets you know when it is at the end.To iterate over each bit, maybe something like:for(i=0; str[i]; i++) // str[i] will evaluate to false(0) when ... |
I'm kinda new at unix programming and I need some help.
I'd like to do something like busy-waiting with a semaphore.
I have multiple procesess which are forked by a parent.In this parent I create a Semaphore.
Bassically I need something like a barrier.I want to signal to all the child process when another child had f... |
The steps are not really specific to UNIX.
In the parent, create a semaphore with the value the same as the number of children.
As each child finishes it's init, the child decrements the semaphore and waits on zero.
When the semaphore reaches zero, all the children are initialised and you can do something else.
|
This question already has answers here:Scope of C variables [duplicate](4 answers)Closed10 years ago.
Recently came across following code which declares a char *p, assigns value such as p="GOOD" and returns return p. Is the return value valid when function call is completed?
```
const char * get_state(int state)
{
... |
Yes, it is valid. The string literals"GOOD"and"BAD"are guaranteed to be in permanent, static storage, and will continue to exist even afterget_state()returns.
```
// Invalid
char str[] = "GOOD";
char *p = str;
return p;
// Valid
char *p = "GOOD";
return p;
```
|
This question already has answers here:Is short-circuiting logical operators mandated? And evaluation order?(7 answers)Closed10 years ago.
In C have the following:
```
return (abc(1) || abc(2));
```
Ifabc(1 == 1)returnstruewill then callabc(2)?
|
No, it won't. This is called"short-circuiting"and it is a common flow-control mechanism:
Witha && b,bis only evaluated ifais true; ifais false, the whole expression must necessarily be false.
Witha || b,bis only evaluated ifais false; ifais false, the whole expressionmaystill be true.
|
C code. Doxygen 1.8.3.
Some files start with large documentation blocks. Most users will read those multi-paragraph comments directly from the code files. Thus, indentation is important for clarity.
But that indentation causes Doxygen to treat the text as 'code' (creating a boxed output in the wrong typeface), and t... |
The boxed text is created using Markdown.
Markdown treats text indented by either 4 spaces or a tab as a code block delimiter (http://daringfireball.net/projects/markdown/syntax#precode).
You can either set
MARKDOWN_SUPPORT = NO
in your configuration file, or use a smaller indentation level to suppress box generat... |
I see a lot of occasions (googling) where enums are declared as follows:
enum enum_tag {a = 0, b, c, d} tag_again;
enum enum_tag {a = 0, b, c, d};
or
enum {a = 0, b, c, d} tag_again;
Some times it seems like enum_tag is the type and tag_again is a variable name, but if enum_tag is not present tag_again seems to s... |
Continued my googling and MSDN gave me the answer:MSDN C Enum Declarations
enum enum_tag {a = 0, b, c, d} tag_again;defines an enum type enum_tag and declares a variable of that type: tag_again.
enum enum_tag {a = 0, b, c, d};defines an enum type of enum_tag
and
enum {a = 0, b, c, d} tag_again;declares a variable ... |
Is there a fast way of using 64bit ints on 32
x86 machines (in c (added: and c++) language compilers)?
32 bit x86 support 64 bit operations in some
extent (there is some movq instruction in old mmx
and some other commands probably), but how to use it from c?
What if someone want to use a 64bit ints arithmetic
in c ... |
To perform 64 bit operations you can use eitherint64_toruint64_t.
They are defined inC99by the header filestdint.h.
|
I am working on a sever/client applicataion. I want to maintain information of all active clients in a text file named "Information.txt".
I update this text file after every 3 seonds. So, I want the text file to clear all of its contents after every 3 seconds without deleting the file.
Is there any way to do it ? :(
I... |
A problem with clearing the file periodically is that if your process crashes after the file has been cleared but before it has been written, you lose data: the old data is gone, but the new data is not there yet.
A common approach to this problem is to create a new file, writing it, and then moving the new file to r... |
in my header file, I have a statement to declare the MEMORY_SIZE variable. I then want to create two arrays using the MEMORY_SIZE as the size of the array. Here is my header file code:
```
#ifndef MEMORY_SIZE
#define MEMORY_SIZE 1024*512
#endif
```
In my main file the code im using for the buffers is:
```
//buffe... |
The issue is that you're compiling Java using a C compiler.
```
unsigned char memBytes[MEMORY_SIZE];
```
Grab a C book, seriously.(It seems you did. In this case, drop the Java one.)
|
When I declare something like
```
#define VAR 1
```
where will the 1 value be stored? I don't think in the heap, nor the stack.. could it be in the .bss section?
|
It's not stored anywhere. It is used only during the preprocessing stage of compilation. You can think of it as just a text replacement ofVARwith1throughout your code. After this has been done, the macro itself no longer exists in your program.
Consider the following example:
```
#define VAR 1
int x = VAR;
```
This... |
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.
I am trying to make an exe version ... |
Code blocks passes the arguments to the executable on the command line. In cmd, you must do that manually since the settings in code blocks no longer apply.
|
Let's say I have achar*called code, and it has"0x41"in it.
```
char *code = "0x41";
```
How can I convert that into anunsigned int? (To be exact, I need aWORD, but that's just anunsigned int).
|
```
unsigned int h;
sscanf(code, "%x", &h);
```
EDITtaking account of the remark ofExP:%xcould catch the value in the string"0x41"
|
I have following two questions
Given the statement like char * str = "999999999999"; how does compiler determine how much space to allocate on stack?How can i iterate over the memory pointed by str and determine the value of various bits inside it?
|
"999999999999"is not on the stack. The pointer may be on the stack, the compiler knows how big the pointer should be. The"999999999999"really has a null termination that lets you know when it is at the end.To iterate over each bit, maybe something like:for(i=0; str[i]; i++) // str[i] will evaluate to false(0) when ... |
I'm kinda new at unix programming and I need some help.
I'd like to do something like busy-waiting with a semaphore.
I have multiple procesess which are forked by a parent.In this parent I create a Semaphore.
Bassically I need something like a barrier.I want to signal to all the child process when another child had f... |
The steps are not really specific to UNIX.
In the parent, create a semaphore with the value the same as the number of children.
As each child finishes it's init, the child decrements the semaphore and waits on zero.
When the semaphore reaches zero, all the children are initialised and you can do something else.
|
This question already has answers here:Scope of C variables [duplicate](4 answers)Closed10 years ago.
Recently came across following code which declares a char *p, assigns value such as p="GOOD" and returns return p. Is the return value valid when function call is completed?
```
const char * get_state(int state)
{
... |
Yes, it is valid. The string literals"GOOD"and"BAD"are guaranteed to be in permanent, static storage, and will continue to exist even afterget_state()returns.
```
// Invalid
char str[] = "GOOD";
char *p = str;
return p;
// Valid
char *p = "GOOD";
return p;
```
|
This question already has answers here:Is short-circuiting logical operators mandated? And evaluation order?(7 answers)Closed10 years ago.
In C have the following:
```
return (abc(1) || abc(2));
```
Ifabc(1 == 1)returnstruewill then callabc(2)?
|
No, it won't. This is called"short-circuiting"and it is a common flow-control mechanism:
Witha && b,bis only evaluated ifais true; ifais false, the whole expression must necessarily be false.
Witha || b,bis only evaluated ifais false; ifais false, the whole expressionmaystill be true.
|
C code. Doxygen 1.8.3.
Some files start with large documentation blocks. Most users will read those multi-paragraph comments directly from the code files. Thus, indentation is important for clarity.
But that indentation causes Doxygen to treat the text as 'code' (creating a boxed output in the wrong typeface), and t... |
The boxed text is created using Markdown.
Markdown treats text indented by either 4 spaces or a tab as a code block delimiter (http://daringfireball.net/projects/markdown/syntax#precode).
You can either set
MARKDOWN_SUPPORT = NO
in your configuration file, or use a smaller indentation level to suppress box generat... |
I see a lot of occasions (googling) where enums are declared as follows:
enum enum_tag {a = 0, b, c, d} tag_again;
enum enum_tag {a = 0, b, c, d};
or
enum {a = 0, b, c, d} tag_again;
Some times it seems like enum_tag is the type and tag_again is a variable name, but if enum_tag is not present tag_again seems to s... |
Continued my googling and MSDN gave me the answer:MSDN C Enum Declarations
enum enum_tag {a = 0, b, c, d} tag_again;defines an enum type enum_tag and declares a variable of that type: tag_again.
enum enum_tag {a = 0, b, c, d};defines an enum type of enum_tag
and
enum {a = 0, b, c, d} tag_again;declares a variable ... |
Is there a fast way of using 64bit ints on 32
x86 machines (in c (added: and c++) language compilers)?
32 bit x86 support 64 bit operations in some
extent (there is some movq instruction in old mmx
and some other commands probably), but how to use it from c?
What if someone want to use a 64bit ints arithmetic
in c ... |
To perform 64 bit operations you can use eitherint64_toruint64_t.
They are defined inC99by the header filestdint.h.
|
I am working on a sever/client applicataion. I want to maintain information of all active clients in a text file named "Information.txt".
I update this text file after every 3 seonds. So, I want the text file to clear all of its contents after every 3 seconds without deleting the file.
Is there any way to do it ? :(
I... |
A problem with clearing the file periodically is that if your process crashes after the file has been cleared but before it has been written, you lose data: the old data is gone, but the new data is not there yet.
A common approach to this problem is to create a new file, writing it, and then moving the new file to r... |
Wandering if I can measure actual time or cpu ticks taken by a particular thread.
```
pthreadcreate(.........);
//
//
pthreadjoin(.......);
```
I am running with 3 threads.
One master thread is calling the rest two threads.
I want to measure the execution time for a called thread.
what should I use in linux enviro... |
you can do one thing
In thread function at start up make a log using printk. You can separate it with different thread printing with it thread_t variable or thread index
and at end of that thread function put another log like that.
So indmesg
will shows the log withtimestamp
so you can differentiate end log time ... |
I have used the isPrime() function in other programs and it works perfectly, I have even referenced it in the same way before. For some reason in this program the function isn't working. I used printf() to check what the function was returning and it seems to be memory locations. I don't know what to change though bec... |
Initializecountto 0.
Apart from this, on my system it works fine.
|
This question already has answers here:What is the use of _start() in C?(4 answers)Closed3 years ago.
Can you help me to understand how
```
__start
```
is used in C internally?
Is it the exact replica of themainfunction or is it the entry point to the compiled program?
Just wondering, how its getting used?
|
Hereis a good overview of what happens during program startupbeforemain. In particular, it shows that__startisthe actual entry pointto your program from OS viewpoint.
It is the very first address from which theinstruction pointerwill start counting in your program.
The code there invokes some C runtime library routi... |
I would like to define a fixed range that a number-variable can belong to.. I'm using a c89 compiler.
So, if I do:
#define minValue -200
#define maxValue 200
I would like something on the lines of:typedef int range[minValue,maxValue]
Can something like this be done?
|
No it is not possible.
You must add some code to check that your value is in the defined range.
For example
```
typedef int Range; // must be between minValue and maxValue
#define CheckRange(x) (((x)>=minValue) && ((x)<=maxValue))
[...]
Range a = ...; // a call to a function or user input request
if (!CheckRange(a))... |
Here is the code (valid C and C++)
```
#include <stdio.h>
int main() {
printf("asfd");
// LINE 1
return 0;
}
```
If in line 1 I put segfaulting expression the program would just crash without printing anything (as expected).
But why is the above code printing "asdf" and not exiting without buffer being... |
This is accomplished by these two sections in the C++ language specification:
[basic.start.main]A return statement inmainhas the effect of leaving the main function and callingexitwith the return value as the argument.
and
[lib.support.start.term]The functionexithas additional behavior in this International Standar... |
What does "for each value converted" mean in the following sentence?
Q: Why doesn't the callscanf("%d", i)work?A: The arguments you pass toscanfmust always be pointers:for each
value converted, scanf "returns" it by filling in one of the
locations you've passed pointers to. (See alsoquestion 20.1.) To fix
the f... |
If you executescanf("%d", &i)with input123, the character sequence123isconvertedto anintvalue, which is stored ini.
This is not a type conversion as might be specified by a cast, but it's still reasonable to refer to it as a "conversion".
|
I wondered what is the big difference between setting up C pointers in this way:
```
int int_var = 5;
int *int_ptr = &int_var;
```
And this way:
```
int int_var = 5;
int *int_ptr = int_var;
```
Since in both cases the result of*int_ptrwill be 5, no?
|
No, only in the first case. The second case will cause undefined behavior when you'll try to deference the pointer. Use the first case.
Some explanation:
```
int int_var = 5;
int *int_ptr = &int_var; // here int_ptr will hold the address of var
```
Whereas
```
int int_var = 5;
int *int_ptr = int_var; // here int_p... |
I have a doubt regarding inline functions. Inline functions will not involve any function calls but just replacement of function definition wherever the call is made to the inline function.Inline functions have type enforcement unlike macros.
What will happen if recursive functions are made inline?
|
"inline" isn't a guarantee, it's a request.
Your recursive inline function won't (typically) be inline.
As some commenters point out, therearespecial cases (e.g. using compiler-specific pragmas) in which inliningispossible.
|
I am trying to initialize an array so that I could use a simple if statement to check if a value was placed into the array or not.
Is this possible?
Here is my code
```
double number[1024] = {non-numeric value}
int i = 0;
while(1){
if (number[i] != non-numeric value){
printf ("%f", number[i]);
i++;
}
... |
To initialize data to NaN, use theNANmacro defined in<math.h>
```
#include <math.h>
// initialize to all NaNs
for (int i=0; i<1024; ++i) number[i] = NAN;
```
To check for NaNs, use theisnanmacro from<math.h>
```
if (!isnan(number[i])) {
// do something if the value isn’t NaN.
}
```
|
i find below code that get keyboard layout but cant convert it to string :
```
TISInputSourceRef sourceRef = TISCopyCurrentKeyboardLayoutInputSource();
```
If you useCFShow(sourceRef);you can see keyboard layout but cant convert sourceRef.
How to get keyboardLayout in string ???
|
I use this objc code:
```
#import <Carbon/Carbon.h>
TISInputSourceRef source = TISCopyCurrentKeyboardInputSource();
NSString *s = (__bridge NSString *)(TISGetInputSourceProperty(source, kTISPropertyInputSourceID));
```
You can probably also cast it toCFStringRefinstead of an objc string.
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.
If I have an array set up as:
```
... |
You can use this code ,
```
int main()
{
int test[10] = {1,2,1,3,4,5,6,7,8,3,2};
int i,j,dupliCount = 0;
for (i =0; i<(sizeof(test)/sizeof(int));i++)
{
for(j=i+1;j<(sizeof(test)/sizeof(int));j++)
{
if (test[i] == test[j])
{
++dupliCount;
break;
}
}
}
printf("duplicate count %d... |
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.
In C, the output is what I expect. ... |
You can use thetoStringmethod:
```
document.write(i.toString(16)+"<br>"); //base 16 (hex)
```
|
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "mystuff.h"
typedef struct Node
{
int size;
int status;
struct Node *next;
struct Node *previous;
} Node;
Node *endNode;
Node *rootNode;
void *my_foo(int size)
{
Node *theNode;
... |
...and declaring theNode and rootNode asNULLdoes not help.
DereferencingNULL(usually)willresult in a segfault. You've got to set them to something more useful (like an allocated structure) before you go off modifying them!
|
A quick question : What is the meaning ofchar c:4in the structure given below
```
struct s
{
char c:4;
}
```
Thanks in advance.
|
This is abit fieldconsisting of a four-bit portion of achar. You can define more bit fields to subdivide a larger type into "nibblets", like this:
```
struct s
{
char c:4;
char d:2;
char e:2;
};
```
Thisstructdefines three fields, all "packed" into a singlechar. Thecfield can hold sixteen distinct values; fie... |
So, I'm getting a few warnings when compiling a C file that I can't figure out how to fix.
The first warning comes from the following code:
```
char line[100];
char* carbonCopy;
char *currentWord;
wordlist *theList = malloc(sizeof(wordlist));
theList->head->string = NULL;
word *fromFile = malloc(sizeof(word));
whi... |
You need to include the header which declaresstrsepandstrlen
```
#include <string.h>
```
|
is there a more efficient way to perform:
```
f = fmod(x+1, 2)
```
to ascertain whether a value is even?
e.g.
f = 1for all even values ofx
f = 0for all odd values ofx
I only need this to work for the set of positive integers (myxdatatype isint)
|
Why are you usingfmod()for an integer?
The standard test would be:
```
const int f = (x + 1) % 2; /* Will be 1 if x is even, 0 if it's odd. */
```
this uses the built-in integer modulo operator%to do the testing.
The addition of 1 is (in my opinion) a bit confusing, I'd do it as:
```
const int f = (x % 2) == 0;
`... |
I want to hook the functionAudioUnitInitializeto grab the Audio Unit of an application by injecting a bundle at the application start.I found an example (http://pastie.org/1882125) but it uses the functionMSHookFunctionto replace the function names. The problem is that I want to replace the functions on Mac OS X, not ... |
If youlook closely, you can find out that MobileSubstrate runs on OS X as well.
|
I need to find all possible solutions for this equation:
x+2y = N,x<100000andy<100000.
givenN=10, say.
I'm doing it like this inpython:
```
for x in range(1,100000):
for y in range(1,100000):
if x + 2*y == 10:
print x, y
```
How should I optimize this forspeed? What should I do?
Essentia... |
ifx+2y = N, theny = (N-x)/2(supposingN-xis even). You don't need to iterate all overrange(1,100000)
like this (for a given N)
```
if (N % 2): x0 = 1
else: x0 = 0
for x in range(x0, min(x,100000), 2):
print x, (N-x)/2
```
EDIT:
you have to take care that N-x does not turn negative. That's whatminis supposed to d... |
I am trying to get the hang of semaphores. I have written a program which deals with semaphores and in which I have this function to create a single semaphore :
```
int semcreate()
{
semp = semget(ftok("./output.txt", 'a'),1,IPC_CREAT|IPC_EXCL|0664);
if(semp == -1) /*Semaphore exists, fetch*/
{
p... |
Probably the semaphore exists on the system. Use commandipcsto list all the semaphore in the system and remove the semaphore created by your program usingipcrm.
|
I have a little doubt on this subject:
If I have:
```
int a = 11;
int *b = &a;
```
when I do:
```
&*b
```
I get the address ofapointed bybso my question is:
does the dereferencing operator return the variable pointed or the value of that variable?
|
does the dereferencing operator return the variable pointed or the value of that variable?
It returns anlvaluereferring to the object that is pointed (i.e. thevariable pointedin your own terms). If you use it in a context where anrvalueis needed thelvalue-to-rvalueconversion will be applied (i.e. thevalue of that var... |
I think I have got my head mostly around the difference, but if I am correct, then this should be correct also:
1.)
```
char *string1 = (char*) malloc(runtime_determined_number);
```
2.)
```
char string2val[runtime_determined_number];
char *string2 = &string2val;
```
Here I would expect string1 and string2 to be ... |
string1andstring2are not pointed to the same memory area
string1is a pointer pointing to achararray allocated dynamically withmalloc
string2is a pointer pointing to achararray allocated statically
|
does anyone know how to display the percentage%character in an ncurses-based C++ / C=based program?
I have tried using\x25and%, but they do not work.
|
You should be able to escape the%with an extra%:
```
%%
```
|
A quick question : What is the meaning ofchar c:4in the structure given below
```
struct s
{
char c:4;
}
```
Thanks in advance.
|
This is abit fieldconsisting of a four-bit portion of achar. You can define more bit fields to subdivide a larger type into "nibblets", like this:
```
struct s
{
char c:4;
char d:2;
char e:2;
};
```
Thisstructdefines three fields, all "packed" into a singlechar. Thecfield can hold sixteen distinct values; fie... |
So, I'm getting a few warnings when compiling a C file that I can't figure out how to fix.
The first warning comes from the following code:
```
char line[100];
char* carbonCopy;
char *currentWord;
wordlist *theList = malloc(sizeof(wordlist));
theList->head->string = NULL;
word *fromFile = malloc(sizeof(word));
whi... |
You need to include the header which declaresstrsepandstrlen
```
#include <string.h>
```
|
is there a more efficient way to perform:
```
f = fmod(x+1, 2)
```
to ascertain whether a value is even?
e.g.
f = 1for all even values ofx
f = 0for all odd values ofx
I only need this to work for the set of positive integers (myxdatatype isint)
|
Why are you usingfmod()for an integer?
The standard test would be:
```
const int f = (x + 1) % 2; /* Will be 1 if x is even, 0 if it's odd. */
```
this uses the built-in integer modulo operator%to do the testing.
The addition of 1 is (in my opinion) a bit confusing, I'd do it as:
```
const int f = (x % 2) == 0;
`... |
I want to hook the functionAudioUnitInitializeto grab the Audio Unit of an application by injecting a bundle at the application start.I found an example (http://pastie.org/1882125) but it uses the functionMSHookFunctionto replace the function names. The problem is that I want to replace the functions on Mac OS X, not ... |
If youlook closely, you can find out that MobileSubstrate runs on OS X as well.
|
I need to find all possible solutions for this equation:
x+2y = N,x<100000andy<100000.
givenN=10, say.
I'm doing it like this inpython:
```
for x in range(1,100000):
for y in range(1,100000):
if x + 2*y == 10:
print x, y
```
How should I optimize this forspeed? What should I do?
Essentia... |
ifx+2y = N, theny = (N-x)/2(supposingN-xis even). You don't need to iterate all overrange(1,100000)
like this (for a given N)
```
if (N % 2): x0 = 1
else: x0 = 0
for x in range(x0, min(x,100000), 2):
print x, (N-x)/2
```
EDIT:
you have to take care that N-x does not turn negative. That's whatminis supposed to d... |
I am trying to get the hang of semaphores. I have written a program which deals with semaphores and in which I have this function to create a single semaphore :
```
int semcreate()
{
semp = semget(ftok("./output.txt", 'a'),1,IPC_CREAT|IPC_EXCL|0664);
if(semp == -1) /*Semaphore exists, fetch*/
{
p... |
Probably the semaphore exists on the system. Use commandipcsto list all the semaphore in the system and remove the semaphore created by your program usingipcrm.
|
I have a little doubt on this subject:
If I have:
```
int a = 11;
int *b = &a;
```
when I do:
```
&*b
```
I get the address ofapointed bybso my question is:
does the dereferencing operator return the variable pointed or the value of that variable?
|
does the dereferencing operator return the variable pointed or the value of that variable?
It returns anlvaluereferring to the object that is pointed (i.e. thevariable pointedin your own terms). If you use it in a context where anrvalueis needed thelvalue-to-rvalueconversion will be applied (i.e. thevalue of that var... |
I think I have got my head mostly around the difference, but if I am correct, then this should be correct also:
1.)
```
char *string1 = (char*) malloc(runtime_determined_number);
```
2.)
```
char string2val[runtime_determined_number];
char *string2 = &string2val;
```
Here I would expect string1 and string2 to be ... |
string1andstring2are not pointed to the same memory area
string1is a pointer pointing to achararray allocated dynamically withmalloc
string2is a pointer pointing to achararray allocated statically
|
does anyone know how to display the percentage%character in an ncurses-based C++ / C=based program?
I have tried using\x25and%, but they do not work.
|
You should be able to escape the%with an extra%:
```
%%
```
|
So, I'm getting a few warnings when compiling a C file that I can't figure out how to fix.
The first warning comes from the following code:
```
char line[100];
char* carbonCopy;
char *currentWord;
wordlist *theList = malloc(sizeof(wordlist));
theList->head->string = NULL;
word *fromFile = malloc(sizeof(word));
whi... |
You need to include the header which declaresstrsepandstrlen
```
#include <string.h>
```
|
is there a more efficient way to perform:
```
f = fmod(x+1, 2)
```
to ascertain whether a value is even?
e.g.
f = 1for all even values ofx
f = 0for all odd values ofx
I only need this to work for the set of positive integers (myxdatatype isint)
|
Why are you usingfmod()for an integer?
The standard test would be:
```
const int f = (x + 1) % 2; /* Will be 1 if x is even, 0 if it's odd. */
```
this uses the built-in integer modulo operator%to do the testing.
The addition of 1 is (in my opinion) a bit confusing, I'd do it as:
```
const int f = (x % 2) == 0;
`... |
I want to hook the functionAudioUnitInitializeto grab the Audio Unit of an application by injecting a bundle at the application start.I found an example (http://pastie.org/1882125) but it uses the functionMSHookFunctionto replace the function names. The problem is that I want to replace the functions on Mac OS X, not ... |
If youlook closely, you can find out that MobileSubstrate runs on OS X as well.
|
I need to find all possible solutions for this equation:
x+2y = N,x<100000andy<100000.
givenN=10, say.
I'm doing it like this inpython:
```
for x in range(1,100000):
for y in range(1,100000):
if x + 2*y == 10:
print x, y
```
How should I optimize this forspeed? What should I do?
Essentia... |
ifx+2y = N, theny = (N-x)/2(supposingN-xis even). You don't need to iterate all overrange(1,100000)
like this (for a given N)
```
if (N % 2): x0 = 1
else: x0 = 0
for x in range(x0, min(x,100000), 2):
print x, (N-x)/2
```
EDIT:
you have to take care that N-x does not turn negative. That's whatminis supposed to d... |
I am trying to get the hang of semaphores. I have written a program which deals with semaphores and in which I have this function to create a single semaphore :
```
int semcreate()
{
semp = semget(ftok("./output.txt", 'a'),1,IPC_CREAT|IPC_EXCL|0664);
if(semp == -1) /*Semaphore exists, fetch*/
{
p... |
Probably the semaphore exists on the system. Use commandipcsto list all the semaphore in the system and remove the semaphore created by your program usingipcrm.
|
I have a little doubt on this subject:
If I have:
```
int a = 11;
int *b = &a;
```
when I do:
```
&*b
```
I get the address ofapointed bybso my question is:
does the dereferencing operator return the variable pointed or the value of that variable?
|
does the dereferencing operator return the variable pointed or the value of that variable?
It returns anlvaluereferring to the object that is pointed (i.e. thevariable pointedin your own terms). If you use it in a context where anrvalueis needed thelvalue-to-rvalueconversion will be applied (i.e. thevalue of that var... |
I think I have got my head mostly around the difference, but if I am correct, then this should be correct also:
1.)
```
char *string1 = (char*) malloc(runtime_determined_number);
```
2.)
```
char string2val[runtime_determined_number];
char *string2 = &string2val;
```
Here I would expect string1 and string2 to be ... |
string1andstring2are not pointed to the same memory area
string1is a pointer pointing to achararray allocated dynamically withmalloc
string2is a pointer pointing to achararray allocated statically
|
does anyone know how to display the percentage%character in an ncurses-based C++ / C=based program?
I have tried using\x25and%, but they do not work.
|
You should be able to escape the%with an extra%:
```
%%
```
|
I have this:
```
long int addsquares(int n, ...)
```
How can I access the parameters?
I can't useva_startandva_arg...
|
Implementation dependent...
pre test
```
long int addsquares(int n, int d1, ...){
printf("%p,%p\n", &n, &d1);
return 0L;
}
```
result :
windows 64bit system, vc10 (sizeof int:4)
```
003DFD54,003DFD58
```
windows 64bit system, gcc 4.4.3 (sizeof int:4)
```
000000000022FE60,000000000022FE68
```
for vc10:
... |
the unixhostnameprogram gives me an exceedingly simple way to get my "real" hostname (not localhost. For example, for me it's currentlyunknown74e5[...]df7.att.net). But how can I do this inside of my own code with C system calls? I'd like to get achar *that has this string in it so that I can pass it intogethostbyname... |
gethostname(2)is the POSIX-mandated C library function that powers thehostnameprogram:
```
int gethostname(char *name, size_t len);
```
|
Is there need to convert to network/host byte ordering when sending and receiving strings. The available functions (such as htons()) only work with 16 and 32 bit integers. I also know for a fact that a single char shouldn't make a difference, as generally, it is a byte large. However what about strings ?
The followin... |
It depends on the encoding of the string.
If it's a byte-oriented format (plain old ASCII or UTF-8), then it doesn't matter.
If it uses "code points" larger than a single byte, then yes it matters.
|
I don't have access to the C11 specification, therefore I can't investigate this bug.
The following declaration rises an error during compilation:
```
int why[2] = 1 == 1 ? {1,2} : {3,4};
```
The error is: expected expression before { and: expected expression before :
|
This is not valid C11.
You can only initialize an array with an initializer-list not with an expression.
```
int why[2] = { ... }; // initializer-list {}
```
Moreover,1 == 1 ? {1,2} : {3,4}is not a valid C expression because{1, 2}is not a C expression.
Just for information using compound literals you can have som... |
I got the following error message while compiling the C code:
```
error: 'for' loop initial declarations are only allowed in C99 mode
note: use option -std=c99 or -std=gnu99 to compile your code
```
What does it mean?
How to fix it?
|
You have done this:
```
for (int i=0;i<10;i++) {
```
And you need to change it to this:
```
int i;
for (i=0;i<10;i++) {
```
Or, as the error says,
use option -std=c99 or -std=gnu99 to compile your code.
Updatecopied from Ryan Fox's answer:
```
gcc -std=c99 foo.c -o foo
```
Or, if you're using a standard makefi... |
I'm not a bash whiz, so please excuse the simplistic nature of this question.
I want to compile, execute and echo the return values of my programs in one line in a Linux shell. Something like...
~$ gcc -Wall -std=c99 program.c && ./a.out && echo $?
These all work separately, and this of course works, too:
```
~$ g... |
The&&operator only executes the next command if the previous was successful. Use;instead.
```
gcc -Wall -std=c99 program.c && (./a.out ; echo $?)
```
The parentheses make it soecho $?doesn't happen ifgccfails.
|
For some reason I am getting the error:
```
expected identifier or '(' before 'wordlist'
```
in my header file (as well as the corresponding function definitions) for the two functions returningwordlistpointers.
With the following code:
```
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
typedef struct word{
char *str... |
This is because when you declare a pointer, the asterisk must follow the type name, not precede it:
```
wordlist * populateList(FILE *file);
// ^
// |
// Here
```
|
I am receiving an incompatible types error as follows:
```
error: incompatible types when assigning to type ‘struct cache *’ from type ‘cache’
```
I have the following structures.
```
typedef struct __region {
int size;
void *addr;
struct __region *next;
} region;
typedef struct {
int size;
int remainingSpace;
voi... |
parentis a pointer to astruct cache, whileM.C[0]is astruct cache. You can use the&operator to get a pointer toM.C[0]as so:
```
M.C[0].S->parent = &(M.C[0]);
```
|
Every time a watchpoint is modified GDB will print the old value and the new value. However, sometimes I don't want to print the value in the default decimal integer format: for instance, if I'm watching*(unsigned*)$ebpto debug a possible stack overflow (wow, SO...), the value is nonsense unless displayed in hexadecim... |
Is it possible to set the display format for a particular watchpoint?
If you want the watchpoint to print in hex, set it as watch of a pointer, e.g.
```
watch *(char**)$ebp or
watch *(void**)$ebp
```
|
Say I have 3 files: file1.c, file2.c and globals.h. file1.c and file2.c both include globals.h. file1.c contains a struct that file2.c needs to use. Is it better to make the struct itself extern or create a pointer to the struct and make that pointer extern in globals.h?
|
If I understand correctly and your "a struct" is supposed to be a global object (which is a questionable design choice), then I'd do it like this:
foo.h:
```
typedef struct foo_struct
{
/* ... */
} foo;
extern foo the_foo;
```
foo.c:[If you like and if it makes sense, you can merge this into file1.c.]
```
#in... |
I read that you can't do bitmasks on pointers, how come you can't do
bitwise operations on pointers?
Is there any way to achieve the same effect?
Does the same apply to C++?
|
The reason you can't do bitwise pointer operations is because the standard says you can't. I suppose the reason why the standard says so is because bitwise pointer operations would almost universally result in undefined or (at best) implementation-defined behavior. So there would be nothing you could do that is both... |
I have an ELF executable and I would like to know how can I modify its .rodata segment.
Also, more generally, how can I modify an ELF executable?
|
You can use any hexeditor to do that, if you know precisely which part of ELF you need to modify.
If you want to parse ELFs and do more complex logic you should write some code which will open file or better, mmap it. Then you can read ELF header which gives basic information about ELF and points to other important p... |
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... |
When it appears on its own without parentheses,mainis apointer to function(effectively, the address ofmain()).
Thus
```
main || c
```
is equivalent to
```
(main != NULL) || (c != 0)
```
which always evaluates to true (i.e.1).
|
This question already has answers here:Facing an error "*** glibc detected *** free(): invalid next size (fast)"(2 answers)Closed9 years ago.
My code:
```
int args_size = 5;
char** args;
args = (char**) malloc(sizeof(char*) * args_size);
// ...
args = (char**) realloc(args, sizeof(char*) * (args_size += 5));
```
... |
SOLVED
Initially, the size ofargsis 5 elements.
As the program was fillingargs, it was mistakenly adding6thelement to it and then callingrealloc.
That caused the error mentioned in the question.
Problem is solved by eliminating the error, by following the comments of WhozCraig, Jens Gustedt and others...
Thanks to... |
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... |
No, there isn't. Loading and saving images is really not the job of an Operating System kernel like Linux. A kernel manages memory, IO and CPU resources, and that's it. Everything else should be done by user-level code.
|
Can I pass two structures as parameters to a pthread in a C program. I need to do something like this:
```
void *funtion1(void *pass_arg, void *pass_arg1)
{
struct thread_arg *con = pass_arg;
struct thread_arg1 *con = pass_arg1;
//necessary code
}
int main()
{
pthread_t threaad;
//necessary code
while(1)
... |
Not directly, because the functions in libpthread accept only one user data argument. But that should be enough, shouldn't it?
```
struct user_struct {
void *p1, *p2;
} arg = { &arg1, &arg2 };
pthread_create(&tid, NULL, threadfunc, &arg);
```
Also, don't cast pointers tovoid *, it's superfluous, dangerous and d... |
I have the following variables:
```
int year = 2013;
int month = 04;
int day = 07;
int hour = 13;
int min = 42;
int sec = 00;
```
...and I need to extract the "epoch" time, or unix time, from them.
How can this be done in standard C?
In this case, the unix time should be:1365342120.
|
The above answer misses some things you might not notice if you've never used this struct:
```
struct tm myTm = {
.tm_sec = sec,
.tm_min = min,
...
.tm_mon= mon-1,
.tm_year= year-1900,
};
time_t t = mktime(&myTm);
printf("%ju\n", (uintmax_t) t);
```
you should subtract 1 to the month, and 1900 to the year or you'l... |
```
strcpy(argv[0], arg0)
strcpy(argv[1], arg1)
strcpy(argv[2], arg2)
strcpy(argv[3], arg3)
strcpy(argv[4], arg4)
strcpy(argv[5], arg5)
strcpy(argv[6], arg6)
strcpy(argv[7], arg7)
strcpy(argv[8], arg8)
strcpy(argv[9], arg9)
```
I known the following is not right, but what is the right way to use macro?
```
#define A... |
Instead of simplifying your sequence of calls tostrcpyyou should rather convert you variablesarg0,arg1, ...,arg9to an array. If you do it, you will be able to do the whole thing in a simple loop.
|
I want to compile a C program related to databases in Windows. I have installed MySQL.
What I actually want to do is re-direct the output of my C code as an input command for my database.
I have done this thing in Ubuntu having followed the below given link:
Connecting to MySQL through C++
P.S. Does it require fo... |
No - you can compile the code anyhow.
If you want to redirect output, it's easiest to make the program a console application (which can be compiled from the IDE or from the command line).
Then you pipe the output of the program to the mysql command line client.
```
yourprogram | mysql --user=user_name --password=yo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.