question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I wrote a SIMD wrapper. To ease the use of different types, I made it as a union:
```
#include <emmintrin.h>
union SIMDType16
{
__m128 simd_by_float;
__m128i simd_by_int;
__m128d simd_by_double;
}
```
However, from some place I heard that the type information in Intel SIMD intrisics is related to hardwa... |
This is absolutely fine, except of course that there are plenty of reasons why unions can get you into trouble, totally independent of SIMD types. For example, if you assign to sims_by_float and then read simd_by_double, you invoke undefined behaviour and your program can crash. SeeC++ Undefined behaviour with unions
... |
I was looking at an example and I saw this:
```
char *str;
/* ... */
if (!str || !*str) {
return str;
}
```
Does it mean it's empty or something?
|
stris a char pointer.!negates it. Basically,!strwill evaluate to true (1) whenstr == NULL.
The second part is saying, (ifstrpoints to something) evaluate to true (1) if the first character is a null char ('\0') - meaning it's an empty string.
Note:*strdereferences the pointer and retrieves the first character. This ... |
How can I get the size and the starting address of the stack per thread in posix C? Or if there's no standard posix way to do this, at least in Linux with gcc.
Some programs such as the Boehm-gc should do this somehow, but I'm now quite confused reading their code. Can you give me some function names?
|
The "clean" but non-portable way to do this is to use thepthread_getattr_np(Linux/glibc, etc.) or similar function to obtain an attributes object for the thread in question, thenpthread_attr_getstackto obtain the stack base/size. There is no portable way to do this, however, and there's essentially nothing portable yo... |
```
byte bigHeart[] = {
B01100110,
B11111111,
B11111111,
B11111111,
B01111110,
B00111100,
B00011000,
B00000000};
```
I'm trying to use it to print to an led screen. COnverting from ino to c to convert to assembly. Cant's quite get it to where the compiler likes it for disassembly from c
|
This should work in C. The binary constants are converted to hexadecimal:
```
unsigned char bigHeart[] = {
0x66,
0xFF,
0xFF,
0xFF,
0x7E,
0x3C,
0x00
};
```
|
I created a sample .h file in C and it didn't work, for some reason. The files are as follows:
header.c:
```
#include <stdio.h>
#include "header.h"
int add(int a, int b) {
int tmp=a;
int i;
for(i=0, i==tmp, i++) {
b++;
}
return(b);
}
```
header.h:
```
#ifndef HEADER_H
#define HEADER_H
int add(int a, int b);
#end... |
You need to compile both main.c and header.c into the same executable:
```
all: main
main: main.o header.o
gcc -o main main.o header.o
header.o: header.c header.h
gcc -c header.c
main.o: main.c header.h
gcc -c main.c
```
Or for a one-liner without a make file:
```
gcc -g -o main main.c header.c
```
|
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.Closed8 years ago.Improve... |
There's shouldn't be a semicolon in theint main(void);declaration.
Try replacing line 4 with:int main(void)instead.
Also, please read up on C function declaration syntaxhttps://msdn.microsoft.com/en-us/library/c4d5ssht.aspx.
|
I have been trying to create a program where you can input text into achararray. The program does compile, however when I run the program it prints a weird question mark character without end.
```
int main()
{
char array[20];
int arraynumber;
scanf("%c", &array);
for(arraynumber = 0; a... |
```
int main(int argc, char **argv)
{
char array[20];
int arraynumber;
for (arraynumber = 0; arraynumber < 20; arraynumber++){
scanf("%c", &array[arraynumber]);
}
for(arraynumber = 0; arraynumber < 20; arraynumber++){
printf("%c", array[arraynumber]);
}
}
```
Couple of problems... |
I am trying to use srand along with time for randomized value. If I look at
srand function it takes unsigned int - but if we initialize it with time which seems to have long long value - so compiler keeps complaining about loss of precision warning. Any better way to do things ?
```
// srand definition
void srand (u... |
If you are using C++, look into<random>. It has much better PRNGs.
If you're limited torand, you can, in this case, ignore the warning, or better, tell the compiler you don't care by explicitly casting(unsigned)time(NULL).
|
I want to write a kernel driver using Visual Studio 2015, so I installed the Windows 10 SDK and WDK alongside with VS 2015.
I created empty kernel driver project and main.c inside the project.
However, intellisense does not work and error list shows:
"command-line error: exception handling option can be used only w... |
C++ is usually not used in kernel mode drivers because it is not supported. I use some C++ in my drivers but that is the exception.
I see this same issue with VS 2015. Just create a blank C file in your project and you will see the intellisense (~) at the first column of the first line. This means intellisense is ... |
I couldn't disable it even though by using-std=c89flag. How can I disable it?
|
You can generate an error for variable length arrays using a compiler flag:
```
-Werror=vla
```
|
In the C language, you have local variables in functions that are destroyed when the function returns (they arn't accessible anymore, unless you pass around pointers obviously).
What happens to sockets? Specifcially, if I create a socket in 1 function, can I pass around the sockid and bind it in another, listen in an... |
There should be no problem doing that. For example:
```
int sock = my_socket();
my_bind(sock);
my_listen(sock);
int connected_sock = my_connect(sock);
my_read(connected_sock);
```
|
So I'm asked to make a method that empty out the entire linked list.
This is what I have now, and I have no idea why it doesn't want to work:
```
void deleteList(){
}
```
|
Your function needs to be passed the head of the list, i.e.struct node *headthat it can operate on. Then you can use that instead ofcurrentto keep track of the current head.
```
void deleteList(struct node *head){
struct node* next;
while (head!= NULL) {
next = head->next;
free(head);
... |
I built C code separately and have libperson.a output. I want to include this library into my xcode project.
Added this .a under “Link Binary with Libraries” to my project.
```
#import "person.h"
```
It can't find the person.h. What am I doing wrong?
|
You also need to add the header file(s) to you project. Or, if the headers are better off somewhere else, you need to add a Header Search Path to your Xcode target's Build Settings; in that way Xcode can find them.
Coming from Java: C has header files in which you typically declare public interfaces of a matching so... |
Is there a general template for sorting a singly linked list alphabetically? The other posts on here have post-specific code and what I am looking for is more of a broad solution that I can tweak and use repeatedly in the future. I'd even appreciate just a link to somewhere that has an explanation of how to build my o... |
This mergesort algorithm for linked list could be useful for you. It's use is generic where you could alter it to your use case. There is also some C code for you to follow along with.
http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
|
```
char dev[20] = "dev_name";
char dest[32];
strncpy(dest,dev,sizeof(dev));
dest[sizeof(dev)-1] = 0;
```
What doesdest[sizeof(dev)-1] = 0;means?
|
In your code, assumingsizeis analogous tosizeof,
```
dev_name[size(dec_name)-1] = 0;
```
dev_name[size(dec_name)-1]points to the last element of the array, rememberCarrays use0based indexing.
Then, by definition, astringin c is exxentially achararraywithnull-termination, so if you want to use a char array asstring,... |
-Ogis a relatively new optimization option that is intended to improve the debugging experience while apply optimizations. If a user selects-Og, then I'd like my source files to activate alternate code paths to enhance the debugging experience. GCC offers the__OPTIMIZE__preprocessor macro, but its only set to 1 when o... |
I don't know if this is clever hack, but it is a hack.
```
$ gcc -Xpreprocessor -dM -E - < /dev/null > 1
$ gcc -Xpreprocessor -dM -O -E - < /dev/null > 2
$ diff 1 2
53a54
> #define __OPTIMIZE__ 1
68a70
> #define _FORTIFY_SOURCE 2
154d155
< #define __NO_INLINE__ 1
```
clang didn't produce the FORTIFY one.
|
Take for example a simple C function for lua:
```
int luacfunc(lua_State *L)
{
printf("%g\n", lua_tonumber(L, 1) + lua_tonumber(L, 2));
}
```
In this case, the parameters show up as index1and2. Since positive number represent the stack bottom-up, it would mean that the parameters are located at the bottom of the... |
The Lua stack is specific to your function call. Each C function call gets its own "stack" (it's actually a slice of a bigger stack, but that's hidden from you). Your arguments are both at the top and at the bottom, because they're the only thing on your stack.
|
I have been trying to create a program where you can input text into achararray. The program does compile, however when I run the program it prints a weird question mark character without end.
```
int main()
{
char array[20];
int arraynumber;
scanf("%c", &array);
for(arraynumber = 0; a... |
```
int main(int argc, char **argv)
{
char array[20];
int arraynumber;
for (arraynumber = 0; arraynumber < 20; arraynumber++){
scanf("%c", &array[arraynumber]);
}
for(arraynumber = 0; arraynumber < 20; arraynumber++){
printf("%c", array[arraynumber]);
}
}
```
Couple of problems... |
I am trying to use srand along with time for randomized value. If I look at
srand function it takes unsigned int - but if we initialize it with time which seems to have long long value - so compiler keeps complaining about loss of precision warning. Any better way to do things ?
```
// srand definition
void srand (u... |
If you are using C++, look into<random>. It has much better PRNGs.
If you're limited torand, you can, in this case, ignore the warning, or better, tell the compiler you don't care by explicitly casting(unsigned)time(NULL).
|
I want to write a kernel driver using Visual Studio 2015, so I installed the Windows 10 SDK and WDK alongside with VS 2015.
I created empty kernel driver project and main.c inside the project.
However, intellisense does not work and error list shows:
"command-line error: exception handling option can be used only w... |
C++ is usually not used in kernel mode drivers because it is not supported. I use some C++ in my drivers but that is the exception.
I see this same issue with VS 2015. Just create a blank C file in your project and you will see the intellisense (~) at the first column of the first line. This means intellisense is ... |
I couldn't disable it even though by using-std=c89flag. How can I disable it?
|
You can generate an error for variable length arrays using a compiler flag:
```
-Werror=vla
```
|
In the C language, you have local variables in functions that are destroyed when the function returns (they arn't accessible anymore, unless you pass around pointers obviously).
What happens to sockets? Specifcially, if I create a socket in 1 function, can I pass around the sockid and bind it in another, listen in an... |
There should be no problem doing that. For example:
```
int sock = my_socket();
my_bind(sock);
my_listen(sock);
int connected_sock = my_connect(sock);
my_read(connected_sock);
```
|
So I'm asked to make a method that empty out the entire linked list.
This is what I have now, and I have no idea why it doesn't want to work:
```
void deleteList(){
}
```
|
Your function needs to be passed the head of the list, i.e.struct node *headthat it can operate on. Then you can use that instead ofcurrentto keep track of the current head.
```
void deleteList(struct node *head){
struct node* next;
while (head!= NULL) {
next = head->next;
free(head);
... |
I built C code separately and have libperson.a output. I want to include this library into my xcode project.
Added this .a under “Link Binary with Libraries” to my project.
```
#import "person.h"
```
It can't find the person.h. What am I doing wrong?
|
You also need to add the header file(s) to you project. Or, if the headers are better off somewhere else, you need to add a Header Search Path to your Xcode target's Build Settings; in that way Xcode can find them.
Coming from Java: C has header files in which you typically declare public interfaces of a matching so... |
Is there a general template for sorting a singly linked list alphabetically? The other posts on here have post-specific code and what I am looking for is more of a broad solution that I can tweak and use repeatedly in the future. I'd even appreciate just a link to somewhere that has an explanation of how to build my o... |
This mergesort algorithm for linked list could be useful for you. It's use is generic where you could alter it to your use case. There is also some C code for you to follow along with.
http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
|
I want execute a code only one time. I used a solution based on a global varibale of bool type. My question, is it the best solution?
Remark: I use ucos-II.
```
if (TRUE == Lock)
{
/*Code to execute one time*/
}
/*The reste of the code*/
```
|
A simple code using a static variable.
```
static bool once = false;
if (once == false)
{
once = true;
// do your "once" stuff here
}
```
|
This question already has answers here:Conflicting types for pointer variable in C (Error)(3 answers)Closed8 years ago.
```
#include<stdio.h>
int c;
c=35;//**warning:** data definition has no type or storage class
int main(){
.....
.....
return 0;
}
```
When I run this code it give Warning as I mentioned in the comm... |
Only assignmemnt is an instruction and each instruction should appear inside a function body.
In global scope only a special case, initialization through assignment while definition is allowed.
|
This question already has answers here:How # flag in printf works?(3 answers)Closed8 years ago.
Can someone explain what the purpose of the#sign in this printf statement:
```
printf("%#d\n",15);
```
It seems to be ignored while printing. The output of the statement is:
15
|
You can look in theprintfdocumentation. You can find the description for#underflags:
Used with o, x or X specifiers the value is preceded with 0, 0x or 0X
respectively for values different than zero. Used with e, E and f, it
forces the written output to contain a decimal point even if no digits
would follow. By... |
Suppose we have a parent process and if it calls an exec function, after calling a fork to create child process.
Now what happens to the child process: will it act like the original parent process, such that the user won't spot the difference that the parent process got replaced with some other binary ?
I think this... |
The pid of the parent process will remain the same after theexec, so the process hierarchy won't be affected.
The problem with this approach is that the newly replaced parent process generally won't be aware that it has previously spawned a child and will not callwaitorwaitpidon it. This will cause the child process ... |
```
#include<stdio.h>
//This program is about structure and there pointer
//
typedef struct{
int i;
char c;
}str1,*strptr;
str1 str[5];
strptr *ptr;
int main(){
ptr = &str;// This is shown as incompatible type assignment **warning**
ptr->i=35; // **error**: request for member 'i' in something
... |
In your code,strptris already a pointer type. You need to change
```
strptr *ptr;
```
to
```
strptr ptr;
```
|
I have been working on driver code that uses event codes. But I haven't find any documentations regarding event codes in Linux drivers.
One thing I find out that mouse device driver uses this event codes for locating the mouse pointer. And another thing I know of event code is User space may get the current event cod... |
You can find the documentation of event codes and much more here
https://git.kernel.org/cgit/linux/kernel/git/stable/linux-stable.git/tree/Documentation/input?id=refs/tags/v4.1.3
|
I am attempting to learn C and have purchased a book to demonstrate some key aspects of the language. It was all well until I found many of the examples did not function properly. My IDE(Xcode) did not show any syntax errors so I do not understand why the following code will not work.
```
#include <stdio.h>
/*... |
Remove extra empty spaces.
Try the following.
```
#include <stdio.h>
/* count characters in input; 2nd version */
int main() {
double nc;
for (nc = 0; getchar() != EOF; ++nc)
;
printf("%.0f\n", nc);
}
```
|
Is there any macro in C or C++ represent the max and min value of int32_t and int64_t? I know it can be literally defined by oneself, but it's better if there is a standard macro. Please note I'm not asking about max of int, long ,etc. butintXX_t
|
In C++, there isstd::numeric_limits::min()andstd::numeric_limits::max()in the<limits>header:
```
std::cout << std::numeric_limits<std::int32_t>::min() << std::endl;
```
and so on. In C, the header<stdint.h>definesINT32_MIN,INT32_MAXetc. These are also available in the C++<cstdint>header.
|
I am writing a simple app in C that is meant to act as a shell. It takes user input from stdin, stores it as a string, and then uses execl with that string to execute it in the terminal as a binary executable. However, execl does not take binaries in the form of "ls" or "who", but instead it expects their absolute pat... |
Useexeclporexecvpinstead ofexeclorexecvp. Thepversions of these calls searchPATHto find the executable if it doesn't contain any slashes.
|
i come across this question in an interview recently. they asked me when we create new user defined Type using Typedef (Like typedef unsigned char CHAR) what happens internally??
|
Internally there will happen nothing because it is only the information for the compiler that you introduced some alias for another type.
According to the C Standard (6.7.8 Type definitions)
...A typedef declaration does not introduce a new type, only a synonym for the type so specified.
Take into account that oppo... |
Is there any macro in C or C++ represent the max and min value of int32_t and int64_t? I know it can be literally defined by oneself, but it's better if there is a standard macro. Please note I'm not asking about max of int, long ,etc. butintXX_t
|
In C++, there isstd::numeric_limits::min()andstd::numeric_limits::max()in the<limits>header:
```
std::cout << std::numeric_limits<std::int32_t>::min() << std::endl;
```
and so on. In C, the header<stdint.h>definesINT32_MIN,INT32_MAXetc. These are also available in the C++<cstdint>header.
|
I am writing a simple app in C that is meant to act as a shell. It takes user input from stdin, stores it as a string, and then uses execl with that string to execute it in the terminal as a binary executable. However, execl does not take binaries in the form of "ls" or "who", but instead it expects their absolute pat... |
Useexeclporexecvpinstead ofexeclorexecvp. Thepversions of these calls searchPATHto find the executable if it doesn't contain any slashes.
|
i come across this question in an interview recently. they asked me when we create new user defined Type using Typedef (Like typedef unsigned char CHAR) what happens internally??
|
Internally there will happen nothing because it is only the information for the compiler that you introduced some alias for another type.
According to the C Standard (6.7.8 Type definitions)
...A typedef declaration does not introduce a new type, only a synonym for the type so specified.
Take into account that oppo... |
Is the memory allocation system of C completely random or does it use pseudo random generator ?
What is the actual algorithm for memory allocation that happens at the back ?
|
C doesn't do memory allocation.You, the programmer, have to do it yourself based on the simple primitivesmalloc()andfree(), which do nothing but ask the OS for free chunks of memory to give you.
|
I am trying to implement the following function in CUDA:
```
int compare(unsigned a, unsigned b) {
if (a == b) {
return 0;
} else {
if (a < b) return -1;
else return 1;
}
}
```
I am currently using a pretty naive macro
```
#define CMP(X, Y) (((X) == (Y)) ? 0 : (((X) < (Y)) ? -1 :... |
You could use a branch-less equivalent, that is:
```
(a > b) - (a < b)
```
This solves potential warp divergence.
In your code,nvcccompiler may eliminate divergence anyway, with usage ofbranch predication. But, even with this technique, some threds in warp may be inactive. You might observe this inThread Execution ... |
I have the below part of code in which I noticed that if I change the 0 to 1 the result is the same. I get theSTACKprint();with "on" as the second argument, nothing with anything else and if there is no argument I get a segmentation fault. I guess for the segmentation fault I need to check if the argument isNULLbut I ... |
To avoid the segfault, check the value ofargcto discover whetherargv[2]exists. Ifargc < 3,argv[2]wasn't supplied.
strcmp()doesn't return true/false; it returns a value either less than, equal to, or greater than zero depending on the relative values of its arguments.
|
In Matlab's mex files there is a functionmxIsScalarthat tells you if that input to the mex files is an scalar or not. But that function has been introduced in R2015a.
If using a previous version of Matlab (2014b in my case, if that matters), what is the most elegant way of checking if an input is an Scalar or an arra... |
As well asmxGetMandmxGetN, there's alsomxGetNumberOfElements, which you could use like so:
```
bool const isScalar = (size_t(1) == mxGetNumberOfElements(prhs[0]));
```
|
Is there a way to use the name of a#defineparameter as another#defineparameter? For example:
```
#define TEST 1
#define FOO(X) foo_##X
#define BAR(X) FOO(##X)
BAR(TEST)
```
Where it results in:
```
foo_TEST
```
Not:
```
foo_1
```
This doesn't work as it gives:
```
pasting "(" and "TEST" does not give a valid... |
Remove the double '#' in the BAR marco.
See the working example:http://ideone.com/hEhkKn
```
#include <stdio.h>
#define FOO(X) foo_##X
#define BAR(X) FOO(X)
int main(void) {
int BAR(hello);
return 0;
}
```
Regarding to your updated question:
If you want to use a defined name like 'TEST', so change you... |
Is there a way to get the exact words passed into the#definewithout stringifying? Example use case:
```
#define NUM 1
#define CREATE_FUN(X) \
void prefix_X() { \ // used exact words passed in
int x = X; \ // use value later on
}
CREATE_FUN(NUM)
```
And output would look like:
```
void prefix_NUM() {
int x... |
Use the token concatenation (##):
```
#define NUM 1
#define CREATE_FUN(X) \
void prefix_##X() { \
int x = X; \
}
CREATE_FUN(NUM)
```
|
I have the following program, the perfect numbers won't print, only output are the numbers 1 and 2, which are not perfect. What's wrong, is it a scope problem or is it the loops? Adding break statement after print statement causes output of all numbers 1 - 99.
```
int sum = 0;
for (int i = 1; i < 100; i++) {
fo... |
Three problems:
summust be initialized to zero foreveryi, not just in the beginningthe second loop condition must bej < i, as per definition of perfect number the number itself is excludedthe check forsum == iand followingprintfmust be moved outside the inner loop, otherwise it prints intermediate results
|
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.Closed8 years ago.Improve... |
In your case,bis having a decimal value 10, not ahexadecimal10. Change
```
int b=10;
```
to
```
int b=0x10;
```
|
If I run the following code,graph[0][0]gets1whilegraph[0][1]gets4.
In other words, the linegraph[0][++graph[0][0]] = 4;puts1intograph[0][0]and4intograph[0][1].
I would really appreciate if anyone can offer reasonable explanation.
I observed this from Visual C++ 2015 as well as an Android C compiler (CppDriod).
```... |
Let's break it down:
```
++graph[0][0]
```
This pre-increments the value atgraph[0][0], which means that nowgraph[0][0] = 1, and then the value of the expression is1(because that is the final value ofgraph[0][0]).
Then,
```
graph[0][/*previous expression = 1*/] = 4;
```
So basically,graph[0][1] = 4;
That's it! N... |
In Matlab's mex files there is a functionmxIsScalarthat tells you if that input to the mex files is an scalar or not. But that function has been introduced in R2015a.
If using a previous version of Matlab (2014b in my case, if that matters), what is the most elegant way of checking if an input is an Scalar or an arra... |
As well asmxGetMandmxGetN, there's alsomxGetNumberOfElements, which you could use like so:
```
bool const isScalar = (size_t(1) == mxGetNumberOfElements(prhs[0]));
```
|
Is there a way to use the name of a#defineparameter as another#defineparameter? For example:
```
#define TEST 1
#define FOO(X) foo_##X
#define BAR(X) FOO(##X)
BAR(TEST)
```
Where it results in:
```
foo_TEST
```
Not:
```
foo_1
```
This doesn't work as it gives:
```
pasting "(" and "TEST" does not give a valid... |
Remove the double '#' in the BAR marco.
See the working example:http://ideone.com/hEhkKn
```
#include <stdio.h>
#define FOO(X) foo_##X
#define BAR(X) FOO(X)
int main(void) {
int BAR(hello);
return 0;
}
```
Regarding to your updated question:
If you want to use a defined name like 'TEST', so change you... |
Is there a way to get the exact words passed into the#definewithout stringifying? Example use case:
```
#define NUM 1
#define CREATE_FUN(X) \
void prefix_X() { \ // used exact words passed in
int x = X; \ // use value later on
}
CREATE_FUN(NUM)
```
And output would look like:
```
void prefix_NUM() {
int x... |
Use the token concatenation (##):
```
#define NUM 1
#define CREATE_FUN(X) \
void prefix_##X() { \
int x = X; \
}
CREATE_FUN(NUM)
```
|
I am learning Pro*c language. I am trying to create a sequence. But I am not getting which keyword to use as when we create a cursor then we use declare with it as
```
EXEC SQL DECLARE CUR_NAME CURSOR FOR <<SELECT STMT>>.
```
So is there any way to create a sequence in Pro*C?
I tried this way using EXECUTE IMMEDIAT... |
Got the solution by 2 ways we can do it:
1st is :
```
EXEC SQL create sequence seq1 minvalue 1 maxvalue 9999 start with 1 increment by 1;
EXEC SQL COMMIT WORK RELEASE;
```
2nd :
```
EXEC SQL EXECUTE IMMEDIATE 'create sequence seq1 minvalue 1 maxvalue 9999 start with 1 increment by 1';
EXEC SQL COMMIT WORK RELEAS... |
The problem is that on one platform (windows, mvsc2015)uint64_tis defined asunsigned long longand on another (ubuntu, clang) it'sunsigned longand there is the code which looks likesprintf(buffer, "%#llx", u64key);
|
The solution is to use C99's format macros, in particularPRIu64for anuint64_t:
```
#include <inttypes.h>
…
sprintf(buffer, "%#" PRIu64 "\n", u64key);
```
|
I have a question about the fseek() usage in C. I know it can set the offset position of a file descriptor created by fopen(). But can it also set the offset position of a newly created file? To be more specific, can I:
```
FILE * pFile;
pFile = fopen ( "myfile.txt" , "wb" ); //myfile.txt doesn't exit before
fse... |
http://en.cppreference.com/w/c/io/fseek
POSIX allows seeking beyond the existing end of file. If an output is
performed after this seek, any read from the gap will return zero
bytes. Where supported by the filesystem, this creates asparse file.
|
What's the meaning of:
```
#include <stdio.h>
int main(){
double bmax = 31.4159265;
printf("%1.4e\n", bmax);
}
```
What is the meaning of%1.4e? I know%ffor double.
|
```
%e specifier is used to print value of float\double in exponential format.
```
So here%1.4ewill print 1 digit before the decimal point and 4 digits after the decimal point.
So ifbmax=12.242then the output will be1.2242e+01.
|
This question already has answers here:Why is unsigned integer overflow defined behavior but signed integer overflow isn't?(7 answers)Closed8 years ago.
When I assignivalue greater thanINT_MAXin this code -
```
#include <stdio.h>
#include <limits.h>
int main()
{
int i;
i=INT_MAX+3;
printf("%d \n",INT_MAX... |
Yes, signed integer overflow has undefined behavior in C.i > INT_MAXis never true for anyint i. How can you have anintgreater than the maximum possibleint?
|
I'm trying to build vp8 for android armv6 but with no luckI tried to set --target=armv6-android-gcc but i get Unrecognized toolchain 'armv6-android-gcc' errorbut --target=armv7-android-gcc works just fine.how should i do it ?
|
There is no ARM6 Android ABI in the NDK. ARM6 Android devices use the ARM5 ABI (which is the plain androideabi).
|
My main.c:
```
#include <stdlib.h>
#include <gtk/gtk.h>
int main(int argc, char **argv)
{
return EXIT_SUCCESS;
}
```
I use:
```
gcc `pkg-config --cflags --libs libgtk+-2.0` -o tresor main.c
```
but I get this error:
```
Package libgtk+-2.0 was not found in the pkg-config search path.
Perhaps you should add... |
Just need to adjust the package name to gtk+-2.0 :
```
gcc `pkg-config --cflags --libs gtk+-2.0` -o tresor main.c
```
|
I am having issues running any make command in a Cygwin bash terminal. The following is the error that is returned.
"'ygdrive' is not reconized as an internal or external command, operable program or batch file"
However I am able to properly run the make file using cmd.exe, any help would be appreciated.
Thanks Eri... |
Looks like you are referencing a path in some recipe with\cygdrive\<letter>\....bashinterprets a single backslash as an escape character and therefore ignores thecdirectly following it.
Solutions:
If you want theMakefileto be portable to Unix systems, just write forward slashes in paths like this/cygdrive/<letter>/.... |
What's the meaning of:
```
#include <stdio.h>
int main(){
double bmax = 31.4159265;
printf("%1.4e\n", bmax);
}
```
What is the meaning of%1.4e? I know%ffor double.
|
```
%e specifier is used to print value of float\double in exponential format.
```
So here%1.4ewill print 1 digit before the decimal point and 4 digits after the decimal point.
So ifbmax=12.242then the output will be1.2242e+01.
|
This question already has answers here:Why is unsigned integer overflow defined behavior but signed integer overflow isn't?(7 answers)Closed8 years ago.
When I assignivalue greater thanINT_MAXin this code -
```
#include <stdio.h>
#include <limits.h>
int main()
{
int i;
i=INT_MAX+3;
printf("%d \n",INT_MAX... |
Yes, signed integer overflow has undefined behavior in C.i > INT_MAXis never true for anyint i. How can you have anintgreater than the maximum possibleint?
|
I'm trying to build vp8 for android armv6 but with no luckI tried to set --target=armv6-android-gcc but i get Unrecognized toolchain 'armv6-android-gcc' errorbut --target=armv7-android-gcc works just fine.how should i do it ?
|
There is no ARM6 Android ABI in the NDK. ARM6 Android devices use the ARM5 ABI (which is the plain androideabi).
|
My main.c:
```
#include <stdlib.h>
#include <gtk/gtk.h>
int main(int argc, char **argv)
{
return EXIT_SUCCESS;
}
```
I use:
```
gcc `pkg-config --cflags --libs libgtk+-2.0` -o tresor main.c
```
but I get this error:
```
Package libgtk+-2.0 was not found in the pkg-config search path.
Perhaps you should add... |
Just need to adjust the package name to gtk+-2.0 :
```
gcc `pkg-config --cflags --libs gtk+-2.0` -o tresor main.c
```
|
I am having issues running any make command in a Cygwin bash terminal. The following is the error that is returned.
"'ygdrive' is not reconized as an internal or external command, operable program or batch file"
However I am able to properly run the make file using cmd.exe, any help would be appreciated.
Thanks Eri... |
Looks like you are referencing a path in some recipe with\cygdrive\<letter>\....bashinterprets a single backslash as an escape character and therefore ignores thecdirectly following it.
Solutions:
If you want theMakefileto be portable to Unix systems, just write forward slashes in paths like this/cygdrive/<letter>/.... |
When I create a StatusBar,CreateWindowEx()will ignore the X and Y coordinates that I specify and the StatusBar will be positioned at the bottom of the parent Window.
Is there a way to prevent this from happening?
Edit:
This is the code to create the StatusBar:
```
CreateWindowEx(0, STATUSCLASSNAME, "", WS_CHILD ... |
The status bar is hard-coded to appear at the bottom of its parent window, and this can't be changed. However what you can change is the parent window.
So to position the status bar in an arbitrary location, put it inside a child window. You can then position the child window as you want.
Just remember that any noti... |
I have a simple program that encrypts message usingCaesar Cipher.
The program works well, but I am unable to check whether the user is entering more than 1 argument. If he is, I need to break and prompt the user to enter the correct number of arguments which is1.
If you enter more than 1 argument in terminal, say./c... |
You should be checking ifargc != 2instead ofargc < 2.
Also, don't bother checkingargv[0], since that represents the name of the executable that was run.
|
Is it safe to use theargvpointer globally? Or is there a circumstance where it may become invalid?
i.e: Is this code safe?
```
char **largs;
void function_1()
{
printf("Argument 1: %s\r\n",largs[1]);
}
int main(int argc,char **argv)
{
largs = argv;
function_1();
return 1;
}
```
|
Yes, it is safe to useargvglobally; you can use it as you would use anychar**in your program. The C99 standard even specifies this:
The parametersargcandargvand the strings pointed to by theargvarray shall be modifiable by the program, and retain their last-stored values between program startup and program terminatio... |
Since theprintffunction returns an integer value every time it is used (the number of characters written on the screen), shouldn't it be compulsory to store this value in anintvariable every timeprintfis called?
Edit:
If a function is returning certain value, why doesn't C make it necessary to store the value at the... |
It can be, only if it is necessary.
If wedon't caredon't want the return value to be used. there is no use storing the same.
|
Given a process id, what is the best way to find the process's creation date-time using C/C++ ?
|
I'd suggest looking at thetopandpssource code (in particular,libtop.c).
Ithinkthe following call should be what you need:
```
int proc_pidbsdinfo(proc_t p, struct proc_bsdinfo *pbsd, int zombie);
```
From<sys/proc_info.h>:
```
struct proc_bsdinfo {
...
struct timeval pbi_start;
...
}
```
Unfortunately th... |
what is __dirstream, where can we find the definition
So, I'm trying to get the sizeof DIR from opendir, which is a typedef of __dirstream. I understand it's hidden at compile-time, is there a defined max size?
|
That__double-underscore in the name marks it as implementation-private. Nothing is defined about it except what the implementation documents.
is there a defined max size
Nope, sorry.
|
I'm fighting with eclipse and autotools project.
I'What I'm trying to find is a way to add includes dirs and new source files to project.
So far I modified in/src/makefileof my project:
DEFAULT_INCLUDESto add all includes directoriesMy_Project_CFLAGSto add used libs
The problem is that each time I have to reconfigu... |
If you are really using autotools, you should edit Makefile.am instead of Makefile.
|
This question already has answers here:What does the comma operator , do?(8 answers)Closed8 years ago.
```
#include<stdio.h>
int main()
{
int a=2;
if(a==3,4)
printf("hello");
return 0;
}
```
Warning: Condition is always true
Why is it always true??
|
The,doesn't work like you think it does.
What a,does is evaluate all the expressions that are separated by the,in order, then return the last.
So what your if statement is actually doing is checkinga==3which returns false, but it discards this result. Then it checksif(4), which returns true.
Essentially your code i... |
Just read somewhere that,
when large buffers are used they must be made global variables otherwise stack overflow occurs.
But i am unable to get why it would happen?
(This is for C language compilers Turbo C on windows).
|
Typically, the executable file header, and OS loader, place a lower limit on the maximum stack size than they do on the global/static data.
Your linker is responsible for assembling the executable header and may be instructed to set a greater, (or smaller), maximum stack size for the executable image, so you could in... |
```
class Myuser * MyClient_GetMyUser(AUser aUser);
```
This is the error for trying to declare that function with ffi.cdef:
```
Error: dllImport.lua:861: declaration specifier expected near 'class' at line 20
```
How is this possible? How would I go about declaring 'class' if I must do so within cdef?
|
classis a C++ keyword. It doesn't exist in C. LuaJIT expects C code, not C++ code in the FFI block.
As for how to work around this, it depends on what you're doing. Either you make that a Cstruct, or you find a different way to access it.
|
So I decided to experiment, completely out of randomness.
And I found this:
```
"Hello World"[1]
```
Actually working on a first view, resulting in'e'even though:
I haven't encounter this anywhere until happened to be in my codeSeems semantically controversial (or at least quite suspicious)Could not find any inform... |
This is semantically correct."Hello World"[1]is equivalent to*("Hello World" + 1). In this expression the string"Hello World"will be converted to pointer to its first element. Therefore,("Hello World" + 1)is the address of second element of string"Hello World".
|
Here is a code:
```
int i = 0;
pid_t pid;
puts("Hello, World!");
puts("");
pid = fork();
if (pid) {
i = 42;
}
printf("%p\n", &i);
printf("%d\n", i);
puts("");
```
And output
```
Hello, World!
0x7fffc2490278
42
0x7fffc2490278
0
```
Program print Hello, World! one time, so child process wasn't start from th... |
Adresses of variables are same. So they are same. But I change i's value in parent process which is executed first, it didn't change for child process. Why?
The addresses are in the scope of a process. They are virtual addresses. Address0x7fffc2490278in the parent process and0x7fffc2490278in the child process are dif... |
I found the following code oncodegolf.stackexchangeto print a code table for ASCII characters:
```
#include <stdio.h>
int main(){
char i;
for(i = 0; i < 256; i++){
printf("%3d 0x%2x: %c\n", i, i, i);
}
return 0;
}
```
Sincechars store single bytes in them, they are always< 256and the loop ne... |
-Wtype-limits(or-Wextra) should trigger this warning
|
Example:
```
a : ++i;
b : i++;
c : i += 1;
d : i = i + 1;
```
Assuming each of them abcd are called completely simultaneous, which one of them will be performed first ?
|
Using gcc 5.2 to compile this program:
```
#include<stdio.h>
int main()
{
int i = 0;
++i;
i++;
i += 1;
i = i + 1;
return 0;
}
```
It gives this ASM:
```
main:
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-4], 0
add DWORD PTR [rbp-4], 1 #++i
add DWORD PTR [rbp-4], 1 #i++
... |
Importing my projects from Visual Studio 2013 to 2015 and compiling them makes DLL size jump from about 80kb to 380kb. (I mainly compile C / C++ DLL's)
I have tried playing with the linker settings but no luck in getting the size down again, including the new incremental linking.
Does anyone know what causes this an... |
It was this one here: /OPT:REF
(Victors -s tip put me on that track, thanks)
I don't know why this gets messed up when upgrading to 2015.
|
How can you dynamically allocate memory using stack ( not heap )?
Do they need different functions thanmalloc(),calloc()? Which header file is used?
|
alloca(3)is the function you're looking for.
```
void test_alloca(int num)
{
int *myarray = alloca(num * sizeof(int));
// do not try to free(myarray) !
}
```
In C99 you can also declare avariable-length array:
```
void test_vla(int num)
{
int myarray[num];
}
```
These two code snippets are functionall... |
I'm fighting with eclipse and autotools project.
I'What I'm trying to find is a way to add includes dirs and new source files to project.
So far I modified in/src/makefileof my project:
DEFAULT_INCLUDESto add all includes directoriesMy_Project_CFLAGSto add used libs
The problem is that each time I have to reconfigu... |
If you are really using autotools, you should edit Makefile.am instead of Makefile.
|
This question already has answers here:What does the comma operator , do?(8 answers)Closed8 years ago.
```
#include<stdio.h>
int main()
{
int a=2;
if(a==3,4)
printf("hello");
return 0;
}
```
Warning: Condition is always true
Why is it always true??
|
The,doesn't work like you think it does.
What a,does is evaluate all the expressions that are separated by the,in order, then return the last.
So what your if statement is actually doing is checkinga==3which returns false, but it discards this result. Then it checksif(4), which returns true.
Essentially your code i... |
Just read somewhere that,
when large buffers are used they must be made global variables otherwise stack overflow occurs.
But i am unable to get why it would happen?
(This is for C language compilers Turbo C on windows).
|
Typically, the executable file header, and OS loader, place a lower limit on the maximum stack size than they do on the global/static data.
Your linker is responsible for assembling the executable header and may be instructed to set a greater, (or smaller), maximum stack size for the executable image, so you could in... |
I am developing akernel-mode driverfor Win7 and later. I want to sendcustom IP packetsin the driver (I want to specify all fields for IP layer). I found theWinsock Kernel (WSK)technique but it only said how to send and receive TCP and UDP packets. I know that in user-mode, there israw socketin WinSock API. So I wonder... |
WskSocketsupportTCP,UDPand "raw sockets" for custom IP paquets :https://msdn.microsoft.com/en-us/library/windows/hardware/ff571149%28v=vs.85%29.aspx
SocketType [in]The type of socket that is being created. The following socket types are supported:
SOCK_STREAM
Supports reliable connection-oriented byte stream co... |
```
#include <stdio.h>
#define R 10
#define C 20
int main()
{
int *p;
int *p1[R];
int *p2[R][C];
printf("%d %d %d", sizeof(*p),sizeof(*p1),sizeof(*p2));
getchar();
return 0;
}
```
Why is the output:4 8 160? Why does size ofp1becomes 8 and not 4?
|
Consider thetypes.
sizeof(*p)==>sizeof(int)sizeof(*p1)==>sizeof(int *)sizeof(*p2)==>sizeof((int [20]))
Note: Depending on your platform and compiler, you'll get different results.
Also, as we know,sizeofproduces a result of typesize_t, it's advised to use%zuformat specifier to print the result.
|
The below program redirects all my output to log file. I need to display all the output along with log file. How can this be achieved?
```
$ gcc test.c
$ ./a.out > log.txt
$
```
|
You could usetee:
```
$ ./a.out | tee log.txt
```
|
I am trying to print out each integer on a new line, given integers separated by whitespace from a user input. It stops printing after a specific number, lets say 84. For example
The user input is
```
20 -4 84 8
```
How could i use a while loop to print these out as
```
20
-4
84
```
i know about scanf("%d %d %d %... |
Push thescanfinto thewhilecondition. Something like
```
while (scanf("%d", &x) != EOF && x != 84)
print("%d\n", x);
```
|
I'm trying to convert X and Y screen coordinates to a float range of -1.0, to 1.0.
(-1,-1 being 0,0 and if the resolution was 640x480, 1,1 would be 640,480. 0,0 would be 320,240... the center.)
How would I approach this? I made several futile attempts, and I'm not exactly mathematically inclined.
|
Here is some C code
```
void convert(int X, int Y)
{
float newx = 2*(X-320.0f)/640.0f;
float newy = 2*(Y-240.0f)/480.0f;
printf("New x = %f, New y = %f", newx, newy);
}
```
EDIT: Added the f suffix to ensure we do not do integer math !
|
I use__attribute__((packed));to make items of astructbeing stored in memory after another as this is critical for some low-level development.As__attribute__((packed));is GCC specific I wonder if there is a similar solution that works on ALL ANSI/C89/C99/C11 compilers or at least some of them.
|
There is no standard approach to accomplish what__attribute__((packed))does. The typical solution is to use#ifdef's to handle different compilers. You can find a few solutions to this approach at thisSO postwhich also contains the details on the Visual C++ equivalent of__attribute__((packed)). Alternatively,GCC sup... |
```
#include <stdio.h>
#define R 10
#define C 20
int main()
{
int *p;
int *p1[R];
int *p2[R][C];
printf("%d %d %d", sizeof(*p),sizeof(*p1),sizeof(*p2));
getchar();
return 0;
}
```
Why is the output:4 8 160? Why does size ofp1becomes 8 and not 4?
|
Consider thetypes.
sizeof(*p)==>sizeof(int)sizeof(*p1)==>sizeof(int *)sizeof(*p2)==>sizeof((int [20]))
Note: Depending on your platform and compiler, you'll get different results.
Also, as we know,sizeofproduces a result of typesize_t, it's advised to use%zuformat specifier to print the result.
|
The below program redirects all my output to log file. I need to display all the output along with log file. How can this be achieved?
```
$ gcc test.c
$ ./a.out > log.txt
$
```
|
You could usetee:
```
$ ./a.out | tee log.txt
```
|
I am trying to print out each integer on a new line, given integers separated by whitespace from a user input. It stops printing after a specific number, lets say 84. For example
The user input is
```
20 -4 84 8
```
How could i use a while loop to print these out as
```
20
-4
84
```
i know about scanf("%d %d %d %... |
Push thescanfinto thewhilecondition. Something like
```
while (scanf("%d", &x) != EOF && x != 84)
print("%d\n", x);
```
|
I'm trying to convert X and Y screen coordinates to a float range of -1.0, to 1.0.
(-1,-1 being 0,0 and if the resolution was 640x480, 1,1 would be 640,480. 0,0 would be 320,240... the center.)
How would I approach this? I made several futile attempts, and I'm not exactly mathematically inclined.
|
Here is some C code
```
void convert(int X, int Y)
{
float newx = 2*(X-320.0f)/640.0f;
float newy = 2*(Y-240.0f)/480.0f;
printf("New x = %f, New y = %f", newx, newy);
}
```
EDIT: Added the f suffix to ensure we do not do integer math !
|
I use__attribute__((packed));to make items of astructbeing stored in memory after another as this is critical for some low-level development.As__attribute__((packed));is GCC specific I wonder if there is a similar solution that works on ALL ANSI/C89/C99/C11 compilers or at least some of them.
|
There is no standard approach to accomplish what__attribute__((packed))does. The typical solution is to use#ifdef's to handle different compilers. You can find a few solutions to this approach at thisSO postwhich also contains the details on the Visual C++ equivalent of__attribute__((packed)). Alternatively,GCC sup... |
Does the SQLite C/C++ API support a way to define a constant for usage in queries? Something like this:
```
SELECT user_defined_function(USER_DEFINED_CONSTANT)
```
whereUSER_DEFINED_CONSTANTevaluates to some specified value.
|
You can create a user-defined function that always returns the same value. Alternatively, since you're talking about the C API, you could consider using a variable or a constant at the C level to help create the text of your prepared statements (containing abona fideSQL literal).
As far as I know or can determine, h... |
Is it possible to develop applications for Roku inCorC++as the SDK is written inC? If yes, how? If no, then which languages other thanBrightscriptcan apps be developed in?
|
My understanding is yes, at least with games and the Marmalade SDKhttps://www.roku.com/developer. I actually just downloaded the SDK and have not looked at it in much detail yet, but as it seems, developing for Roku involves a mix of Brightscript, C++ and Java (Android). Hope that helps!
|
I have a source code that gives the error "expression must have pointer type"
It is legacy code and I do not have the whole code. The code on which the error comes is:
```
(void *)&arr[0]
```
I do not know the type ofarr.
On what conditions can this error occur?What type ofarrcould be causing this error?
I know t... |
This error occurs whenarrdoesn't have pointer or array type. Any type ofarrexcept an array or pointer type causes this error.
|
Actually, I had mistakenly typed the below statement but compiler allowed me to execute the statement without throwing any error. My code is,
```
unsigned i=3;
```
Why thegccallowed assigning value without giving data type? Is that the way whatgccwill work?
|
FromC11standard, chapter §6.7.2,Type specifiers, the list of type specifiers appear as,
...—int,signed, orsigned int—unsigned, orunsigned int...
and the "Semantics" says,
Each of the comma-separated multisets designates the same type,...
So, basically,unsignedandunsigned intrefers to the same type and can be consi... |
I just ran into a smallish issue when working with size_t values in some code.
First I wanted to use size_t because it's [guaranteed] to be the same size on most platforms, that way going from 32 to 64 bit shouldn't cause any issues.
Then I negated the size_t value and got a really big number, looking back I realize... |
If you want to have exactly the same number of bits on all platforms, simply use for instance int32_t as defined instdint.h
|
```
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int x,n;
float sum=0;
printf("Length and Value");
scanf("%d%d",&n,&x);
for(int i=1;i<=n;i++)
{
sum+=(pow(x,2*i+1) * pow(-1,i+1));
}
printf("%f",sum);
return 0;
... |
Yes, you're a bit wrong. In your code
```
printf("%f",sum);
```
sumis anintand using%fto print the value of anintisundefined behaviour.
The functionpow()returns adouble. You may want to change yoursumto typedouble.
If you don't mind using your own version, a better looking implementation, without usingpow()will be... |
Actually, I had mistakenly typed the below statement but compiler allowed me to execute the statement without throwing any error. My code is,
```
unsigned i=3;
```
Why thegccallowed assigning value without giving data type? Is that the way whatgccwill work?
|
FromC11standard, chapter §6.7.2,Type specifiers, the list of type specifiers appear as,
...—int,signed, orsigned int—unsigned, orunsigned int...
and the "Semantics" says,
Each of the comma-separated multisets designates the same type,...
So, basically,unsignedandunsigned intrefers to the same type and can be consi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.