question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
```
void callback(struct ev_loop *loop, ev_io *w, int events)
{
if (EV_READ == events) {
...
}
else if (EV_WRITE == events) {
...
}
else {
here recv event's number is 3
}
}
```
In libev source code 'ev.h', i had not been find macro to define number 0x03
```
EV_READ = 0x01, /* ev_io detected read will not block */
EV_WRITE = 0x02, /* ev_io detected write will not block */
```
|
It's a bit mask. 3 indicates both a readable and writable condition are available to process.
Try something like
```
if (events & EV_READ) { // something is readable
...
}
if (events & EV_WRITE) { // something is writable
...
}
```
|
I have an utf-8 file which I can process normally with widechar functions.
However now I need to convert and use them in multibyte form and I'm struggling to make it work.
```
printf("%s\n",setlocale(LC_CTYPE, "")); //English_United States.1252
_setmbcp(_MB_CP_LOCALE);
FILE *f = NULL;
f = _wfopen(L"data.txt", L"r,ccs=UTF-8");
wchar_t x[256];
fwscanf(f, L"%ls", x); //x = L"một"
char mb[256];
int l = wcstombs(mb, x, 256); //mb = "m?t"
```
What did I do wrong?
|
In your textfile you have the characterộ(note the point below the character) instead ofô.
The characterôexists incodepage 1252, but the characterộdoesn't, and thereforewcstombstransforms it into a?.
You will have the same problem if your UTF-8 encoded text file contains for example cyrillic or greek characters.
The only solution is not having characters that don't have a representation in codepage 1252.
|
I'm building a network kernel extension which requires the OpenSSL library by including a few headers in some of my project files.
The problem is that OpenSSL includesstdlib.h(among other headers) which all throw errors (File not found). Same happens if I includestdlib.hin a project file.
I guess that's due to the fact that they are not available in the kernel.
So, how do I include them? What am I missing?
Otherwise, how do I include CommonCrypto or any crypto library in the kernel?
Thank you!
|
OpenSSL and CommonCrypto are userspace libraries. They are not available in the kernel.
Some parts of CoreCrypto are available in the kernel under<libkern/crypto/…>and<corecrypto/…>. Generally speaking, however, this is limited to cryptographic primitives (AES, RSA, SHA, etc), not higher-level tools like X509 certificate parsing, key exchange algorithms, or TLS.
|
I want to initialize aconstvariable using anif-else.For example:
```
const int foo;
if (bar) {
foo = 1;
} else {
foo = 2;
}
```
In Java, this is legal code (usingfinalinstead ofconst). The reason is that in all possible outcomes, the variable is assigned once and never reassigned. In C, this is not legal code. What is the reason that it can't be legal code in C?
|
You can initialize thefoovariable conditionally by means of theternary operator:
const int foo = bar ? 1 : 2;
Note that, iffoois not an automatic variable, then the initializing expression must be abe to be evaluated at compile-time, otherwise it won't compile.
|
This question already has answers here:Octal representation inside a string in C(2 answers)Closed6 years ago.
```
#include<stdio.h>
#include<string.h>
int main() {
char a[100]="1234\0567"; //Answer: 6
int len=strlen(a);
printf("%d",len);
}
```
This code prints 6 as the answer. Shouldn't it print 4 since strlen returns the count until the null character is encountered?
However when a space is included between \0 and 5. It returns 4 as the answer
```
char a[100]="1234\0 567"; //Answer: 4
```
Am I missing something?
|
You first version has the octal number\056not the\0character
Edit:
in the similar situations use\000octal sequence instead:
```
/* from your example*/ char a[100]="1234\000567";
```
|
The structure's code that is giving me problems is
```
typedef struct gamer
{
char name[MAXNAME];
Cell token;
unsigned score;
} Gamer;
```
The enum is
```
typedef enum cell
{
BLANK, RED, CYAN
} Cell;
```
When I try to set the value of my structCellmember I use this code;
```
gamer1->Cell = RED;
```
however when compiling it gives me this error;
```
error: 'Gamer' has no member named 'Cell'". Thanks in advanced.
```
|
You should dogamer1->token = RED;
tokenis the member of the struct and notCell.
|
I useopenmpto parallel a specific region in my C code:
```
#pragma omp parallel private()
{
...
}
```
When I check the process (via Activity Monitor in Mac OS X), I notice the number of threads is not returned back to 1 after exiting the#pragmablock. Do I need to write something to return the process to be on a single thread after finishing?
|
Most OpenMP implementations make use of thread pools. Threads are not destroyed but rather put to sleep and awaken when there is a new parallel region where they are needed. This is done both for the sake of efficiency, e.g, that way the overhead of creating new parallel regions is reduced, and for conformity to the OpenMP specification regarding the lifetime and accessibility of thread-private variables.
|
Hello this particular function is definied as
```
void initBoard(Cell board[BOARD_HEIGHT][BOARD_WIDTH]);
```
and theCellenum code is;
```
typedef enum cell
{
BLANK, RED, CYAN
} Cell;
```
I was wondering how to interpret and then call this function, if I dissect the function to my best ability I know that;
voidmeans that it doesn't return a value,initBoardis the name of the function,Cellis a enum (I don't know what this does or what to change this to when calling the function) and thenboard[][]would be making a 2d array for the function to use. If any one would be willing to give me a hand on how to call this function it would be great, thanks :)
|
Declare the 2d array like:
```
Cell board[BOARD_HEIGHT][BOARD_WIDTH];
```
boardis a 2D array (BOARD_HEIGHTxBOARD_WIDTH) where each value is aCell(i.e. eitherBLANK,REDorCYAN).
To call yourinitBoard()function do:
```
initBoard(board);
```
|
The structure's code that is giving me problems is
```
typedef struct gamer
{
char name[MAXNAME];
Cell token;
unsigned score;
} Gamer;
```
The enum is
```
typedef enum cell
{
BLANK, RED, CYAN
} Cell;
```
When I try to set the value of my structCellmember I use this code;
```
gamer1->Cell = RED;
```
however when compiling it gives me this error;
```
error: 'Gamer' has no member named 'Cell'". Thanks in advanced.
```
|
You should dogamer1->token = RED;
tokenis the member of the struct and notCell.
|
I useopenmpto parallel a specific region in my C code:
```
#pragma omp parallel private()
{
...
}
```
When I check the process (via Activity Monitor in Mac OS X), I notice the number of threads is not returned back to 1 after exiting the#pragmablock. Do I need to write something to return the process to be on a single thread after finishing?
|
Most OpenMP implementations make use of thread pools. Threads are not destroyed but rather put to sleep and awaken when there is a new parallel region where they are needed. This is done both for the sake of efficiency, e.g, that way the overhead of creating new parallel regions is reduced, and for conformity to the OpenMP specification regarding the lifetime and accessibility of thread-private variables.
|
Hello this particular function is definied as
```
void initBoard(Cell board[BOARD_HEIGHT][BOARD_WIDTH]);
```
and theCellenum code is;
```
typedef enum cell
{
BLANK, RED, CYAN
} Cell;
```
I was wondering how to interpret and then call this function, if I dissect the function to my best ability I know that;
voidmeans that it doesn't return a value,initBoardis the name of the function,Cellis a enum (I don't know what this does or what to change this to when calling the function) and thenboard[][]would be making a 2d array for the function to use. If any one would be willing to give me a hand on how to call this function it would be great, thanks :)
|
Declare the 2d array like:
```
Cell board[BOARD_HEIGHT][BOARD_WIDTH];
```
boardis a 2D array (BOARD_HEIGHTxBOARD_WIDTH) where each value is aCell(i.e. eitherBLANK,REDorCYAN).
To call yourinitBoard()function do:
```
initBoard(board);
```
|
I want my program to convert characters into integers, but not into their ASCII equivalents.
For example,'A'should equal 0, not 65, while'B'should equal 1.
Then I want to add that number to an ASCII character and convert that value back to achar.
|
```
char test = 'C';
int num = test - 'A';
// result: 2 with ASCII and any other encoding
// having the uppercase letters in sequence
```
|
what is the true path to prevent codeblocks error.
I know question very short but when I selected any path I am getting error
|
1-Create New console C project
2-Right Click your project and click properties in the context menu
3-go to the libraries page
4-click 'Avaliable in pkg-config' in the known libraries layout
5-and make it like the following picture
|
You can use getopt to parse arguments in c, with a string containing the flags, if they are mandatory or not, if they take an argument...
Is it possible to have an argument that doesn't require any flag, like so ?
./program -a arg1 arg2
Here arg2 doesn't need any flag, yet it would still be parsed. Is it possible to do so with getopt ?
|
Fromman 3 getopt:
extern int optind;If there are no more option characters,getopt()returns-1. Thenoptindis the index inargvof the firstargv-element that is not an option.
Ifoptindis less thanargc, read it, incrementoptind, and continue parsing.
|
Why does the following c code end up in an infinite loop?
```
for(unsigned char i = 0; i <= 0xff; i++){}
```
It is the same result with:
```
for(unsigned char i = 0; i <= 0xff; ++i){}
```
In which way do I have to modify the code, to get it working as expected (without usingintorunsigned intdatatype)?
|
If you really need to useunsigned charthen you can use
```
unsigned char i = 0;
do {
// ...
} while(++i);
```
When an arithmetic operation on anunsignedinteger breaks its limits, the behaviour is well defined. So this solution will process 256 values (for 8-bitunsigned char).
|
This question already has answers here:Why C++ compiler allows assigning 0 to pointers and no other number [duplicate](3 answers)Why are NULL pointers defined differently in C and C++?(3 answers)Closed6 years ago.
The following code compiles in C but not in C++:
```
int *ptr = 25; //why not in C++?
```
Error
```
prog.cpp: In function ‘int main()’:
prog.cpp:6:11: error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive]
int *ptr = 25;
```
But this compiles in both C and C++:
```
int *ptr = 0; //compiles in both
```
Why does assigning 0 work fine and other numbers does not work?
|
Because you can't implicitly convert frominttoint*in C++, however 0 can, due to historical reasons, since it is often used as the value ofNULL.
If you want to do it in C++, you need to explicitly cast the number to a pointer:
```
int *ptr = reinterpret_cast<int*>(25);
```
|
recently while I am running some of clang implementation over gcc spec benchmark, I have found that following in gcc spec source code:
```
int main PARAMS ((int argc, char **argv));
```
Any guess what actually means from c programming perspective? What could be the reason to use this?
|
It's for compatibility with ancient compilers that didn't support function prototypes.
Modern compilers accept:
```
int main (int argc, char **argv);
```
Ancient ones need:
```
int main ();
```
So to support both with a preprocessor that might not have variadic arguments yet, you can do:
```
#if __STDC__
/*all standard compliant compilers since the 1st version of the standard
must both define __STDC__ to a truthy value and support function prototypes*/
# define PARAMS(X) X
#else
# define PARAMS(X) ()
#endif
/*...*/
int main PARAMS ((int argc, char **argv));
```
|
```
uint16_t x[] = {1,2,4,8};
uint16_t *y = &x[1];
y+=2;
```
So the output is 8 and I wanted to know why? In my opinion this should equal to 4, because &x[1] should be 2 and adding 2 should equal 4. What am I missing?
|
Here's your array:
```
[0] [1] [2] [3]
+---+---+---+---+
x= | 1 | 2 | 4 | 8 |
+---+---+---+---+
```
y = &x[1]is a pointer tox[1], the second element:
```
[0] [1] [2] [3]
+---+---+---+---+
x= | 1 | 2 | 4 | 8 |
+---+---+---+---+
^
|
y
```
y += 2movesytwo steps to the right:
```
[0] [1] [2] [3]
+---+---+---+---+
x= | 1 | 2 | 4 | 8 |
+---+---+---+---+
^
|
y
```
and now*yis 8
|
Why does the following c code end up in an infinite loop?
```
for(unsigned char i = 0; i <= 0xff; i++){}
```
It is the same result with:
```
for(unsigned char i = 0; i <= 0xff; ++i){}
```
In which way do I have to modify the code, to get it working as expected (without usingintorunsigned intdatatype)?
|
If you really need to useunsigned charthen you can use
```
unsigned char i = 0;
do {
// ...
} while(++i);
```
When an arithmetic operation on anunsignedinteger breaks its limits, the behaviour is well defined. So this solution will process 256 values (for 8-bitunsigned char).
|
This question already has answers here:Why C++ compiler allows assigning 0 to pointers and no other number [duplicate](3 answers)Why are NULL pointers defined differently in C and C++?(3 answers)Closed6 years ago.
The following code compiles in C but not in C++:
```
int *ptr = 25; //why not in C++?
```
Error
```
prog.cpp: In function ‘int main()’:
prog.cpp:6:11: error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive]
int *ptr = 25;
```
But this compiles in both C and C++:
```
int *ptr = 0; //compiles in both
```
Why does assigning 0 work fine and other numbers does not work?
|
Because you can't implicitly convert frominttoint*in C++, however 0 can, due to historical reasons, since it is often used as the value ofNULL.
If you want to do it in C++, you need to explicitly cast the number to a pointer:
```
int *ptr = reinterpret_cast<int*>(25);
```
|
recently while I am running some of clang implementation over gcc spec benchmark, I have found that following in gcc spec source code:
```
int main PARAMS ((int argc, char **argv));
```
Any guess what actually means from c programming perspective? What could be the reason to use this?
|
It's for compatibility with ancient compilers that didn't support function prototypes.
Modern compilers accept:
```
int main (int argc, char **argv);
```
Ancient ones need:
```
int main ();
```
So to support both with a preprocessor that might not have variadic arguments yet, you can do:
```
#if __STDC__
/*all standard compliant compilers since the 1st version of the standard
must both define __STDC__ to a truthy value and support function prototypes*/
# define PARAMS(X) X
#else
# define PARAMS(X) ()
#endif
/*...*/
int main PARAMS ((int argc, char **argv));
```
|
```
uint16_t x[] = {1,2,4,8};
uint16_t *y = &x[1];
y+=2;
```
So the output is 8 and I wanted to know why? In my opinion this should equal to 4, because &x[1] should be 2 and adding 2 should equal 4. What am I missing?
|
Here's your array:
```
[0] [1] [2] [3]
+---+---+---+---+
x= | 1 | 2 | 4 | 8 |
+---+---+---+---+
```
y = &x[1]is a pointer tox[1], the second element:
```
[0] [1] [2] [3]
+---+---+---+---+
x= | 1 | 2 | 4 | 8 |
+---+---+---+---+
^
|
y
```
y += 2movesytwo steps to the right:
```
[0] [1] [2] [3]
+---+---+---+---+
x= | 1 | 2 | 4 | 8 |
+---+---+---+---+
^
|
y
```
and now*yis 8
|
The answer of simple recursion problem is easy to predict but when it involves multiple calls at a time then it gets difficult (here e(--n) is called two times
in single block of scope).
My problem is how to solve this kind of programs by creating TREE kind of structure
```
void e(int);
int main(void)
{
int a = 3;
e(a);
putchar('\n');
return 0;
}
void e(int n)
{
if (n > 0)
{
e(--n);
printf("%d ", n);
e(--n);
}
}
```
|
If you do it on a piece of paper with a pencil you should get this:
call => e(3);
call => e(2);call => e(1);call => e(0);initial printf: 0call => e(-1);initial printf: 1call => e(0);initial printf: 2call => e(1);call => e(0);initial printf: 0call => e(-1);
|
Linux has thebacktrace()function, which is a GNU extension.
FreeBSD also introduced thebacktrace()function since version 10.0, and NetBSD since version 7.0.
Is there any way to accomplish this on OpenBSD?
|
Not sure when it first appeared, but thereisa libexecinfo for OpenBSD 6.1 which implements thebacktrace()andbacktrace_symbols()functions:
```
{openbsd-amd64 ~}$ pkg_info libexecinfo
Information for inst:libexecinfo-0.3v0
Comment:
clone of backtrace facility found in the GNU libc
Description:
This is a quick-n-dirty BSD licensed clone of backtrace facility found
in the GNU libc, mainly intended for porting linuxish code to BSD
platforms, however it can be used at any platform which has a gcc
compiler.
Maintainer: The OpenBSD ports mailing-list <[email protected]>
WWW: https://github.com/conformal/backtrace/wiki
```
|
How to Link/Load DKM projects with Kernel Image(VIP) project so that i can call the Entry point function of DKM project(application) from Kernel Image project's "usrAppInit.c" to get the application started automatically at boot time?
Could some one please describe steps or point me to any documentation?
|
Add the DKM project as sub-project of your VIP. You can drag and drop, or open the VIP Project Properties, and from Project References check your DKM projectIn usrAppInit.c, call the entry point of your DKM. You will probably want to include the appropriate headerModify the VIP include paths as required to include the header file.If required, configure the kernel to use the correct build target for the DKM.
Using this approach, when you build the VIP, it will first build the child DKM projects (which will generate the .out files) then the VIP, generating a vxworks image that includes the .out files
|
This question already has answers here:Why cast an unused function parameter value to void?(2 answers)Closed6 years ago.
i was working on Iotivity framework, while tracing i was not able to know the use of these statements.
iotivity-1.3.0/resource/csdk/stack/src/ocstack.c
i'm curious to know the usage...
```
OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode)
{
(void) ipAddr;
(void) port;
return OCInit1(mode, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS);
}
```
|
In the code
```
(void) ipAddr;
(void) port;
```
is a way to silence compiler warning about "unused" variables.
It comes handy when the APIs has to follow a certain pattern to accept a number of parameters to conform to some standard, but actually, in the code you do not use the variables anyway.
|
How can I setup thePyArg_ParseTuplefunction with more than one argument?
|
This is an example:
```
const char *field = 0; PyObject *value; int typeField; size_t size = 0;
if (!PyArg_ParseTuple(args, "isO|n", &typeField, &field, &value, &size)) {
return 0;
}
```
The characters in the 2ndargument have to correspond to the C types of the passed pointers, of course.
Btw. thesizeis an optional parameter.
A complete doc. aboutPyArg_ParseTuple()can be found in the Python doc.
Parsing arguments and building values.
|
Here is the c code:
```
#include<stdio.h>
int main()
{
int a[]={0,1,2,3,4};
int*p[]={a,a+1,a+2,a+3,a+4};
int**ptr=p;
ptr++;
printf("%d , %d ",*ptr-a , **ptr);
*ptr++;
printf("\n%d , %d ",*ptr-a , **ptr);
*++ptr;
printf("\n%d , %d ",*ptr-a , **ptr);
++*ptr;
printf("\n%d , %d ", *ptr-a , **ptr);
return 0;
}
```
I am unable to understand the error and what should be amended in the code.
|
You have not yet executed line 8 in gdb.
```
8 int **ptr = p;
```
So till nowptris not defined yet in your program. Hence, can not access it. You can pressncommand in gdb prompt and then follow byprint
```
(gdb) n
(gdb) print *ptr
```
Also, your program should have%ldinstead of%dinprintfas format specifier to silence compiler warning as in
```
printf("%ld , %ld ",*ptr-a , **ptr);
```
|
I'm reading Apache httpd source code, I would like to know when a request come, which function get called first, followed by which function, and so on, is there some easy way to do so?
Something like
```
Waiting client connection... # a client send a HTTP request
client.c:accept_request() is called
client.c:handle_request() is called
asdf.c:func1() is called
fdsa.c:func2() is called
response.c:send_response() is called
Waiting client connection...
```
|
Put aprintfstatement at the beginning of each function
```
printf("Called function: %s\n", __func__);
```
This will print the name of the function when that function is called and this way you will able to know the function call sequence.
|
My function needs a reference as input:
```
test = foo(&xyz)
```
Is it possible to pass a fixed value? Of course
```
test = foo(1.23)
```
does not work. I could define a new variable to pass but is this really necessary?
Thanks
Philipp
|
You can't take the address of a constant, such as1.23in C. But, you can use a compound literal to create an unnamed object, and take its addressas suggested by @BLUEPIXY:
```
test = foo(&(double){ 1.23 });
```
It is unclear why you might want to do this, though, since usually when a pointer is passed into a function, the idea is that the object will be modified and used again after modification. Without an identifier, there would be no way to access the object created by the compound literal afterfoo()has returned.
|
it's simple code.
it shouldn't print a:(null).
it should be a:Mon Jul 31 14:33:39 2017
why print a:(null) ?
```
#include "stdafx.h"
#include <time.h>
#include <stdlib.h>
#include <windows.h>
int main()
{
time_t currentTime;
char c_time_string[26];
currentTime = time(NULL);
if (currentTime == (time_t)-1 )
{
(void)fprintf(stderr, "Failure to obtain the current time. \n");
exit(EXIT_FAILURE);
}
ctime_s(c_time_string, 26, ¤tTime);
if ( c_time_string == NULL)
{
(void)fprintf(stderr, "Failure to obtain the current time. \n");
exit(EXIT_FAILURE);
}
(void)printf("a: %d \n a:%s \n", currentTime, c_time_string);
(void)printf("b: %s", c_time_string);
getchar();
}
```
|
i solved this problem. see comments. there is answer
|
I'm trying to understand this code:
```
char * pl[] = {"test.sh", NULL};
execv("./test.sh", pl);
```
This will execute my script from a c program, but this will not:
```
execv("./test.sh", ["test.sh", NULL]);
```
This delivers an error message:
error: expected expression before '[' token
This doesn't work either:
```
execv("./test.sh", (char *) ["test.sh", NULL]);
```
Same exact error...
What is going on here?
I am obviously misunderstanding thechar * []declaration type. Should I be able to cast the array? Can i get this into one line of code?
I am not understanding the {}, how would I pass this bit to a function which is the end goal of this code snippet?
|
You can use a compound literal:
```
execv("./test.sh", (char*[]){"test.sh", NULL});
```
This is for C99 and later only.
|
Here is the c code:
```
#include<stdio.h>
int main()
{
int a[]={0,1,2,3,4};
int*p[]={a,a+1,a+2,a+3,a+4};
int**ptr=p;
ptr++;
printf("%d , %d ",*ptr-a , **ptr);
*ptr++;
printf("\n%d , %d ",*ptr-a , **ptr);
*++ptr;
printf("\n%d , %d ",*ptr-a , **ptr);
++*ptr;
printf("\n%d , %d ", *ptr-a , **ptr);
return 0;
}
```
I am unable to understand the error and what should be amended in the code.
|
You have not yet executed line 8 in gdb.
```
8 int **ptr = p;
```
So till nowptris not defined yet in your program. Hence, can not access it. You can pressncommand in gdb prompt and then follow byprint
```
(gdb) n
(gdb) print *ptr
```
Also, your program should have%ldinstead of%dinprintfas format specifier to silence compiler warning as in
```
printf("%ld , %ld ",*ptr-a , **ptr);
```
|
I have the following OpenSSL code:
```
BIO* out = BIO_new(BIO_s_file()); // BIO_new_fp(stdout, BIO_NOCLOSE);
if (out == NULL) {
CNGerr(CNG_F_CNG_CTRL, CNG_R_FILE_OPEN_ERROR);
return 0;
}
BIO_set_fp(out, stdout, BIO_NOCLOSE); // Program exits with code 0x1 here
```
On the lineBIO_set_fp(out, stdout, BIO_NOCLOSE);the program exists with error 0x1.
I am using Visual Studio 2015 on Windows 10.
|
I solved it by changing the flag in:
Properties > C/C++ > Code Generation > Runtime Library: Multi-threaded DLL /MD
|
This question already has answers here:Are negative array indexes allowed in C?(9 answers)Closed6 years ago.
I understand working of *(p+i), but, what actually is happening at memory level when retrieving values with *(p-i) or p[-i] through printf() function ?
```
#include <stdio.h>
int main() {
int i, arr[5] = {1, 2, 3, 4, 5}, *p;
p = &arr[4];
for (i = 0; i < 5; i++)
printf("%d\t%d\t", *(p - i), p[-i]);
// why does this prints in reverse order?
return 0;
}
```
|
It's simple,*(p - i)andp[-i]are exactly the same with different syntax. It's interesting that you can also write,-i[p]with exactly the same meaning*(p - i).
It prints in the reverse order because you start atarr[4]and then subtractifrom the pointer, which subtracts0,1,2one by one until it reaches4, so it printsp[4],p[3],p[2],p[1],p[0]which is the arrayarrfrom the last element to the first.
|
This question already has answers here:Are negative array indexes allowed in C?(9 answers)Closed6 years ago.
I understand working of *(p+i), but, what actually is happening at memory level when retrieving values with *(p-i) or p[-i] through printf() function ?
```
#include <stdio.h>
int main() {
int i, arr[5] = {1, 2, 3, 4, 5}, *p;
p = &arr[4];
for (i = 0; i < 5; i++)
printf("%d\t%d\t", *(p - i), p[-i]);
// why does this prints in reverse order?
return 0;
}
```
|
It's simple,*(p - i)andp[-i]are exactly the same with different syntax. It's interesting that you can also write,-i[p]with exactly the same meaning*(p - i).
It prints in the reverse order because you start atarr[4]and then subtractifrom the pointer, which subtracts0,1,2one by one until it reaches4, so it printsp[4],p[3],p[2],p[1],p[0]which is the arrayarrfrom the last element to the first.
|
Self studying coding (noob here), the answer to a practice problem is as follows:
amount = (int) round (c);
Wherecis a float.
Is it safe to say that this line converts the float to an integer through rounding?
I tried researching methods of converting floats to integers but none used the syntax as above.
|
You should look at the return value ofround.If it returns a float, then yourintcasting will not lose precision and will convert the float to anint.If it returns anint, then the conversion happens in the function, and there is no need to try converting it again.
This is of course if you really wish to round the number. If you want10.8to become11, then your code is a possible solution, but if you want it to become10, then just convert (cast) it to anint.
|
Like we do with macros:
```
#undef SOMEMACRO
```
Can we alsoundeclareordeletethe variables in C, so that we can save a lot of memory?
I know aboutmalloc()andfree(), but I want to delete the variables completely so that if I useprintf("%d", a);I should get error
```
test.c:4:14: error: ‘a’ undeclared (first use in this function)
```
|
No, but you can create small minimum scopes to achieve this since all scope local variables are destroyed when the scope is exit. Something like this:
```
void foo() {
// some codes
// ...
{ // create an extra minimum scope where a is needed
int a;
}
// a doesn't exist here
}
```
|
I had a while loop looking like:
```
while (str[i] != *p)
++i;
```
and a friend popped over and mentioned that it would be faster to do:
```
char c = *p;
while (str[i] != c)
++i;
```
I guess the question is:
if I dereference a pointer multiple times, at what point does it become faster to create a temp variable.
|
If*pis notvolatilequalified, the compiler is allowed to load the*ponly once and do what your friend is proposing.
So in "normal" code you should prefer readability and maintainability and let the compiler do its job. If in doubt, you can look at the assembler that the compiler produces, usually with option-S.
|
I need convert unsigned char array into unit8_t array maybe someone has an idea how to do it?
I tried to look for information on the Internet, but unfortunately I did not succeed.
:)
|
So, have you trieduint8_t* myuint8array = (uint8_t*)myuchararray;?
|
I'm trying to write a function in C that takes a pointer to an array and returns that pointer with all the values multiplied by the multiple. I have:
```
int* returnNpledArray(int *a, int n){
int i = 0;
for(i = 0; i < SIZE; i++){
*a++ *= n;
}
return a;
}
```
but when I call it, which I do in the main this way:
```
int sample2[] = {-10,-8,-6,-4,-2,0,2,4,6,8};
returnNpledArray(sample2, 3);
int d = 0;
for (d = 0; d < SIZE; d++){
printf("%d\n", *sample2);
}
```
the entire array prints out as only the first value in it multiplied by n. I thought that because in the function, I say *a++ *= n; that I am both dereferencing the value at that spot in a AND incrementing the pointer. How can I get this to work?
|
Because you are stuck at one pointer i.e.sampleby doingprintf("%d\n", *sample2);, instead it should beprintf("%d\n", sample2[d]);
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed6 years ago.Improve this question
I have the following string.
```
str[]="10,2";
```
I want to assign '10' to:
```
int n;
```
and '2' to:
```
int k;
```
I tried using index, string copy and many more methods, but didn't work.
|
```
#include<stdio.h>
int main(void) {
int n,k;
char str[]="10,2";
if(sscanf(str,"%d,%d",&n,&k)==2)//it will return 2, if both parameter has been assigned
printf("%d %d\n",n,k);
return 0;
}
```
|
I am creating an apache module using eclipse c/c++ on eclipse but I am getting this errorType 'apr_pool_t' could not be resolved Eclipse C/C++I included/usr/include/apacheand/usr/libwhere is the structureapr_pool_t?
|
I solved by myself. It is as simple as include /usr/include/apr-1.0 in right click on my project properties->C/C++General->Paths & Symbols.
|
I know that#errordirective works at least withGCCandMSVC
```
#if !defined(__cplusplus)
#error C++ compiler required.
#endif
```
But is it crossplatform and crosscompiler in general? Is it a part of some standard maybe?
PS. Because even looking at examples given in GCC and MSVC manuals one sees differences. While it works both with quotes or not, it makes a sad feeling, that it might be somehow compiler dependent.
GCC example
```
#error "Won't work on ..." // quotes here
```
MSVC example
```
#error C++ compiler required. // no qutes
```
|
Yes it is. It's a standard preprocessor directive in C and C++.
References:http://en.cppreference.com/w/cpp/preprocessor/errorhttp://en.cppreference.com/w/c/preprocessor/error
|
I need convert unsigned char array into unit8_t array maybe someone has an idea how to do it?
I tried to look for information on the Internet, but unfortunately I did not succeed.
:)
|
So, have you trieduint8_t* myuint8array = (uint8_t*)myuchararray;?
|
I have the following snippet of code
```
#include <stdio.h>
int main()
{
int i1 = 0x18f;
char c1 = i1;
char c2 = 15;
unsigned short s1 = 0174670;
printf("1) %o\n", i1);
printf("2) %d\n", c1);
i1 = c1;
printf("3) %d\n", i1 & c2);
printf("4) %x\n", s1 ^= 0x5555);
}
```
with this output
```
1) 617
2) -113
3) 15
4) aced
```
Could someone explain why the second and fourth outputs come out to -113 and aced respectively. Thank you.
|
char c1 = i1;is undefined behaviour.i1is 399 which needs at least 2 bytes to be represented while char is 1 byte. The output you are having is just the truncation of 399 = 110001111 in binary to 1 byte: 10001111 = signed -133 but since it's UB it could be anything else just as well
The fourth is just the hex representation of the number
|
The compiler throws no warnings or errors for the following code. Is the meaning of the const qualifier being abused? Obviously I cannot reassign it later in the same loop iteration but it does seem to reassign it after each iteration.
Sample code:
```
for(int i = 0; i < 10; ++i)
{
const int constant = i;
}
```
|
You aren'tre-initializing it, you're justinitializingit in each loop iteration*. Formally there is a newintbeing created and destroyed in each loop iteration, although the compiler can do whatever it wants as long as it seems to behave that way.
* You can't really "re-initialize" things in C++, initialization only happens once in the lifetime of an object
|
Consider the following code:
```
close(channel_data->pty_master);
if (login_tty(channel_data->pty_slave) != 0) // new terminal session
{
exit(1); // fail
}
execl("/bin/sh", "sh", mode, command, NULL); // replace process image
exit(0);
```
According to the documentation ofexecl(), the current process image is being replaced and the call returns only on errors.
But why callexit()after a call toexecl()if the process image is replaced?
|
Exec calls may fail. A common epilogue would be:
```
perror("Some eror message");
_exit(127); /*or _exit(1); (127 is what shells return) */
```
You would usually run_exitrather thanexithere, in order to skipatexithooks andstdiobuffer flushes.
|
Code sample:
```
int main(int argc, char **argv)
{
switch(argc)
{
case 0:
argc = 5;
__attribute__((fallthrough));
case 1:
break;
}
}
```
Using gcc 6.3.0, with-std=c11only, this code gives a warning:
```
<source>: In function 'main':
7 : <source>:7:3: warning: empty declaration
__attribute__((fallthrough));
^~~~~~~~~~~~~
```
What is the correct way to use this without eliciting a warning?
|
As previously answered,__attribute__ ((fallthrough))was introduced inGCC 7.
To maintain backward compatibility and clear thefall throughwarning for both Clang and GCC, you can use the/* fall through */marker comment.
Applied to your code sample:
```
int main(int argc, char **argv)
{
switch(argc)
{
case 0:
argc = 5;
/* fall through */
case 1:
break;
}
return 0;
}
```
|
There is an error.
Is it wrong to assign a value to a[i] in the following code?
Or something is wrong with conditional operators?
```
#include<stdio.h>
#include<string.h>
int main(){
char a[12]="sumit tyagi";
int i=0;
while(a[i]!='\0'){
a[i]>90 ? a[i]=a[i]-32 : a[i]=a[i]+32; //error in this line
i++;
}
printf("\n %s",a);
```
|
a[i]>90 ? a[i]=a[i]-32 : a[i]=a[i]+32;
isnotevaluated as
a[i]>90 ? (a[i]=a[i]-32) : (a[i]=a[i]+32);
since=has lower precedence than?:. In standard C you can't write it as above although some compilers allow it as an extension.
You could write it as the more readable (and portable)
```
a[i] += a[i] > 90 ? -32 : +32;
```
|
Consider the following code:
```
close(channel_data->pty_master);
if (login_tty(channel_data->pty_slave) != 0) // new terminal session
{
exit(1); // fail
}
execl("/bin/sh", "sh", mode, command, NULL); // replace process image
exit(0);
```
According to the documentation ofexecl(), the current process image is being replaced and the call returns only on errors.
But why callexit()after a call toexecl()if the process image is replaced?
|
Exec calls may fail. A common epilogue would be:
```
perror("Some eror message");
_exit(127); /*or _exit(1); (127 is what shells return) */
```
You would usually run_exitrather thanexithere, in order to skipatexithooks andstdiobuffer flushes.
|
Code sample:
```
int main(int argc, char **argv)
{
switch(argc)
{
case 0:
argc = 5;
__attribute__((fallthrough));
case 1:
break;
}
}
```
Using gcc 6.3.0, with-std=c11only, this code gives a warning:
```
<source>: In function 'main':
7 : <source>:7:3: warning: empty declaration
__attribute__((fallthrough));
^~~~~~~~~~~~~
```
What is the correct way to use this without eliciting a warning?
|
As previously answered,__attribute__ ((fallthrough))was introduced inGCC 7.
To maintain backward compatibility and clear thefall throughwarning for both Clang and GCC, you can use the/* fall through */marker comment.
Applied to your code sample:
```
int main(int argc, char **argv)
{
switch(argc)
{
case 0:
argc = 5;
/* fall through */
case 1:
break;
}
return 0;
}
```
|
There is an error.
Is it wrong to assign a value to a[i] in the following code?
Or something is wrong with conditional operators?
```
#include<stdio.h>
#include<string.h>
int main(){
char a[12]="sumit tyagi";
int i=0;
while(a[i]!='\0'){
a[i]>90 ? a[i]=a[i]-32 : a[i]=a[i]+32; //error in this line
i++;
}
printf("\n %s",a);
```
|
a[i]>90 ? a[i]=a[i]-32 : a[i]=a[i]+32;
isnotevaluated as
a[i]>90 ? (a[i]=a[i]-32) : (a[i]=a[i]+32);
since=has lower precedence than?:. In standard C you can't write it as above although some compilers allow it as an extension.
You could write it as the more readable (and portable)
```
a[i] += a[i] > 90 ? -32 : +32;
```
|
Given a standard Mac address "xx:xx:xx:xx:xx:xx" what format does it need to be in to be sent using libpcap's packet inject?
I load it into the ethernet frame where srcMac is just a char:
```
memcpy(ðernet.ether_src, srcMac, sizeof(ethernet.ether_src));
```
But in wireshark the address is incorrect. The visible Mac address in wireshark changes depending on what the string is so it's not being overwritten by the default address or anything.
|
I suppose, that in your codeethernet.ether_srchas typestruct ether_addrso it is not just achar*-string.
So you need to convert ASCII string to Ethernet address, e.g. with function declared as
```
extern struct ether_addr *ether_aton (__const char *__asc) __THROW;
```
|
Just starting in C, and learning the basics.
I have created a simple program that when compiled, would expected to compile as a.out however gcc is compiling as a.exe.
|
GCC on Windows defaults to creating an file nameda.exeon Windows, because the.exeextension is important - a file namea.outwould not recognized as an executable program on Windows. The default output could be nameda.out.exebut it would be different froma.outanyway, so it is just as sensible to produce a file nameda.exeinstead.
a.exeis less keypresses, too.
|
I have the following union structure:
```
typedef union Message
{
struct
{
unsigned short header: 16;
unsigned short header2: 16;
unsigned int timestamp: 32;
unsigned int payload: 32;
} pieces;
unsigned short whole[6];
}Message;
```
If I declare this way it works
```
Message msg = {.whole={255,255,255,0,255,0}};
```
I am just wondering there is any solution to declare union by an exsisting array? Like this:
```
unsigned short arr[] = {255,255,255,0,255,0};
Message msg = {.whole=arr};
```
|
No, that is not possible. Using the name of an array has it "decay" to a pointer to the first element in almost all contexts.
BTW, this has nothing to do with the fact that your array is hidden inside aunion. Arrays can't be assigned to and the only way to initialize them is by using an initializer as you did.
You could just usememcpyto copy the contents, though.
|
My C program can run more than 3 hours. For the sake of my experiment, I want to calculate the duration time (i.e., execution time) taken by the program until it finishes. I usestart = clock();at the beginning ofmain(), at the end I doend = clock(), finally subtractend - startthe get the execution time. However, as it is saidhere,clock_t clock(void)is limited to 72 minutes. How can I enforce it to count the whole execution time not only 72 minutes?
|
Thetime()function is specified in C89, C99, C11. It has second resolution and usually spans more than 30-bits worth of seconds. It's likely the most portable solution. In fact, I'd never heard ofclock()until today. Counting ticks is rarely what you want even if you need high resolution.
If you don't need a portable way to measure CPU/execution time, useprocfs.proc/self/stat'sstimefield andsysconf(_SC_CLK_TCK)should be all you need.
|
I am trying to write a code in C that will print at a given range (0 - 100).
x would only print from 0 to 3, and then 8 to 11, and then 16 to 19 and so on.
y would only print the rest, for example from 4 to 7, and then 12 to 15, and then 20 to 23 and so on.
The output should look like this:
```
x = 0 1 2 3 8 9 10 11 ... 92 93 94 95
y = 4 5 6 7 12 13 14 15 ... 96 97 98 99
```
|
Using%won't get you far...k = i % divisor;will make surekis somewhere between [0,4] (sincedivisor = 4) which is not what you want.
What about using 2 loops?
```
int main(){
int i,j;
for(i = 0; i < 100; i+=8){ // increment by 8 to make 0 -> 8 -> 16 jumps
for(j = 0; j < 4; j++){ // print 4 values for x and y, starting from the initial value i, and i+4
printf("x = %d\ty = %d\n", i+j, i+j+4);
}
}
return 0;
}
```
|
I'm not familiar with C and I'm trying to translate a piece of code I found to another language. For the most part, it's been rather intuitive but now i encountered a bit of code in which a subtraction operator is preceeded by a fullstop, like this:
```
double C;
C = 1.-exp(A/B)
```
I searched for it but all I can find about the dot operator is the standard property access of an object. I've encountered the '.-' operator in other langauges where it denoted element-wise operation on an array, but in my code none of the elements are arrays; all of A, B and C are doubles.
|
It instructs the compiler to treat that literal number as afloating-pointnumber.1. = 1.0
In your caseC = 1.-exp(A/B)is equivalent toC = 1.0 -exp(A/B)
|
For example, given a structure S:
```
typedef struct {
int a, b;
} S;
```
... and a method which takes a pointer toS, can I assign it the value of an aggregate initializer1all in one line? Here's my existing solution which uses a temporary:
```
void init_s(S* s) {
S temp = { 1, 2 };
*s = temp;
}
```
I'm using C11.
1For the very rare super-pedant who doesn't understand my question because somehow "aggregate initializer" wouldn't apply here because the LHS is not declaring a new object, I mean "aggregate-initializer-like syntax with the braces and stuff".
|
Yes, you can using thecompound literalssyntax:
```
#include <stdio.h>
typedef struct {
int a, b;
} S;
int main(void) {
S s;
S *p = &s;
*p = (S){1,2};
printf("%d %d\n", p->a, p->b);
return 0;
}
```
Demo
|
Can someone help me understand why this is giving me segmentation fault? The function is supposed to add n at the end of the list.
```
typedef struct lligada {
int valor;
struct lligada *prox;
} *LInt;
void appendL (LInt *l, int n){
LInt new=(LInt)malloc(sizeof(struct lligada));
while ((*l) && (*l)->prox) l=&((*l)->prox);
(*l)->prox=new;
new->valor=n;
new->prox=NULL;
}
```
|
If initially the head node is equal toNULLthen this statemenet
```
(*l)->prox=new;
```
gives you the segmentation fault.
A more correct function definition can look like
```
void appendL ( LInt *l, int n )
{
LInt new = (LInt)malloc(sizeof(struct lligada));
new->valor = n;
new->prox = NULL;
while ( *l != NULL ) l = &( *l )->prox;
*l = new;
}
```
|
I have to display the numbers in reverse order but i get an error program terminated to "Segmentation fault"(11).
My code:
```
#include<stdio.h>
void main()
{
int a,b[100],i;
printf("Enter the total numbers:\n");
scanf("%d",&a);
printf("Enter the numbers:\n");
for(i=0;i<a;i++)
{
scanf("%d",&b[i]);
}
for(i=a-1;i>=0;i++)
{
printf("%d\n",b[i]);
}
}
```
|
You need to replace i++ with i--
```
#include<stdio.h>
void main()
{
int a,b[100],i;
printf("Enter the total numbers:\n");
scanf("%d",&a);
printf("Enter the numbers:\n");
for(i=0;i<a;i++)
{
scanf("%d",&b[i]);
}
for(i=a-1;i>=0;i--)
{
printf("%d\n",b[i]);
}
}
```
|
I'm not familiar with C and I'm trying to translate a piece of code I found to another language. For the most part, it's been rather intuitive but now i encountered a bit of code in which a subtraction operator is preceeded by a fullstop, like this:
```
double C;
C = 1.-exp(A/B)
```
I searched for it but all I can find about the dot operator is the standard property access of an object. I've encountered the '.-' operator in other langauges where it denoted element-wise operation on an array, but in my code none of the elements are arrays; all of A, B and C are doubles.
|
It instructs the compiler to treat that literal number as afloating-pointnumber.1. = 1.0
In your caseC = 1.-exp(A/B)is equivalent toC = 1.0 -exp(A/B)
|
For example, given a structure S:
```
typedef struct {
int a, b;
} S;
```
... and a method which takes a pointer toS, can I assign it the value of an aggregate initializer1all in one line? Here's my existing solution which uses a temporary:
```
void init_s(S* s) {
S temp = { 1, 2 };
*s = temp;
}
```
I'm using C11.
1For the very rare super-pedant who doesn't understand my question because somehow "aggregate initializer" wouldn't apply here because the LHS is not declaring a new object, I mean "aggregate-initializer-like syntax with the braces and stuff".
|
Yes, you can using thecompound literalssyntax:
```
#include <stdio.h>
typedef struct {
int a, b;
} S;
int main(void) {
S s;
S *p = &s;
*p = (S){1,2};
printf("%d %d\n", p->a, p->b);
return 0;
}
```
Demo
|
a is a pointer to structure and b is the structure
```
a++ -> b
```
The order of evalution of above code will be
```
((a++) -> b)
```
or
```
(a -> b) ++
```
|
Aspostfix incrementand thepointer to member operatorhave exactly the sameprecedence, theassociativityof the two operators comes into play. Both are left to right.
Hence
```
a++ -> b
```
is evaluated as
```
(a++) -> b
```
This means that the->applies to the previous value of the pointera, andais incremented with the normal rules - to be accomplished sometime before the statement completes execution.
(One for the pub quiz, theprefix incrementhas a lower precedence than->).
|
I'm trying to compile android-kernel-goldfish-2-6-29 but when i use make -j2 to compile it, i get this error:
include/linux/compiler-gcc.h:86:30: fatal error: linux/compiler-gcc6.h: No
such file or directory
#include gcc_header(__GNUC__)
my ubuntu is 17.04 and i downgrade my gcc to
gcc version 4.7.4 (Ubuntu/Linaro 4.7.4-3ubuntu12)
can any body fix the problem?
|
I changed the goldfish version from 2.6.29 to 3.18 and now everything is okay.
|
Given this struct :
```
typedef struct test {
char field1[20];
char *field2;
} test_s
```
How can initialize this kind of structure with a designated initializer, knowing that I want field2 to point to field1 ?
```
test_s test = {.field1[0] = '\0', .field2 = .field1};
```
doesn't work.
|
In case of a single-item declaration you can use the name of the variable being declared, because the compiler can take address at any time during initialization:
```
test_s test = {.field1[0] = '\0', .field2 = test.field1};
```
Demo.
|
In the C language, what is the use of the equal sign twice in a statement? For example, in the following code statement —*arr += *(arr + n - 1) += 10;— there are two equal signs.
```
#include <stdio.h>
#define SIZE(arr) sizeof(arr) / sizeof(*arr);
void fun(int* arr, int n)
{
int i;
*arr += *(arr + n - 1) += 10;
}
void printArr(int* arr, int n)
{
int i;
for(i = 0; i < n; ++i)
printf("%d ", arr[i]);
}
int main()
{
int arr[] = {10, 20, 30};
int size = SIZE(arr);
fun(arr, size);
printArr(arr, size);
return 0;
}
```
|
It means, add 10 toarr[n-1], then add the newarr[n-1]value toarr[0].
|
The version of GNUTLS is 3.5. I want to use a child thread to handshake with remote peer.
In my child thread, I just usegnutls_handshake().
In the parent thread, can I usepthread_cancel()to cancel the child thread safety regardless of the current handshake state?If I have registered the pull/pull_timeout/push functions withpthread_cleanup_push/pthread_cleanup_pop,
can I cancel the child thread?
|
i have emailed Nikos Mavrogiannopoulos(current maintainers of gnutls) ,his answer as follow:
gnutls functions were never designed as pthread cancellation points. I
have not thought that much, but I believe your main concern is memory
leaks right? It may be that if you deallocate the session in another
thread it may just work; though you may have to create a stress test
for that to verify that this is possible.
|
Whenever I try to use a gem using Ruby's C API (with rb_require), I get a "cannot load such file --" error UNLESS i use the full path. Requiring gems work fine in regular ruby scripts. Is these something else I need to do? These gems are installed using Bundler.
|
When you callrb_requirefrom an extension you are calling the core “built-in” process for requiring files in Ruby. This bypasses the Gem handling code that is added by Rubygems when it replaces theKernel#requiremethod.
In order to get the proper gem handling you need to call the normalrequiremethod and let the usual method dispatch route the call to the Rubygems code. You can do that with:
```
rb_funcall(rb_cObject, rb_intern("require"), 1, rb_str_new_cstr("the_gem"));
```
You could callrb_internonce and store the result to avoid calling it multiple times if you wanted.
|
```
double* sol = (double*) calloc(n_samp, sizeof(double));
double** m = (double**) calloc(n_samp, sizeof(double*));
for (int i = 0; i < n_samp; i++){
*(m+i) = (double*) calloc((n_samp + 1), sizeof(double));
}
```
I am generating a 2D array using the above. It works fine but valgrind is telling me that there's a memory leak. What is the proper way to free the memories here?
|
To free the memory, you have to do the exact opposite of what you did when allocating the memory.
Start with the dynamic elements which you have created insid the loop:
```
for (int i = 0; i < n_samp; i++){
free( *(m+i) );
}
```
and then do the rest:
```
free( m );
free( sol );
```
|
As far as I know,#ifdefcan only check if a macro is defined, not what a macro is defined as.
```
#define MY_NUMBER 1
.
.
.
#ifdef MY_NUMBER
function();
#endif
```
I've tried something like this:
```
#define MY_NUMBER 1
.
.
.
#ifdef MY_NUMBER 1
function();
#endif
```
and the compiler issues the following:
```
warning: extra tokens at end of #ifdef directive
```
and the value of the macro is not taken into account (it's just ignored).
How do I check if a macro has a specific value?
|
Just like in conditional statements, you can use equality (==) or inequality (</>/<=/>=) in your preprocessor directives:
```
#if MY_NUMBER == 1
function1();
#elif MY_NUMBER == 2
function2();
#else
function3();
#endif
```
|
This question already has answers here:printf just before a delay doesn't work in C(5 answers)Closed6 years ago.
Why below function is not printing "Just kidding!".
```
void justCheck() {
printf("Just kidding!");
while (1) {
}
}
```
while this is printing "Justing Kidding!" followed by non stopping "Just Kidding inside loop!".
```
void justCheck() {
printf("Just kidding!\n");
while (1) {
printf("Justing Kidding inside loop!\n");
}
}
```
can anyone please explain the logic?
|
Your first example
```
printf("Just kidding!");
```
The output is buffered and therefore not displayed
In the second example
```
printf("Just kidding!\n");
```
The\nat the end will flush the buffer and therefore the string will be displayed.
In the first example before the while loop insertfflush(stdout);
|
I am looking for help in making this logic more legible. Assume each alphabet letter is a compare statement (e.g TRUE == a.foo). Each alphabet is about 30 char long statements.
```
if ( ((a || b)
&& (c || d)) ||
((e || f)
&& (g || h)) )
```
Any suggestions?
|
Decompose it.
```
int ab = a || b,
cd = c || d,
ef = e || f,
gh = g || h,
firstThing = ab && cd,
secondThing = ef && gh;
if (firstThing || secondThing)
```
|
Is it possible to get the memory size ( i.e., RAM) via C code? For instance, we can generate a directory usingsystem("mkdir -p /path/")wheremkdiris actually a unix command. Can I do something similar to get the memory size assuming I am on linux system?
Thank you
|
For Linux systems there issysinfo():
```
#include <sys/sysinfo.h>
#include <stdio.h>
int
main(int argc, char **argv)
{
struct sysinfo info;
sysinfo(&info);
// use info.totalram, info.freeram, etc
printf("%lu bytes\n", info.totalram);
return 0;
}
```
Check you man page onsysinfo(2)to know all the details of the struct.
|
Whenever I try to use a gem using Ruby's C API (with rb_require), I get a "cannot load such file --" error UNLESS i use the full path. Requiring gems work fine in regular ruby scripts. Is these something else I need to do? These gems are installed using Bundler.
|
When you callrb_requirefrom an extension you are calling the core “built-in” process for requiring files in Ruby. This bypasses the Gem handling code that is added by Rubygems when it replaces theKernel#requiremethod.
In order to get the proper gem handling you need to call the normalrequiremethod and let the usual method dispatch route the call to the Rubygems code. You can do that with:
```
rb_funcall(rb_cObject, rb_intern("require"), 1, rb_str_new_cstr("the_gem"));
```
You could callrb_internonce and store the result to avoid calling it multiple times if you wanted.
|
```
double* sol = (double*) calloc(n_samp, sizeof(double));
double** m = (double**) calloc(n_samp, sizeof(double*));
for (int i = 0; i < n_samp; i++){
*(m+i) = (double*) calloc((n_samp + 1), sizeof(double));
}
```
I am generating a 2D array using the above. It works fine but valgrind is telling me that there's a memory leak. What is the proper way to free the memories here?
|
To free the memory, you have to do the exact opposite of what you did when allocating the memory.
Start with the dynamic elements which you have created insid the loop:
```
for (int i = 0; i < n_samp; i++){
free( *(m+i) );
}
```
and then do the rest:
```
free( m );
free( sol );
```
|
As far as I know,#ifdefcan only check if a macro is defined, not what a macro is defined as.
```
#define MY_NUMBER 1
.
.
.
#ifdef MY_NUMBER
function();
#endif
```
I've tried something like this:
```
#define MY_NUMBER 1
.
.
.
#ifdef MY_NUMBER 1
function();
#endif
```
and the compiler issues the following:
```
warning: extra tokens at end of #ifdef directive
```
and the value of the macro is not taken into account (it's just ignored).
How do I check if a macro has a specific value?
|
Just like in conditional statements, you can use equality (==) or inequality (</>/<=/>=) in your preprocessor directives:
```
#if MY_NUMBER == 1
function1();
#elif MY_NUMBER == 2
function2();
#else
function3();
#endif
```
|
This question already has answers here:printf just before a delay doesn't work in C(5 answers)Closed6 years ago.
Why below function is not printing "Just kidding!".
```
void justCheck() {
printf("Just kidding!");
while (1) {
}
}
```
while this is printing "Justing Kidding!" followed by non stopping "Just Kidding inside loop!".
```
void justCheck() {
printf("Just kidding!\n");
while (1) {
printf("Justing Kidding inside loop!\n");
}
}
```
can anyone please explain the logic?
|
Your first example
```
printf("Just kidding!");
```
The output is buffered and therefore not displayed
In the second example
```
printf("Just kidding!\n");
```
The\nat the end will flush the buffer and therefore the string will be displayed.
In the first example before the while loop insertfflush(stdout);
|
I am looking for help in making this logic more legible. Assume each alphabet letter is a compare statement (e.g TRUE == a.foo). Each alphabet is about 30 char long statements.
```
if ( ((a || b)
&& (c || d)) ||
((e || f)
&& (g || h)) )
```
Any suggestions?
|
Decompose it.
```
int ab = a || b,
cd = c || d,
ef = e || f,
gh = g || h,
firstThing = ab && cd,
secondThing = ef && gh;
if (firstThing || secondThing)
```
|
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.Closed6 years ago.Improve this question
Why does theforloop in the code below not seem to run if I include the declaration of theunion test? I'm using the clang compiler.
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
union test{
int intv;
float floatv;
};
int main(){
union test test1; // When this is removed the below loop displays.
for(int i, j = 0; i < 5; i++, j = (j + i) * 2){
printf("%d %d\n", i, j);
}
return 0;
}
```
|
It's undefined behavior. You never initializedi.
|
Why does the snippet of code below produce an error?
```
int fun(auto int arg)
{
return 1;
}
```
If I use "register" in place of "auto", it works fine. Is there any reason behind this or is it just the way C standard is defined?
|
Allowingregisteris likely an historical artifact from the times when compilers were not sophisticated enough to optimize register allocations as well or better than humans. Back then it was desirable to tell the compiler that a particular parameter should be passed in one of CPU's registers, not through a stack frame.
No other storage class specifier could possibly make sense here: you cannot pass parameters asexternorstatic, whileautowould create confusion.
|
```
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(void)
{
_Bool = b1;
printf("1 = Wahr, 0 = Unwahr\n");
b1 = getchar ();
if(putchar(b1) = 1) {
printf("b1=1 =>wahr\n");
}
else {
printf("b1= =>unwahr\n");
}
return 0;
}
```
The error I get
```
10 16 C:\Netzwerk\owncloud\Visualisierung\TAG3\3.5 log. Datentyp\bool_leer.c [Error] lvalue required as left operand of assignment
```
|
```
int main(void)
{
_Bool b1 /* = 1 or 0 */;
printf("1 = Wahr, 0 = Unwahr\n");
b1 = getchar();
if (putchar(b1) == 1) {
printf("b1=1 =>wahr\n");
}
else {
printf("b1= =>unwahr\n");
}
return 0;
}
```
Two problems here:
change_Bool = b1with_Bool b1;changeif(putchar(b1) = 1)withif(putchar(b1) == 1)or withif(b1)as Bathsheba pointed out.
|
In pci device driver, I am trying to read PCI_COMMAND register using ioread32 in MIPS platform but Data bus error is thrown. I ve verified for valid parameter before passing into ioread32. Any help on this? Does using pci_bus_read_config_word in this case prevent Data bus error?
|
It depends on your platform on what kind of support it has for configuration space access. There two types of access -
1 -Legacy PCI configuration mechanism- This uses IO port address to access the endpoint configuration space. You can use ioread32() for this.2 -Enhanced PCI configuration mechanism- This uses memory mapped IO. You can use simple pointer operations to read from this.
Since its difficult to find out the access mechanism support, its better to use pci API's (which in this case is pci_bus_read_config_word) than use ioread32().
pci_*() API will take care of the access method valid for that platform.
|
The following piece of code does not compile in Eclipse:
```
typedef int Data;
typedef struct node* Node;
typedef struct node {
Data data;
Node next;
};
int main() {
Node n = newNode();
return 0;
}
Node newNode() {
Node newNod;
newNod = malloc(sizeof(struct node));
if(!newNod){
return NULL;
printf("\naa");
}
newNod->data = 3;
return newNod;
}
```
The one error displayed on compile time is
```
error: conflicting types for 'newNode'* (line with newNode() method declaration "Node newNode() {").
```
I'm clueless. What's wrong?
|
Move the definition ofnewNodeabovemain[or add a forward declaration ofnewNodeabovemain].
In your code, when the compiler sees the call tonewNodeinmain, it is using an implicit declaration. When the actual definition is encountered, it doesn't match that
|
I'm trying to get how memory allocation works, what happens with addresses and memory while changing types, etc.
I stacked with this string and can't understand what exactly is happening here:
```
(uint32_t)(((uint64_t)addr) >> 32)
```
There is no pointers so I have no guesses how memory allocation is changed here.
Could you explain me, please? Let's imagine that variable "addr" has type DWORD.
|
addris casted to uint64_t; its content shifted 32 bits to the right (with zeros pushed from the left) and the results is cast to uint32_t. It does not seems to make much sense a part of returning zero of type uint32_t in a complex way.
Besides, it has nothing to do with memory allocation, a part of possibly few temporaries on the stack.
|
Code:
```
printf( "%s", __builtin_return_address(0));
```
Warning :
format '%s' expects type 'char *', but argument 2 has type 'void
Side NotesI have been experimenting with some register keywords.. Perhaps the command above would have provided some info if it had worked.
|
According togcc.gnu.org, syntax of function:
```
void * __builtin_return_address (unsigned int level)
```
function return thevoid*. So, use%pformat specifier instead of%s.
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed6 years ago.Improve this question
I want to check if .elf file was built from specific code or from some other code
Is there any way to write something on C so that it can be identified by looking into binary elf file?
|
Well I suppose you could just insert a literal string into your code. If you don't actually use this string, the compiler might decide to remove it during optimization, so perhaps you could try something like this:
```
#include <stdio.h>
int main(int argc, char *argv[]) {
char *id_string = "MARKER";
if (argc < 0) { // (never true)
puts(id_string);
}
return 0;
}
```
|
I had written this c program for study purpose and I have found that
printf("%s",a);works butprintf("%s",*a);does not works.
I had definedalike thischar *a[]="how are you";
why*ais not pointing towards the string?
I am getting this error
```
test2.c: In function ‘main’:
test2.c:7:10: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
printf("%s \n",*a);
~^ ~~
%d
```
|
It isundefined behaviourbecause of%sprintf interprets*aas an address, but it's actually not an address and if you treat it as address it points to some location that is read protected for your program. So,may be you get segmentation fault.
|
Does GLib have a data type that can be used as a LIFO (stack) collection?It does havelists, queues, hash tables and such but I can't seem to find a stack data type.
There is a trash stack type but it was designed with a specific purpose in mind and it has also been deprecated since version 2.48.
What can be used as a stack in GLib?
|
Never used it, but from the documentation you should be able to use a double ended queue. To put onto stack useg_queue_push_head()and to pop from stack useg_queue_pop_head()see:https://people.gnome.org/~desrt/glib-docs/glib-Double-ended-Queues.html
|
I'm unable to understand below this line , could somebody tell me what it does ?
```
fscanf(file_pointer, "%*[^\n]");
```
|
From thedocsone might see, that:
*- assignment-suppressing character which is used not to assign the value being read to any receiveing argument offscanf.
[^\n]- conversion specifier which matches any symbol except (^) new line (\n).
As a result, thisfscanfreads all symbols until new line is met.
|
I was willing to know what doesputc()return. I was going through the following link:https://www.tutorialspoint.com/c_standard_library/c_function_putc.htm. Now ifputc()returnsEOFon error, then a natural question is what does it return on end of file? for that I wrote the following in dev c++:
Code
```
#include <stdio.h>
int main() {
char ch = EOF;
printf("%d\n", putc(ch, stdout));
printf("hello %d", EOF);
return 0;
}
```
Output
```
255
hello -1
```
This is a little bit weird. Can anyone help me out ?EOFis not an ASCII character as stated inWhat is the ascii value of EOF in c.?then why255(yes its not ASCII) in the first line and-1in second?
|
EOF is -1 as you already have probably already found out. So if youputc(EOF,stdout)then you see255in the output because -1 is converted tounsigned charbefore printing.
|
Below typedef use case really confuses me, can you give an explaination for each line?
```
typedef char *one;
one abc();
typedef one (*twft)();
twft abcde();
```
|
'one' is a typedef as char pointer
```
typedef char *one;
```
'abc' function declaration returning char pointer
```
one abc()
```
'twft' is typedef of a function pointer returning char pointer
```
typedef one (*twft)()
```
The last one is that function declaration of abcde() which returns a function pointer of a function defined by above typedef
```
twft abcde()
```
|
Can anyone explain how x^-1 is being executed in below code. I tried but no luck. I understood how x^1 is being executed.
```
#include <stdio.h>
int main(void)
{
int a=220, b=221, c=3;
printf("a^1= %d ,, a^-1= %d \n", a^1, a^-1);
printf("b^1= %d ,, b^-1= %d \n", b^1, b^-1);
printf("c^1= %d ,, c^-1= %d \n", c^1, c^-1);
return 0;
}
/* output: a^1= 221 ,, a^-1= -221
b^1= 220 ,, b^-1= -222
c^1= 2 ,, c^-1= -4 */
```
|
The^operator is theXORorexclusive-oroperator in C.
To make it simple, consider 8-bit signed values, using the typicaltwo's-complement encoding. Theinttype will work in the same way.
```
Decimal Binary
1 00000001
-1 11111111
-------- XOR
-2 11111110
```
Note that the unary operator-has higher precedence that the^bitwise operator.
|
I'm having some issues when using gdb on a raspberry pi 3
On raspbian it doesn't show libc function names.
If I define a function the disassembly showsbl my_func.
For libc functions -puts("test")- it shows something likebl 0x12345
I have the latest version of libc6-dbg installed.
Should I install other libraries? Am I doing something wrong?
As a side note, I've also tried ubuntu mate - gdb shows proper function names for libc functions, however it crashes with a segfault when running the binary; I found this thread regarding this issuehttps://bugs.launchpad.net/gdb/+bug/1576432
|
I am not sure, but I think address resolution for PLT stubs is just not implemented in upstream gdb/BFD. I found this discussion:
https://groups.google.com/forum/#!topic/android-ndk/LnweJJORhZI
And the patch has not been applied. Perhaps Ubuntu is carrying it as a private patch?
|
Percppreference.comthe length modifier %L is valid only for float types. But modern GNU compiler & library seems to accept it also for integers as synonym of %ll (long long). Is there a chance that cppreference mistakes on this? Or is %L for integers going to become standard in future?
|
From the latest C11 draftN1570, §7.21.6.1 section 7:
L-- Specifies that a followinga,A,e,E,f,F,g, orGconversion specifier
applies to along doubleargument.
So your source is correct,Las alength modifieris only defined forfloating pointconversions. I wouldn't expect this to change in future versions, as there's simply no need. Just uselandllas appropriate.
|
Can anyone explain how x^-1 is being executed in below code. I tried but no luck. I understood how x^1 is being executed.
```
#include <stdio.h>
int main(void)
{
int a=220, b=221, c=3;
printf("a^1= %d ,, a^-1= %d \n", a^1, a^-1);
printf("b^1= %d ,, b^-1= %d \n", b^1, b^-1);
printf("c^1= %d ,, c^-1= %d \n", c^1, c^-1);
return 0;
}
/* output: a^1= 221 ,, a^-1= -221
b^1= 220 ,, b^-1= -222
c^1= 2 ,, c^-1= -4 */
```
|
The^operator is theXORorexclusive-oroperator in C.
To make it simple, consider 8-bit signed values, using the typicaltwo's-complement encoding. Theinttype will work in the same way.
```
Decimal Binary
1 00000001
-1 11111111
-------- XOR
-2 11111110
```
Note that the unary operator-has higher precedence that the^bitwise operator.
|
I'm having some issues when using gdb on a raspberry pi 3
On raspbian it doesn't show libc function names.
If I define a function the disassembly showsbl my_func.
For libc functions -puts("test")- it shows something likebl 0x12345
I have the latest version of libc6-dbg installed.
Should I install other libraries? Am I doing something wrong?
As a side note, I've also tried ubuntu mate - gdb shows proper function names for libc functions, however it crashes with a segfault when running the binary; I found this thread regarding this issuehttps://bugs.launchpad.net/gdb/+bug/1576432
|
I am not sure, but I think address resolution for PLT stubs is just not implemented in upstream gdb/BFD. I found this discussion:
https://groups.google.com/forum/#!topic/android-ndk/LnweJJORhZI
And the patch has not been applied. Perhaps Ubuntu is carrying it as a private patch?
|
Percppreference.comthe length modifier %L is valid only for float types. But modern GNU compiler & library seems to accept it also for integers as synonym of %ll (long long). Is there a chance that cppreference mistakes on this? Or is %L for integers going to become standard in future?
|
From the latest C11 draftN1570, §7.21.6.1 section 7:
L-- Specifies that a followinga,A,e,E,f,F,g, orGconversion specifier
applies to along doubleargument.
So your source is correct,Las alength modifieris only defined forfloating pointconversions. I wouldn't expect this to change in future versions, as there's simply no need. Just uselandllas appropriate.
|
When I try to print all the values in the array(which should be zero?), it starts printing 0's but at the end prints wonky numbers:
"(printing zeros)...0,0,0,0,0,0,0,1810432,0,1809600,0,1809600,0,0,0,5,0,3907584..."
When I extend the array, only at the end do the numbers start to mess up. Is this a memory limitation or something? Very confused, would greatly appreciate if anyone could help a newbie out.
Done in CS50IDE, not sure if that changes anything
```
int main()
{
int counter [100000];
for(int i = 0; i < 100000; i++)
{
printf("%i,", counter[i]);
}
}
```
|
Your array isn't initialized. You simply declare it but never actually set it. In C (and C++, Objective-C) you need to manually set a starting value. Unlike Python, Java, JavaScript or C# this isn't done for you...
which should be zero?
The above assertion is incorrect.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.