question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question
I am using the visual studio directive#regionand I would like to know if that directive is only forVisual S... |
#regionis not part of the C standard. I would assume that it is only recognized by Visual Studio.
|
I would like to copy the contents of a char array to int variables or an array. For example, the first five values have to go to an int array (int x):
```
char a[] = "123456";
```
I saw in other threads that to change a char to an int, I need to do this:
```
int x = a[0] - '0';
```
Is there other ways of doing it?... |
Copy properly sized portions of the string to a separate buffer and usestrtol()orstrtod().
|
C newbie here, and I'm wondering, how come j is not incremented in the example below?
I searched everywhere for an explanation
```
int i, j, k;
i = 3; j=4; k=5;
_Bool checkbit;
checkbit = i < j || ++j < k;
printf("%d\n", checkbit );
printf("%d %d %d\n", i, j , k);
```
The output is
```
1
3 4 5
```
instead of
... |
Because it doesn't need to be evaluated.
```
checkbit = i < j || ++j < k;
```
i < jwill yieldtrue, so no matter what the second part of the expression yields, the value ofcheckbitwill betrue. Thus, it doesn't even bother evaluating it.
Just for kicks:
```
checkbit = i > j && ++j < k;
```
In this case, the secon... |
This question already has answers here:How to create a single instance application in C or C++(15 answers)Closed10 years ago.
I have a binary and it's a daemon and it's developed in C. I want to add a check at the beginning of my program to guarantee that the binary is launched only one time. My binary runs on Linux.... |
Acommon methodis to put aPID filein/var/run. After your daemon starts successfully, youflockwrite its PID to this file. At startup, you check the value of the PID in this file, if it exists. If there is no PID currently running, it's safe for the application to startup. If the PID exists, perform a check to see if tha... |
Hi I need some help in understand some C code:
```
#if 0
some C code 1
#elif 0
static int8 arry[10];
#pragma Align_to(32, arry)
ASSERT(((int8ptr_t)arry) & 15) == 0)
#else
ASSERT(((int8ptr_t)arry) & 15) == 0)
#endif
```
My questions:
Is only the#elsepart compiled?What is the meaning of#pragma Align_to(32... |
Actually better way to answer is ask compiler - useg++ -Eor MSVC:cl /EPto print what is really compiled
|
This question already has answers here:Difference between two declarations involving a pointer and an array(6 answers)Closed10 years ago.
I want to know what is a difference between :
```
int *a[3];
```
And
```
int (*a)[3];
```
Thanks a lot , good luck .
|
int *a[3]=>ais array ofint *
(a+1)will point to next integer by with the increment of integer size.
int (*a)[3]=> a pointer to array of 3 integers
(a+1)will point to next array of 3 integers, with the increment of (3 * integer size)
to find details read more about pointer to arrays
|
I am working with a legacy code.
So I am not sure about where to define the start and stop address for stack.
The environment specifications are.
OS : Free RTOS
Compiler : Gcc compiler
Processor : STM32
This is to understand the start and stop address
of stack to experiment on the maximum stack range used on... |
In FreeRTOS, you don't provide the stack explicitly, you merely specify the requred size andxTaskCreate()dynamically allocates the stack for you.
FreeRTOS does have some support forstack usage and overflow checking.
|
This question already has answers here:Why do function pointer definitions work with any number of ampersands '&' or asterisks '*'?(5 answers)Closed6 years ago.
In C/C++, if I have a the following functions:
```
void foo();
void bar(void (*funcPtr)());
```
Is there a difference between these two calls:
```
bar(foo... |
No, there is no difference, since function can be implicitly converted to pointer to function.
Relevant quote from standard (N3376 4.3/1).
An lvalue of function type T can be converted to a prvalue of type “pointer to T.” The result is a pointer to
the function.
|
Suppose this scheme:
```
/* avl.c */
typedef struct avl {
void *data;
int height;
struct avl *left, *right;
} node;
/* avl.h */
struct avl; /* opaque */
```
I want to use:
```
struct node *root;
```
instead of
```
node *root;
```
in avl.c, but for now the best I have found is:
```
struct avl {
... |
There is no other way than using macros to do that. The reason is that struct tags have their ownnamespace. Different names in the tag namespace always refer to different types, even if the structs contain the same member types. Proper aliasing of types can only be done with typedefs, which aredefinedto be aliases and... |
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 have to read coordinates from a f... |
You can use your file as it is but you are going to need kind of messyString Processing. In order to get the individual numbers you have to get rid of thebracketsand thecomma..
Rather I would suggest you to change the way you save the points to your file.rather than putting the points [in your file] like this:(25, 4... |
I would like to have Library in C or C++ that give me some Bluetooth paquet field (like address, RSSI, type,..) for a given Bluetooth stream.I used hcidump command but it doesn't give me what I want and with the manner that I need. i would like to write a program that do like hcidump but with my manner with parameter ... |
On linux you can use bluez, which is nicely donehttp://www.bluez.org/download/
|
Lets say I have lots ofprintfusage, but I want to store them in a string and print them all in one go. Imagine the case below:
```
printf("%d,", _counter);
printf("IS REAL,", _condition);
printf("%f,", _value);
printf("%d,\r\n", _time);
```
What I want to do is to build a string and useprintfonly once when I am sure... |
You usesprintf(), or (much better)snprintf().
```
char buffer[32];
snprintf(buffer, sizeof buffer, "%d,IS REAL,%f,%d\r\n", _counter, _value, _time);
printf("%s", buffer);
```
I skipped the_conditionvariable access, since that line didn't do any formatting.
|
Are cmathexp()andlog()functions always symmetrical?
Ergo if I do
```
double x;
double y = exp(log(x));
assert(x == y);
```
will the assert ever fail, and in that case: under what circumstances? We can assume thatxis arational number > 0.
|
A floating-pointlogcannot be one-to-one. It needs to be monotone increasing and satisfylog(64) > 4.15andlog(128) < 4.86. There are 252doubles between 64 and 128, but there are fewer than 250doubles between 4.15 and 4.86. There are multipledoublesin that range with the same double-precision logarithm, soexp(log(x)) ... |
Below is a part of my code. I am not sure what is wrong with it because when I debug this code, I get a the following error:
Unhandled exception at 0x60e8144c (msvcr90d.dll) in client0.exe:
0xC0000005: Access violation writing location 0x00000000.
This is somewhere in the line itoa.
CODE:
```
int num = LOWORD (... |
You have to pass a valid initialized pointer toitoa().
|
I was reading through some of the best practices for the GNOME project, and one thing that they kept stressing was avoiding C99 features, as support was still not widespread. Some of the things they mentioned were features like single-line comments and declaring variables in the middle of a block. It made me wonder, i... |
http://en.wikipedia.org/wiki/C99#Implementations
Seems like it still is a bit of an issue, even in GCC, though it looks like some commercial compilers have implemented the entire standard.
Microsoft have said repeatedly there are no plans to implement the C99 standard at any point in the future which is a shame for ... |
Where is _TRACE macro defined? What's the purpose of it? Does it trace the stack and lets you know when your app crash?
|
If you want you can define it compile time using below command
```
make CFLAGS=-D_TRACE
```
|
How do I represent extremely large or small numbers in C with a certain amount of significant figures. For example, if I want to do calculations on 1.54334E-34, how could I do this. Also, is this applicable to OpenCL code?
|
```
float var = 1.54334E-34;
double var2 = 1.54334E-34;
printf("\n normal:%f\n sci:%e \n or \n sci:%E \n",var,var,var);
printf("\n normal:%f\n sci:%e \n or \n sci:%E \n",var2,var2* 1.0E3 ,var2 * 1.0e3);
```
|
I'm starting a new project, a text data arhivator, that will useHuffman coding.
What structure is better to use in implementation of such an algorithm?
My approach is to create a simply linked list that will contain binary trees in each node. In order to build the Huffman-tree.
Is there a better way?
|
If you're talking about generating the Huffman code from the symbol frequencies (your question is not clear), then the data structure can be implicit in the storage of the tree. In fact, the calculation can be done in place, over the frequencies. SeeIn-Place Calculation of Minimum-Redundancy Codes.
|
Is
```
MOV MUL_AXB[EBX * 4], EAX
```
supposed to actually change the effective MUL_AXB address?
I have declared MUL_AXB as
```
int* MUL_AXB;
```
on the global scope after the using statements and i have assigned it a value with
```
MUL_AXB = (int*) memset(malloc(size), 0, size);
```
Any insight on this issue is... |
What you are doing will write in memory somewhere past themul_axbpointer, causing bad things to happen.
To actually write into the allocated array, you need to load the pointer into a register first. Assuming this is 32-bit code:
```
mov edx, [mul_axb]
mov [edx + ebx*4], eax
```
|
Is there typically a difference in performance between calling anexternfunction versus calling astaticfunction? If so, what causes this difference -- aren't both calls mapped the same way (i.e. to a specific machine address) via early binding?
|
That's an implementation detail, entirely up to the compiler/linker. On Linux, calling a static function or an extern function in a statically-linked library are essentially the same, while calling a function in a shared library adds a level of indirection, and so is a bit slower.
Also, the compiler has more informat... |
I am looking at taking the 10 bit data from my ADC conversion and storing it into 1 16 bit integer data looks like 0x03 ADRESH 0xFF ADRESL. What I am doing right now is
```
data = 0x03 & ADRESH;
data = data << 8;
data = data & 0x03FF & ADRESL;
```
will this work how I think it should or am I missing somethin... |
Why don't you use the|operator ?short data = ((0x03 & ADRESH) << 8) | ADRESL;should work fine.
|
I would like to do following:
parser.h
```
#ifndef WS_PARSER_H
#define WS_PARSER_H
#include <stdin.h>
#include <stdbool.h>
typedef enum {
FIN = 0x80;
RSV1 = 0x40
/* ... */
} ws_flags;
#endif
```
parser.c
```
#ifndef WS_PARSER
#define WS_PARSER
#include "parser.h"
ws_read_fin_flag(unsigned char * chu... |
```
#ifndef WS_PARSER_H
#define WS_PARSER_H
#include <stdin.h>
#include <stdbool.h>
typedef enum {
FIN = 0x80,
RSV1 = 0x40,
/* ... */
} ws_flags;
#endif
```
It's an,instead of;.
|
I want to set a given bit from one bitmask to another in C. This is the way I do it currently.
```
const int MASK_THIRD = (1<<2);
if (mask & MASK_THIRD) {
mask_another |= MASK_THIRD;
} else {
mask_another &= ~MASK_THIRD;
}
```
Is there a smarter way of doing it?
|
Another way:
mask_another ^= ((mask ^ mask_another) & MASK_THIRD);
Which is in essence saying "if the bit is different, flip it". It requires one less operation which is why I figured it's worth mentioning.
|
How to memcpy the two dimensional array in C:
I have a two dimensional array:
```
int a[100][100];
int c[10][10];
```
I want to usememcpyto copy the all the values in array c to array a, how to do this using memcpy?
```
int i;
for(i = 0; i<10; i++)
{
memcpy(&a[i][10], c, sizeof(c));
}
```
is this correct?
|
That should work :
```
int i;
for(i = 0; i<10; i++)
{
memcpy(&a[i], &c[i], sizeof(c[0]));
}
```
|
I'm trying to figure out how user input can be used as a filename in C. Here's the simple program I wrote.
```
#include <stdio.h>
#define MAX 100
int main()
{
FILE *fp;
char name[MAX];
printf("Enter filename: ");
fgets(name, MAX, stdin);
if((fp = fopen(name, "w")) == 0)
printf("File ca... |
fgetsretains the newline in the input.
|
My code for implementation of DDA (Digital Differential Analyzer) algorithm is working good for drawing lines with slope less than 45obut fails in lines slope more than 45o.
It is behaving like a broken line for angles > 45o
Code
```
void dda(int x1,int y1,int x2,int y2)
{
float x,y,xinc,yinc,dx,dy;
int k... |
If you want to draw lines with a slope > 1, you have to iterate over the y-value. This is natural since there are more steps in the y-direction than there are in the x-direction.
|
I was experimenting withwchar_tand I tried to copy one array into another array.
here is my code:
```
wchar_t name[]=L"Aayman Khalid";
wchar_t Name[50]=L"";
wcscpy_s(Name,sizeof(name),name);
printf_s( "Name = %s\n", Name );
```
however when I run this code,I get the first letter i.eA.
could someone explain to me as ... |
Useprintf_swith"%ls"specifier.
|
I was reading through some of the best practices for the GNOME project, and one thing that they kept stressing was avoiding C99 features, as support was still not widespread. Some of the things they mentioned were features like single-line comments and declaring variables in the middle of a block. It made me wonder, i... |
http://en.wikipedia.org/wiki/C99#Implementations
Seems like it still is a bit of an issue, even in GCC, though it looks like some commercial compilers have implemented the entire standard.
Microsoft have said repeatedly there are no plans to implement the C99 standard at any point in the future which is a shame for ... |
Where is _TRACE macro defined? What's the purpose of it? Does it trace the stack and lets you know when your app crash?
|
If you want you can define it compile time using below command
```
make CFLAGS=-D_TRACE
```
|
How do I represent extremely large or small numbers in C with a certain amount of significant figures. For example, if I want to do calculations on 1.54334E-34, how could I do this. Also, is this applicable to OpenCL code?
|
```
float var = 1.54334E-34;
double var2 = 1.54334E-34;
printf("\n normal:%f\n sci:%e \n or \n sci:%E \n",var,var,var);
printf("\n normal:%f\n sci:%e \n or \n sci:%E \n",var2,var2* 1.0E3 ,var2 * 1.0e3);
```
|
I'm starting a new project, a text data arhivator, that will useHuffman coding.
What structure is better to use in implementation of such an algorithm?
My approach is to create a simply linked list that will contain binary trees in each node. In order to build the Huffman-tree.
Is there a better way?
|
If you're talking about generating the Huffman code from the symbol frequencies (your question is not clear), then the data structure can be implicit in the storage of the tree. In fact, the calculation can be done in place, over the frequencies. SeeIn-Place Calculation of Minimum-Redundancy Codes.
|
Is
```
MOV MUL_AXB[EBX * 4], EAX
```
supposed to actually change the effective MUL_AXB address?
I have declared MUL_AXB as
```
int* MUL_AXB;
```
on the global scope after the using statements and i have assigned it a value with
```
MUL_AXB = (int*) memset(malloc(size), 0, size);
```
Any insight on this issue is... |
What you are doing will write in memory somewhere past themul_axbpointer, causing bad things to happen.
To actually write into the allocated array, you need to load the pointer into a register first. Assuming this is 32-bit code:
```
mov edx, [mul_axb]
mov [edx + ebx*4], eax
```
|
Is there typically a difference in performance between calling anexternfunction versus calling astaticfunction? If so, what causes this difference -- aren't both calls mapped the same way (i.e. to a specific machine address) via early binding?
|
That's an implementation detail, entirely up to the compiler/linker. On Linux, calling a static function or an extern function in a statically-linked library are essentially the same, while calling a function in a shared library adds a level of indirection, and so is a bit slower.
Also, the compiler has more informat... |
I am looking at taking the 10 bit data from my ADC conversion and storing it into 1 16 bit integer data looks like 0x03 ADRESH 0xFF ADRESL. What I am doing right now is
```
data = 0x03 & ADRESH;
data = data << 8;
data = data & 0x03FF & ADRESL;
```
will this work how I think it should or am I missing somethin... |
Why don't you use the|operator ?short data = ((0x03 & ADRESH) << 8) | ADRESL;should work fine.
|
I would like to do following:
parser.h
```
#ifndef WS_PARSER_H
#define WS_PARSER_H
#include <stdin.h>
#include <stdbool.h>
typedef enum {
FIN = 0x80;
RSV1 = 0x40
/* ... */
} ws_flags;
#endif
```
parser.c
```
#ifndef WS_PARSER
#define WS_PARSER
#include "parser.h"
ws_read_fin_flag(unsigned char * chu... |
```
#ifndef WS_PARSER_H
#define WS_PARSER_H
#include <stdin.h>
#include <stdbool.h>
typedef enum {
FIN = 0x80,
RSV1 = 0x40,
/* ... */
} ws_flags;
#endif
```
It's an,instead of;.
|
I want to set a given bit from one bitmask to another in C. This is the way I do it currently.
```
const int MASK_THIRD = (1<<2);
if (mask & MASK_THIRD) {
mask_another |= MASK_THIRD;
} else {
mask_another &= ~MASK_THIRD;
}
```
Is there a smarter way of doing it?
|
Another way:
mask_another ^= ((mask ^ mask_another) & MASK_THIRD);
Which is in essence saying "if the bit is different, flip it". It requires one less operation which is why I figured it's worth mentioning.
|
How to memcpy the two dimensional array in C:
I have a two dimensional array:
```
int a[100][100];
int c[10][10];
```
I want to usememcpyto copy the all the values in array c to array a, how to do this using memcpy?
```
int i;
for(i = 0; i<10; i++)
{
memcpy(&a[i][10], c, sizeof(c));
}
```
is this correct?
|
That should work :
```
int i;
for(i = 0; i<10; i++)
{
memcpy(&a[i], &c[i], sizeof(c[0]));
}
```
|
I'm trying to figure out how user input can be used as a filename in C. Here's the simple program I wrote.
```
#include <stdio.h>
#define MAX 100
int main()
{
FILE *fp;
char name[MAX];
printf("Enter filename: ");
fgets(name, MAX, stdin);
if((fp = fopen(name, "w")) == 0)
printf("File ca... |
fgetsretains the newline in the input.
|
My code for implementation of DDA (Digital Differential Analyzer) algorithm is working good for drawing lines with slope less than 45obut fails in lines slope more than 45o.
It is behaving like a broken line for angles > 45o
Code
```
void dda(int x1,int y1,int x2,int y2)
{
float x,y,xinc,yinc,dx,dy;
int k... |
If you want to draw lines with a slope > 1, you have to iterate over the y-value. This is natural since there are more steps in the y-direction than there are in the x-direction.
|
I was experimenting withwchar_tand I tried to copy one array into another array.
here is my code:
```
wchar_t name[]=L"Aayman Khalid";
wchar_t Name[50]=L"";
wcscpy_s(Name,sizeof(name),name);
printf_s( "Name = %s\n", Name );
```
however when I run this code,I get the first letter i.eA.
could someone explain to me as ... |
Useprintf_swith"%ls"specifier.
|
how can i give particular name to .gcda and .gcno files each time compile rather than the default name so that i can combine all results in lcov.
Suppose in following code.
```
enter code here
#include<stdio.h>
main()
{
int n;
printf("Enter an integer\n");
scanf("%d",&n);
if ( n%2 == 0 )
prin... |
If you're on Windows, you can useCopyFile(source, destination, FALSE);Checking the number of times you've compiled, just analyze how many files were copied by byCopyFile()with an open file function likefopen("test.txt", "r");. It return NULL if the file does not exist.
|
I have a file which I've opened a reference to using fopen_s
Now I want to remove certain lines from the file.
Most recommendations are to copy the lines I want to a temp file, delete the original file and then write back the lines to a newly created file.
However, I have an additional problem that up to 20 other s... |
First rename the file (maybe using the Process/thread Id in the name), create your temp file in the same folder, delete the renamed file and rename the temp file back to the original name.
|
Let's say we want to change the value of maximum number of precesses each uid can execute contemporarily, what if we modify value CHILD_MAX in limits.h.
Is the value in limits.h just set in order to let us know the 'limits', or we can actually manipulate our system with it?
I think since kernel is not recompiled, ther... |
The values in<limits.h>are just there to inform you of the actual limits. Redefining the macros will not change the actual limits.
|
This question already has answers here:Why does the indexing start with zero in 'C'?(16 answers)Closed10 years ago.
I have a question on C/C++ arrays.
Why does the index of the arrays start from '0' not from '1'?
Is there any mathematical reason for that?
|
In most programming language, the name of any array is a pointer, which is nothing but a reference to a memory location, and so the expression array[n] points to a memory location which is n-elements away from the first element. This means that the index is used as an offset. The first element of the array is exactly ... |
I've been trying to figure out the best way to write binary data to stdout from a C program. It works fine on Linux, but I'm having issues when I compile on Windows because "\n" gets converted to "\r\n".
Is there a standard way to write to stdout in some sort of binary mode which avoids newline conversion? If not, wh... |
You can usesetmode(fileno(stdout), O_BINARY)
Wrap it in an ifdef if you want to keep it compatible with Linux.
See also:https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/setmode?view=vs-2017
|
if I hit Ctrl-D KDevelop will comment out the line where my cursor sits, which is all good. What's not so good is the C++ style comments it chooses // I want it to use /**/. Is there a way to make KDevelop use C style comments?
The reasons I ask are:
1)
Our code guide line requires/**/2)
We import a lot of code and t... |
Set the mode of the source toANSI C89either manuallyEditor->Tools->Mode->Sources->ANSI C89or using a kate modeline/* kate: syntax ANSI C89; */
|
recvfrom on IPv6 sockets (GNU/Linux) gives unusual addresses for the client/from address of the forma00::<two_radom_bytes>:</64_network_prefix>.
What are theses addresses called or by what search terms can more information be found?
|
Finally found the problem staring right at me; I used&addrinstead of&addr.sin6_addrfor function inet_ntop.
Sorry for bugging everyone with this silly problem.
|
Is there a way to generate random numbers in c language independent of time.
The idea is that I want to generate an array of random numbers at a time,but since rand() method depends on time,all the values in the array are generated similarly.
|
rand()doesn't depend on time. People typically seed their pseudo-random number generatorusingthe current time (through thesrand()function), but they don't have to. You can just pass whatever number you want tosrand().
If your random numbers aren't of a high enough quality for your purposes (libc'srandis notorious for... |
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... |
Sincenameis a string why don't you usestrcmpfunction?
```
if (strcmp(name, "exit") == 0)
{
exit(0);
}
```
|
how to pass array as arguments in C?
```
int a,b,c[10];
void Name1(int x, int y, int *z)
{
a = x;
b = y;
c = z;
}
```
I try to pass it as argument, but it does not build, how to fix it?
And is the declaration ofvoid Name1(int x, int y, int *z);is the same asvoid Name1(int x, int y, int z[])? does thevo... |
When you pass array as an argument to function it decays as an pointer to its first element.
So,
```
void Name1(int x, int y, int *z)
```
will work.But arrays are not assignable so:
```
c = z;
```
does not work, you will need to explicitly copy each array element from source to destination.
|
I'm writing code on Arduino (very similar to C, which I don't know, or very little), and I have a little issue concerning the switch/case statement.
I need my Arduino to do this or that depending on the values of a potentiometer (0 to 1023). However, I have no clue how to tell it case "0 to 200". For example, I tried... |
You will have to use a cascade of if's (also/especially if your value is a floating point number)
```
int value= ...;
if (value>=0 && value<=250 {
// some code 0..250
}
else
if (value>250 && value<=500) {
// some code 251..500
}
else
if (value>500 && value<=1000) {
// etc.
}
else {
// all other va... |
Is there a way to allocate a block of memory so that its starting address is aligned with a given page size? Note that I do not want to calculate the aligned address after the block has been allocated. The reason is that at some point I will have to call mremap() on the block: mremap requires the old address argument ... |
mremapmay only safely be used on memory regions allocated bymmap, which are inherently page-aligned. Using it on anything else is dangerous (formally, undefined behavior) and may appear to work but will probably badly break things in ways that you won't see right away.
|
I'm sorry to ask this question, because I found similar answered questions, but I'm having difficulty to understand how to read lines of unknown length but the structure is the same.
Each line is structured by the following: name:id:buyingPrice:sellingPrice:profit:quantity
The names and IDs are strings while the res... |
Have you thought about usingstrtokto parse the tokens after thefgets?
|
I've seen a lot of topics for PayPal integration for sites, Java, C# and even Objective-C, but I can't seem to find anything on C/C++, specifically. So where can I look to get an idea of what might be necessary to go about adding PayPal into a C++ project that is intended to operate on Windows, Mac and Linux, at least... |
Well, there is no official NVP library for C++ and I doubt using a third-party one (if it exists) is a good idea.
So, you should probably go with their SOAP API. Finding SOAP libs for C++ is not a problem.
Another option is simply using a webpage and opening it (that is, in the user's browser). Or you could integrat... |
I was solving Euler problem no. 10 that asks to find sum of all primes below 2million.
I am getting different results on usingsqrtandpowfunctions.
Usingsqrtgives the correct answer, plus using pow function takes more time. Here is my code.
```
for(sum=0,i=3;i<=2000000;i+=2)
{
for(j=3;j<=sqrt(i);j++)
if(i%... |
I can not reproduce your problem on my computer, but your testing ondoubleis a very dangerous one. Ifiis the square of a prime number you are relying on high precision of thesqrtandpowto have the correct result. Maybe on your system there is a slight rounding difference on one or more of such squares. You'd better tes... |
This works in VS C++ but produces an error compiling with GCC:
"error: invalid conversion from 'int ( * )(float, int)' to 'void *' [-fpermissive]|"
```
#define CLASS_HOOK_FUNC(vtable, name, tableindex) oNHook_##name = (_##name)vtable.HookVTableFunctionByIndex(tableindex, hNHook_##name);
#define HOOK_EXPORT(name) CL... |
Microsoft C++ permits an implicit conversion from a function pointer to avoid*which the standard doesn't permit. GCC emits an error.
There was a recent bug report on Microsoft Connect:https://connect.microsoft.com/VisualStudio/feedback/details/786150/msvc-performs-implicit-conversion-of-function-pointers-to-void
Yo... |
If I add//(*to an un-commented line in my source code, the rest of the font becomes italicized and changes color. The code still seems to compile however. And I cannot find a way to "undo" this change of font sequence with some other sequence. What is this used for? This occurs in C and C++ code so far as I can tell, ... |
//(*and//*)is a special comment block used to identify code that is automatically generated by the wxSmith plugin included with Code::Blocks.
|
```
char p[3][6]={{'a','b','c','\0'},{'d','e','f','\0'},{'g','h','i','\0'}};
char s[3][6]={"abc","def","ghi"};
```
Are they both same? If different please explain what way and how it is stored in memory?
|
They're the same in memory. Here in the VS 2010 debugger, I cast to char* so I can inspect the first 18 raw bytes of p and s:
|
```
debian@debian:~$ cat /tmp/test.c
#include<stdio.h>
int main(void)
{
int m=1;
printf("m=%d\n",&m);
printf("m=%p\n",&m);
}
debian@debian:~$ gcc /tmp/test.c -o /tmp/test.exe
debian@debian:~$ /tmp/test.exe
m=-1078061268
m=0xbfbe172c
debian@debian:~$ python
Python 2.7.3 (default, Jan 2 2013, 16:53:07)
[GCC 4.... |
They are the same, you're comparing signed to unsigned.
take a lookhereat the formats.
```
#include<stdio.h>
int main(void)
{
int m=1;
printf("m=%u\n",&m); // 3219008780
printf("m=%p\n",&m); // 0xbfde2d0c
}
```
|
i wrote a program in C using Dev-Cpp, my question is : how can i change and customize this program icon ?
|
The program will default to the lowest-numbered icon in its resources. (If you don't have a resource script yet then you need to add one to your project.)
|
In pure ANSI C (C89), I have the following.
```
unsigned y=<smallnumber>,x=y+3;
printf("%<whatgoeshere>\n",x-y);
```
What do I put after the%to be absolutely sure it will print3? I can see arguments for both%u(result is unsigned if both operands are) and%d(integral expressions are converted tointwhen passing argumen... |
Unsigned. Use%u. When performing default promotions on integral expressions (because ofprintf()being a variadic function), unsigned to signed conversion doesnothappen.
|
How can I allocate a bi-dimensional array usingmalloc?
This is my current code:
```
typedef struct object product, *pprod;
struct object{
int type;
int quantity;
pprod next;
};
pprod t[4][3];
```
Thanks a lot for your help.
|
To allocate memory in such a way that the layout is compatible with a normal two-dimensional array - or array of arrays - you need a pointer to an array of appropriate size,
```
pprod (*t)[m] = malloc(n * sizeof *t);
```
Thustis a pointer to arrays ofmelements of typepprod, and you can simply use it
```
t[i][j]
```... |
I picked up a copy of tiny c compiler (TCC) so i can do some c programming at work. Unfortunately, a new network security policy prohibits non-IT personnel from downloading/saving exe files. Of course, each time I try to complile helloworld.c the boss gets notified that I'm a malicious haxor...
My question -- is so... |
tryideoneit gives you a web based front end with the possibilities to compile code and and run it. the output of the program is then printed on the page.
|
Currently, I have a scenario much like this:
```
#define my_macro(var) __builtin_types_compatible_p(typeof(var), foo) ? do_something : do_something_else
```
However, inadvertently the macro gets passed this parameter:
```
my_macro(int x);
```
Which of course fails, becausetypeof(int x)isn't valid.
Is there a tran... |
Well, I found a way to do it, using yet another GCC extension, this time the statement expression:
```
#define my_typeof(definition) typeof(({ definition, _def; _def; }))
```
Which, of course, expands to:
```
typeof(({ int x, _def; _def; }))
```
Pretty ugly, but why do I care? It works.
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed9 years ago.Improve... |
If you usegcc -Eto output the preprocessed source, you'll see you have an extrareturninget_data:
```
const char* get_data(a_type a) { return return "a"; }
```
|
I read that C holds the carry-out from shifts and it can be found in processor-specific .h.
Is this true and should I use it? or should work out the carry-out bit myself ?
|
There is no standard way to access the carry bit(s) of primitive operations in C.
You will either need to perform the shift in a larger data type:
```
uint16_t foo = ...;
uint32_t tmp = (uint32_t)foo << shift;
uint16_t result = (uint16_t)tmp;
uint16_t carry = (uint16_t)(tmp >> 16);
```
or by performing the opposi... |
I tried an example fromGCC-Inline-Assembly-HOWTO
```
int main(void)
{
int foo = 10, bar=15;
_asm__volatile_( "addl %%ebx,%%eax;\n"
:"=a"(foo)
:"a"(foo), "b"(bar));
printf("foo+bar+%d\n",foo);
return 0;
}
```
the above code gives me thiserror:add_two.c:8:3: error... |
```
_asm__volatile_( "addl %%ebx,%%eax;\n"
```
...is not correct syntax.asmandvolatileare separate keywords.
```
__asm__ __volatile__( "addl %%ebx,%%eax;\n"
```
...compiles (and executes with correct result).
|
My function returns a float value from an object. If the function cannot find a proper float value an error should be returned so i can deal with it properly in the code.
My question is how to return an error.
The option of adding an extra parameter and using it to set an error marker is not preferred.
I could retu... |
If you#include <math.h>, you can returnNANin case of error. This is the only floatffor whichf == fisFALSE.
|
I have a small simple code to compare 2 floating point numbers:
I tried using fabs but it gives wrong weird result. What is the mistake, and what is the correct form?
```
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
void compareFloat(double a1, double a2)
{
if(fabs(a1 - a2) < DBL_EPSILON)
pri... |
The prototype for abs is an integer!
```
int abs (int number);
```
You want fabs for floating point
```
double fabs (double number);
```
|
Is it possible to configure a COM port (bitrate, parity) on Windows using only CRT functions? Or must I use Win32 functions (CreateFile, SetCommState, ReadFile, WriteFile), to use it with the bitrate and parity I want?
|
If by "CRT" you mean "standard C functions", then I would not expect it to be possible, no.
Serial ports are not something covered by the C language, so their configuration and management must be system-specific.
In Linux, it's thetermiosPOSIX APIthat you use for this, but as clarified inthis questionit's not availa... |
I am working on a C project. I am new to C so forgive me if this is a simple question.
I have achar **which is an array that contains various values. Out of all the values I have no problem what the values contain except for one where it keeps on core dumping on strcmp.
Below is my code:
```
if (strcmp(reportParame... |
Use"Y"which is a string literal, not'Y'which is acharliteral, asstrcmp()takes twoconst char*arguments.
Compile with warnings at the high level and don't ignore them (preferably treat them as errors).
|
I have this piece of code in C:
```
void f(void *x) {
printf(">>> %p\n", x);
}
int main() {
f NULL;
return 0;
}
```
I think is for the definition of NULL, but I'd like an explanation to clarify my doubt.
|
IfNULLis defined as((void *)0)or(0), then this expands tof ((void *)0)orf (0), which are proper function calls. The code errors out for anything non-parenthesized during compilation.
|
Here I want to generate a bit pattern to setndigits equal to1starting from positionp.
Digits are numbered from0 to 31.
Following is what I did.
```
int bitPattern(int n, int p) {
int hex, num1, num2;
hex = 0x80000000;
num1 = (hex >> (31 - p));
num2 = (hex >> (31 - (n+p)));
return num1 ^ num2;
}
``... |
You can do it like this:
```
return ((1<<n)-1)<<p;
```
To makenones at position zero, compute(2^n)-1; recall that2^nis1<<n, so the expression becomes((1<<n)-1). Now you need to addpzeros at the back, so shift the result left byp.
|
```
int
cycle(n) {
char *s3 = "Different";
int i, length;
length = strlen(s3)
printf("%s\n", s3);
for (i=0; i<length; i++) {
printf("%s\n", &s3[i]);
}
return 0;
}
```
I'm trying to print out one character at a time on each newline however the output looks like this -
```
C: Diffe... |
You should change:
```
printf("%s\n", &s3[i]);
```
to
```
printf("%c\n", s3[i]);
```
The former prints astringwhile the latter prints achar.
|
Just wondering what happens when I use the wrong format specifier in C?
For example:
```
x = 'A';
printf("%c\n", x);
printf("%d\n", x);
x = 65;
printf("%c\n", x);
printf("%d\n", x);
x = 128;
printf("%d\n", x);
```
|
what happens when I use the wrong format specifier in C?
Generally speaking, undefined behaviour.*
However, recall thatprintfis a variadic function, and that the arguments to variadic functions undergo thedefault argument promotions. So for instance, acharis promoted to anint. So in practice, these will both give ... |
How can I allocate a bi-dimensional array usingmalloc?
This is my current code:
```
typedef struct object product, *pprod;
struct object{
int type;
int quantity;
pprod next;
};
pprod t[4][3];
```
Thanks a lot for your help.
|
To allocate memory in such a way that the layout is compatible with a normal two-dimensional array - or array of arrays - you need a pointer to an array of appropriate size,
```
pprod (*t)[m] = malloc(n * sizeof *t);
```
Thustis a pointer to arrays ofmelements of typepprod, and you can simply use it
```
t[i][j]
```... |
I picked up a copy of tiny c compiler (TCC) so i can do some c programming at work. Unfortunately, a new network security policy prohibits non-IT personnel from downloading/saving exe files. Of course, each time I try to complile helloworld.c the boss gets notified that I'm a malicious haxor...
My question -- is so... |
tryideoneit gives you a web based front end with the possibilities to compile code and and run it. the output of the program is then printed on the page.
|
Currently, I have a scenario much like this:
```
#define my_macro(var) __builtin_types_compatible_p(typeof(var), foo) ? do_something : do_something_else
```
However, inadvertently the macro gets passed this parameter:
```
my_macro(int x);
```
Which of course fails, becausetypeof(int x)isn't valid.
Is there a tran... |
Well, I found a way to do it, using yet another GCC extension, this time the statement expression:
```
#define my_typeof(definition) typeof(({ definition, _def; _def; }))
```
Which, of course, expands to:
```
typeof(({ int x, _def; _def; }))
```
Pretty ugly, but why do I care? It works.
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed9 years ago.Improve... |
If you usegcc -Eto output the preprocessed source, you'll see you have an extrareturninget_data:
```
const char* get_data(a_type a) { return return "a"; }
```
|
I read that C holds the carry-out from shifts and it can be found in processor-specific .h.
Is this true and should I use it? or should work out the carry-out bit myself ?
|
There is no standard way to access the carry bit(s) of primitive operations in C.
You will either need to perform the shift in a larger data type:
```
uint16_t foo = ...;
uint32_t tmp = (uint32_t)foo << shift;
uint16_t result = (uint16_t)tmp;
uint16_t carry = (uint16_t)(tmp >> 16);
```
or by performing the opposi... |
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.
Can I compile a specific function o... |
You must move the function into a separate compile unit (a.cfile), and link it. You cannot switch compilers in the middle of a compile unit.
|
I have this program and I want it to increment by one and print the value of my counter each time I give a character
```
#include <stdio.h>
int main(void){
//Declarations
long nc;
//Instantiations
nc = 0;
while (getchar() != EOF){
++nc;
printf("%... |
Terminal input is normallyline buffered. Your program only gets input to process when you press ENTER. If you type several characters, you will get one line of output for each character you input (plus the newline itself) asgetchar()returns each character in sequence.
|
I have foundSetupDiGetDeviceRegistryPropertyto get properties from devices, but I havent figured out how to get the parent property (you can see this property when you open a devices properties in device manager, click on details, and choose parent from the property drop down. How do I access that property from native... |
The predefined DEVPKEY_Device_Parent guid is the key for the Parent property. Read it with SetupDiGetDeviceInterfaceProperty().
|
So I'm running some C code on a few different machines and on all of them except one I'm getting the same results. But on one machine, I am getting an incorrect value for Zth.
On my machine I get the correct value. On the other machine I get 0.000 + 0.000 which is not right. I'm guessing it has something to do with... |
Break the expression down into smaller and smaller pieces until you find the problem.
Double check your compiler command and make sure it isn't using a different set of options for the build, such as-ffast-math.
|
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.
Lets say I have function of type vo... |
Use function pointers in C.
```
void (*array[2])();
array[0] = fun1;
array[1] = fun2;
```
Orstd::functionin C++:
```
std::function<void(void)> fn1 = fun1;
std::function<void(void)> fn2 = fun2;
std::vector<std::function<void(void)> > v;
v.push_back(fn1);
v.push_back(fn2);
```
|
I am using a#ifdefblock to conditionally include a block of code based on -Dflagpassed to the compiler.
Is there a way to implement this with anif?
Something along the lines of:
```
if (defined(flag)) {
}
```
|
You use preprocessor to produce a different flag, which could be tested with a run-timeifstatement, like this:
```
#ifdef flag
#define flag_defined 1
#else
#define flag_defined 0
#endif
```
Now you can do this:
```
if (flag_defined) ...
```
|
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.
Can I compile a specific function o... |
You must move the function into a separate compile unit (a.cfile), and link it. You cannot switch compilers in the middle of a compile unit.
|
I have this program and I want it to increment by one and print the value of my counter each time I give a character
```
#include <stdio.h>
int main(void){
//Declarations
long nc;
//Instantiations
nc = 0;
while (getchar() != EOF){
++nc;
printf("%... |
Terminal input is normallyline buffered. Your program only gets input to process when you press ENTER. If you type several characters, you will get one line of output for each character you input (plus the newline itself) asgetchar()returns each character in sequence.
|
I have foundSetupDiGetDeviceRegistryPropertyto get properties from devices, but I havent figured out how to get the parent property (you can see this property when you open a devices properties in device manager, click on details, and choose parent from the property drop down. How do I access that property from native... |
The predefined DEVPKEY_Device_Parent guid is the key for the Parent property. Read it with SetupDiGetDeviceInterfaceProperty().
|
So I'm running some C code on a few different machines and on all of them except one I'm getting the same results. But on one machine, I am getting an incorrect value for Zth.
On my machine I get the correct value. On the other machine I get 0.000 + 0.000 which is not right. I'm guessing it has something to do with... |
Break the expression down into smaller and smaller pieces until you find the problem.
Double check your compiler command and make sure it isn't using a different set of options for the build, such as-ffast-math.
|
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.
Lets say I have function of type vo... |
Use function pointers in C.
```
void (*array[2])();
array[0] = fun1;
array[1] = fun2;
```
Orstd::functionin C++:
```
std::function<void(void)> fn1 = fun1;
std::function<void(void)> fn2 = fun2;
std::vector<std::function<void(void)> > v;
v.push_back(fn1);
v.push_back(fn2);
```
|
I am using a#ifdefblock to conditionally include a block of code based on -Dflagpassed to the compiler.
Is there a way to implement this with anif?
Something along the lines of:
```
if (defined(flag)) {
}
```
|
You use preprocessor to produce a different flag, which could be tested with a run-timeifstatement, like this:
```
#ifdef flag
#define flag_defined 1
#else
#define flag_defined 0
#endif
```
Now you can do this:
```
if (flag_defined) ...
```
|
Say I have an array of n elements and also I have a pointer reference to one of the elements. Based solely on this information is it possible to find out the position of the element in the array?
|
If you know for sure that the element is in the array, then yes, it is simple:
```
position = the_pointer - the_array;
// or
position = &the_reference - the_array;
```
If you aren't sure if the element is part of the array, then doing this may be undefined behavior.
There is no (standard approved) way to tell that ... |
I want an equivalent forprintf("%2.2x", var);tocerr<<in C++.code:
```
typedef unsigned char byte;
static byte var[10];
for(i=1; i<10; i++)
printf("%2.2x", var[i]);
```
The idea is to redirect the debugging to a file like this:./myprog 2>out.txt.If I don't ask too much I would like to receive explanations to... |
Usefprintf(stderr, ...), e.g.:
```
fprintf(stderr, "%2.2x", var[i]);
```
|
Assuming that I'm printing a string, as follows:
```
printf("%s", s);
```
What can we assume the asymptotic complexity of this function is?
Is itO(n)where n isstrlen(s)- it's length? Or is it somehowO(1), constant time. Or something different? I supposed you'd need to know how printf tends to be implemented, howeve... |
It's complexity is O(m + n), where m is the size of the input and n is the size of the output.
If not passing additional parameters like in your case time complexity is O(2*m) = O(m).
But be aware that your code can fail, because s may contain formatting codes itself and that will produce an undefined/unknown/unpred... |
This question already has answers here:Is an array argument passed to a function not a constant pointer?(6 answers)Closed10 years ago.
If there is a function that is declared asvoid foo(char s[])and another is declared asvoid goo(char *s), then are the two declarations equivalent?
|
Yes, an array always decays to a pointer when passed to a function as an argument.
This will print the same result:
```
#include <stdio.h>
void foo(char* arg, int size)
{
int i;
for (i = 0; i < size; i++)
printf("%c", arg[i]);
printf("\n");
}
void bar(char arg [], int size)
{
int i;
for... |
If I have two C structures initialised to have identical members, can I guarantee that:
```
memcmp(&struct1, &struct2, sizeof(my_struct))
```
will always return zero?
|
I don't think you can safelymemcmpa structure to test for equality.
From C11§6.2.6.6 Representations of types
When a value is stored in an object of structure or union type,
including in a member object, the bytes of the object representation
that correspond to any padding bytes take unspecified values.
This im... |
The following code gives the error"error: invalid conversion from void* to char* [-fpermissive]"
```
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char *t = malloc(20);
}
```
However, casting the result of malloc solves the problem. But I cannot understand why asthisquestion says that cast... |
You compiled this C program using a C++ compiler. Itisnecessary to cast the result of malloc in C++, but not in C.
|
I'm having problems with some codes in C:
```
char opt, name[10], path[25];
printf("Things\nMore things\n");
printf("Even more things\n");
printf("\nChar: ");
scanf("\n%c",&opt);
printf("\nTask name: ");
scanf("%s",name);
printf("Name: %s\n", name);
printf("\nFolder name: ");
scanf("%s",path);
printf("Name: %s\n", na... |
If you want to limit user input to exact amount of chars, try
```
scanf("%24s",path);
```
It should prevent buffer-overloading for your char arrays.
|
I have a question regarding to the function declaration:
I declared a function in b.c
```
//b.c
void getNumber();
//common header
common.h
```
In a.c I use it like this:
//a.c
```
#include "common.h"
void getInfo()
{
getNumber();
}
```
but it complain the getNumber is implicit declaration of function, what is... |
add the following line tocommon.h
```
void getNumber();
```
the b.c file should contain the function definition in this way
```
void getNumber() {
....
}
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.