question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I don't fully understand this, could someone help me evaluate the expression below? If message has**and length only has*, by using*()are we dereferencing to*messageandlength? Any help would be much appreciated.
```
bool func(char** message, size_t* length)
{
*(*message + *length) = '\0';
}
```
|
*(a + b)is another way of writinga[b]. The statement above is equivalent to
```
(*message)[*length] = '\0';
```
*messageis achar*string, and*lengthis a size. It sets the character at index*lengthto NUL.
There is no particular reason for the extra layer of pointers. It would be more normal to remove one*from each pa... |
My code creates an array of 3 strings and attemps to populate each string using getline(). It also prints every string it gets:
```
int i;
size_t n = 100;
char (*words[3])[100];
for ( i = 0; i < 3; i++)
{
getline(&words[i], &n, stdin);
printf("%s\n",words[i] );
}
```
When I enter the third string in the comm... |
You have to declarewordsas an array of pointer and initialize it toNULLaccording to theman page:
```
char *words[3] = {NULL};
```
http://ideone.com/GxV9qy
|
Could anyone point out what is wrong with this piece of code? I'm trying to write a simple(without using arrays and stuff like that) program that would convert the base 10 numbers to any other base. I'm a beginner, I've just started coding in C.
PS: As you can see I haven't written anything that would inverse the res... |
Change your while loop to a != 0. You want to loop until you have reduced the input number to zero. Your code is terminating when the first digit is 0.
|
Will the compiler make structure definition available in object file? Assume that I don't turn on flags like-g.
|
In general, no. C has no use for a structure definition once the code is compiled. The compiler will convert all the member references like this...
```
foo.x = 1;
```
...to assembly language that only knows thatxis a data item of a certain type at a certain offset from the beginning offoo. (Some hardware architectur... |
I'm working with linked lists. I'm having trouble accessing the data contained in a struct through a pointer. Here is my code:
```
void insertNode(Node **head, int num) {
Node *newNode = malloc(sizeof(Node));
newNode -> num = num;
while (head->next) { <-----problematic code
}
```
}
I've passed... |
Node **headis a pointer to a pointer to aNode. Sohead->is dereferencing a pointer to a pointer and therefore gives you a pointer. A pointer is not a struct or union, hence the error. You can use:
```
(*head)->
```
to dereference the underlying node.
|
thank you in advance for any help you may provide. I'm trying to print a board of the "+" symbols based on values given for M and N (so if it was M:3 and N:1 it would come out as +++) but I am drawing an absolute blank on how you do that. The code is in C.
Edit: To clarify. I don't remember what I need to do to print... |
to get you started
```
for(int i = 0; i < N; i++)
{
printf("X");
}
```
|
```
#include<stdio.h>
int main()
{
int a[2]={10,4};
int *k;
int *j;
j=a;
k=j;
printf("j=%d,k=%d\n\n",*j,*k);
*j++;
++*k;
printf("j=%d,k=%d",*j,*k);
return 0;
}
```
The output is:
j=10 k=10
j=4 k=11
I thought that it should have same result but this is not the case.
I wish... |
You need to dig out your operator precedence table.
*p++is evaluated as*(p++)
++*pis evaluated as++(*p)
The second one is due to the prefix++having the same precedence as pointer dereference*soassociativity(which is from right to left for those operators) comes into play.
For completeness' sake,*(p++)dereferences ... |
I started studying C a week ago and decided to write my owntic-tac-toegame for practise.
I have a game loop inmain:
```
for(int i = 1; player1.isWinner!=1 || player2.isWinner!=1 || noWinner!=1; i++){...}
```
Wherei- counts turns and condition of end of the game is one of players has won, or no one has won (draw).
... |
Is a value of 1 where someone won?
If so, then you would need check any of those conditions is true and loop if they are not:
```
!(player1.isWinner==1 || player2.isWinner==1 || noWinner==1)
```
Or using AND, check and loop when none are set:
```
(player1.isWinner!=1 && player2.isWinner!=1 && noWinner!=1)
```
|
I know that I can open multiple connections to an In-Memory sqlite database usingfile:DB_NAME?mode=memory&cache=sharedinsqlite3_open_v2().
I open 2 connections to an In-Memory database. One with the flagsSQLITE_OPEN_URI | SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITEand another withSQLITE_OPEN_READONLY | SQLITE_OPEN_URI... |
TheSQLITE_OPEN_READONLYflag affects how the database accesses any files and handles transactions.
Inshared-cache mode, multiple connections appear as a single connection in the interface to the file system. Therefore, they share the file access/transaction settings.
To prevent a connection from starting any write tr... |
This question already has answers here:Is it good practice to free a NULL pointer in C? [duplicate](4 answers)Closed6 years ago.
Ì used to make sure a pointer was not null before freeing it, so I would normally destroy dynamically created structs like this:
```
Node *destroy_node(Node *node) {
if (node) {
... |
Yes, passingNULL(a null-pointer constant) tofree()is perfectly valid.
QuotingC11, chapter §7.22.3.3, (emphasis mine)
Thefreefunction causes the space pointed to byptrto be deallocated, that is, made
available for further allocation.Ifptris a null pointer, no action occurs.[...]
|
In javascript we can do the following:
```
var obj = {alpha: [1, 2, 3], omega:[1, 2, 3]};
function test(field) {
return obj[field];
}
test("alpha");
```
Now im trying to achieve the same in c using a typedef struct in c:
```
typedef struct FooBar{
char alpha[50];
char beta[50];
} FooBar;
FooBar fooBar;
... |
You could do it with a macro:
```
#define getTest(t) sizeof(fooBar.t)
typedef struct FooBar {
char alpha[50];
char beta[50];
} FooBar;
FooBar fooBar;
int main()
{
int alphasize = getTest(alpha);
}
```
But I'm not sure if this fulfills your requirement.
|
I got a task to modify the content of a 2-dimensional arrayint[5][5], I was given the definitionint *a[5][5]and ordered to use aint**(the pointer of a pointer) to handle this task.
I'm now wondering the meaning of thisint *a[5][5], how can I understand the meaning of this and similar definitions?
|
int *a[5][5]is a 2D array ofpointers. A pointer-to-pointer can be used to point at any pointer item in this array.
A for how to understand the declaration, everything left of the variable name is the type of each item in the array, in this caseint*.
You could also usethis site. It works for many C declarations, but ... |
Could anyone point out what is wrong with this piece of code? I'm trying to write a simple(without using arrays and stuff like that) program that would convert the base 10 numbers to any other base. I'm a beginner, I've just started coding in C.
PS: As you can see I haven't written anything that would inverse the res... |
Change your while loop to a != 0. You want to loop until you have reduced the input number to zero. Your code is terminating when the first digit is 0.
|
Will the compiler make structure definition available in object file? Assume that I don't turn on flags like-g.
|
In general, no. C has no use for a structure definition once the code is compiled. The compiler will convert all the member references like this...
```
foo.x = 1;
```
...to assembly language that only knows thatxis a data item of a certain type at a certain offset from the beginning offoo. (Some hardware architectur... |
I'm working with linked lists. I'm having trouble accessing the data contained in a struct through a pointer. Here is my code:
```
void insertNode(Node **head, int num) {
Node *newNode = malloc(sizeof(Node));
newNode -> num = num;
while (head->next) { <-----problematic code
}
```
}
I've passed... |
Node **headis a pointer to a pointer to aNode. Sohead->is dereferencing a pointer to a pointer and therefore gives you a pointer. A pointer is not a struct or union, hence the error. You can use:
```
(*head)->
```
to dereference the underlying node.
|
thank you in advance for any help you may provide. I'm trying to print a board of the "+" symbols based on values given for M and N (so if it was M:3 and N:1 it would come out as +++) but I am drawing an absolute blank on how you do that. The code is in C.
Edit: To clarify. I don't remember what I need to do to print... |
to get you started
```
for(int i = 0; i < N; i++)
{
printf("X");
}
```
|
```
#include<stdio.h>
int main()
{
int a[2]={10,4};
int *k;
int *j;
j=a;
k=j;
printf("j=%d,k=%d\n\n",*j,*k);
*j++;
++*k;
printf("j=%d,k=%d",*j,*k);
return 0;
}
```
The output is:
j=10 k=10
j=4 k=11
I thought that it should have same result but this is not the case.
I wish... |
You need to dig out your operator precedence table.
*p++is evaluated as*(p++)
++*pis evaluated as++(*p)
The second one is due to the prefix++having the same precedence as pointer dereference*soassociativity(which is from right to left for those operators) comes into play.
For completeness' sake,*(p++)dereferences ... |
I have iput two double variable in c and I need if one of the input is string terminate with print message i try something like this
```
double a, b;
printf("Input two variables:\n");
scanf("%lf %lf", &a, &b);
printf("%lf\n", a);
printf("%lf\n", b);
if(( a <= 0.0 ) || (b <= 0.0))
{
printf("Bad input\n");
return 2... |
You try and useabefore validating whether the input is valid. This could lead to unexpected behavior. You need to validate your input, something like:
```
if (scanf("%lf %lf", &a, &b) != 2) {
// handle bad input
}
```
|
```
#include <stdio.h>
int multiple(int, int);
int main()
{
int i;
int x;
int y;
scanf("%d %d", &x, &y);
printf("%d", multiple(x,y));
}
int multiple(int N,int M)
{
int i;
int result;
for (i=0;i*M<N;i++)
{
result=i*M;
printf("%d", result);
}
}
```
When I put... |
The loop does print up to 98. However,multipleis declared to return anintbut doesn't actually have areturnstatement, so the return value is unspecified (and in practice you'll get some arbitrary value from a previous calculation). Then you print this "garbage" return value and in your case it happens to be 105.
If yo... |
I need to remove the first 3 characters from anarraywithout any libraries. How would I go about doing this? I know that I can usememmovebut I'm working on a system without the standard library, alsomemmoveis for pointers. WithmemmoveI can dothis:
```
void chopN(char *str, size_t n)
{
assert(n != 0 && str != 0);
... |
As long as you know the string is at least 3 characters long, you can simply usestr + 3.
|
please can you help me with my easy program? I am begginer and my english is not good, it hard to understand. :/
PROGRAM:
```
void tisk_pole (P);
int main()
{
char P1[3][3]={{'1','2','3'},{'4','5','6'},{'7','8','9'}};
tisk_pole(P1);
return 0;
}
void tisk_pole (P){
int i, j;
for (i = 0; i < 3; ... |
You're missing the type declaration of the argumentP.
```
void tisk_pole(char P[3][3]) {
int i, j;
for (i = 0; i < 3; i++){
for (j = 0; j < 3; j++)
printf("%c", P[i][j]);
putchar('\n');
}
}
```
SeeC Function with parameter without type indicator still works?for how compilers... |
I want to print the values of phrs to terminal and check their data type. I thought I got the first part:
```
mexPrintf("Value: %d\n",prhs[0]);
```
But that's giving me junk. What am I missing? (Probably something obvious) Is there a way to check data types and print them out?
|
To check prhs date type, i think you can usemxGetClassName(prhs[0]). To print its value, you need to dereference it again, as I remember correctly. For example:
```
double* data = mxGetPr(prhs[0]);
mexPrintf("Value: %f\n",data[0]);
```
Note, mxGetPr, returns pointer to double, so left it in this example.
|
I have a .au audio file and am reading it in parts using fread. However when i write this to /dev/audio there is no sound being played. Do I need to do something or is the system supposed to play back as soon as I write to /dev/audio. I am not getting any errors.
```
player = open("/dev/audio", O_WRONLY, 0);
if ... |
The issue seems to be with Ubuntu. I tried the same on a Gentoo installation in my lab and the sound can be heard
|
I am writing a function in nasm that will be called from 32bit ansi C.
The function prototype in C looks like this:long double scalar(int n, long double *x)Where x is a pointer to an array oflong doubles.
The problem occurs when I try to load a singlelong doubleto the FPU:
```
mov ecx, [esp+8] ; n
mov eax, [esp... |
To specify the size explicitely use the following form in NASM:
```
fld TWORD [eax] ; load 10 bytes from [eax]
```
As you pointed out, FPU stack registers are 80 bits wide. The C compiler chooses 12 bytes, because of the data alignment requirements of the stack frame.
|
Both Clang/LLVM and GCC show this warning. I am aware that headers must be included in order to use many functions, butstdio.his included at the top of the file. I've used other functions (e.g.,setbuf()) from the same header, and these work fine. Removing the header include causes errors and warnings to be thrown for ... |
Include thisbeforeincludingstdio.h:
```
#define _BSD_SOURCE
```
setlinebuf()is not a standard C function and thus it may not be included by default instdio.h.
But note that_BSD_SOURCEhas been deprecated since glibc 2.20 and been superseded by_DEFAULT_SOURCE.
|
So, I have this program, where I store the line number in a variable, using
```
int x = __LINE__;
```
The value of x can keep changing.
Is it possible to jump from an arbitrary line to the one given by x, using goto or any other keyword in C?
I'm looking for something like
```
'keyword' x;
```
where the program sh... |
The GCC compiler supports, as an extension,using labels as valuesso that you can work with them in a way that resembles what you're after.
It allows you to do:
```
void *ptr = &&label;
label:
```
and then
```
goto *ptr;
```
to jump tolabel.
This is typically useful inside the core of a virtual machine, and can o... |
I want to print the values of phrs to terminal and check their data type. I thought I got the first part:
```
mexPrintf("Value: %d\n",prhs[0]);
```
But that's giving me junk. What am I missing? (Probably something obvious) Is there a way to check data types and print them out?
|
To check prhs date type, i think you can usemxGetClassName(prhs[0]). To print its value, you need to dereference it again, as I remember correctly. For example:
```
double* data = mxGetPr(prhs[0]);
mexPrintf("Value: %f\n",data[0]);
```
Note, mxGetPr, returns pointer to double, so left it in this example.
|
First semester of CS.
When I change "%d" to "%f" the output is 10 times worse, not even showing the KPH row. Really not sure what I am doing wrong other than that.
This is a screenie of what happens as it is now.
Thanks for halpz I am n00b
```
#include<stdio.h>
float convertToMPH(float KPH);
float convertToKPH(fl... |
Change
```
printf("%d\t%d\n", i, convertToMPH(i));
```
to
```
printf("%d\t%f\n", i, convertToMPH(i));
```
|
I am reading the source code ofopen-iscsi. In this source files I see few functions start with prefix "__". Whats the reason behind naming a function with double underscore as prefix in general in C language?
Example: In the file usr/iscsi_sysfs.c, the function namestatic int __get_host_no_from_hwaddress(void *data, ... |
These are reserved identifiers. Using them guarentees no naming collisions with user's code (assuming the users follow the convention).
7.1.3 Reserved identifiers....All identifiers that begin with an underscore and either an uppercase letter or another
underscore are always reserved for any use.
Such names should... |
I'm trying to make a tic tac toe program, but I have run into a warning. I know that the code still compiles, but I want to know why I have this warning and what I can do to fix it.
I get the warning when p = a;
```
void clean(){
char a[N][N], *p;
p = a;
for(int i = 0; i < N; i++){
for(int j = 0... |
Yourcleanfunction should be this:
```
void clean(void){
char a[N][N];
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
a[i][j] = '_';
}
}
display(a);
}
```
There is absolutely no advantage of having theppointer, except that your code is less readable.
|
I am not sure how to phrase this. But I have a C Program that will call another C Program in unix. After the call, the program(foo-exe) will prompt for an input "Y/N". I would like to suppress(hide) this prompting message and enter 'Y' thereafter as input. How do I go about doing that?
```
#include <stdio.h>
int main... |
If that's all (Y or N) thefoo-exeexpects then you could redirect its stdin to read from a pipe.
```
system("echo Y | /home/xyz/foo-exe bar");
```
But be aware of thepitfallsofsystem()and its use is generally discouraged.
|
I thought using RegSaveKeyEx would help me to save a registry subkey as a .REG file, but it is not working. I have this code:
```
// Saving key
LONG saveKey = RegSaveKeyExW(keyResult, L"C:\\Demo1.reg", securityAttributes, Flags);
```
securityAttributesis set asNULL, andFlags, asREG_LATEST_FORMAT.
I don't have any ... |
There is no Registry API function that will output a key in.regformat. You will have to enumerate the key's content yourself and write out your own.regfile manually.
|
I am learning unit testing using Ceedling, with CMock for mocks, on an existing, embedded C code-base (which I can adjust to suit).
I have come across the situation where one function in a unit calls a second function within the same unit.
```
int foo_a(int r)
{
/* foo_a work */
/* do not wish to test this ... |
You can't do this without modifying your source code.
Consider breaking the functions out into two separate compilation units.
Or, add an#ifndef TESTaround the function you want to replace.
|
I am not sure how to phrase this. But I have a C Program that will call another C Program in unix. After the call, the program(foo-exe) will prompt for an input "Y/N". I would like to suppress(hide) this prompting message and enter 'Y' thereafter as input. How do I go about doing that?
```
#include <stdio.h>
int main... |
If that's all (Y or N) thefoo-exeexpects then you could redirect its stdin to read from a pipe.
```
system("echo Y | /home/xyz/foo-exe bar");
```
But be aware of thepitfallsofsystem()and its use is generally discouraged.
|
I thought using RegSaveKeyEx would help me to save a registry subkey as a .REG file, but it is not working. I have this code:
```
// Saving key
LONG saveKey = RegSaveKeyExW(keyResult, L"C:\\Demo1.reg", securityAttributes, Flags);
```
securityAttributesis set asNULL, andFlags, asREG_LATEST_FORMAT.
I don't have any ... |
There is no Registry API function that will output a key in.regformat. You will have to enumerate the key's content yourself and write out your own.regfile manually.
|
I am learning unit testing using Ceedling, with CMock for mocks, on an existing, embedded C code-base (which I can adjust to suit).
I have come across the situation where one function in a unit calls a second function within the same unit.
```
int foo_a(int r)
{
/* foo_a work */
/* do not wish to test this ... |
You can't do this without modifying your source code.
Consider breaking the functions out into two separate compilation units.
Or, add an#ifndef TESTaround the function you want to replace.
|
I am working on compiler design for 8051. I want to declare a memory of say 30 locations, each location is of 8bits. How do I declare that in C?
|
to declare 30 x 8 bits memory:
```
char memory[30];
```
to declare n x n memory:
```
char memory[30][30];
```
it declares 30 x 30 x 8bits memory.
|
I have a basic question, which is bugging me a lot and I am unable to figure out why a programmer uses it.
```
if (0 == Indx)
{
//do something
}
```
What does the above code do and how is it different from the one below.
```
if (Indx == 0)
{
// do something
}
```
I am trying to understand some source code... |
Some programmers prefer to use this:
```
if (0 == Indx)
```
because this line
```
if (Indx == 0)
```
can "easily" be coded by mistake like an assignment statement (instead of comparison)
```
if (Indx = 0) //assignment, not comparison.
```
And it is completely valid in C.
Indx = 0is an expression returning 0 (wh... |
Here's the sample structure.
```
main.c
|
--------------
|
dir0-"sum.h","sum.c"
```
sumandsubare just two simple functions, located indir0. They're called inmain.c.
I'm trying to compile using gccgcc -Idir0 main.c sum.c -o main.
But it throws an error t... |
The command should be:
```
gcc -Idir0 main.c dir0/sum.c -o main
```
Notice that sum.c is in a sub-directory and you have to tell the compiler that.
|
I have a basic question, which is bugging me a lot and I am unable to figure out why a programmer uses it.
```
if (0 == Indx)
{
//do something
}
```
What does the above code do and how is it different from the one below.
```
if (Indx == 0)
{
// do something
}
```
I am trying to understand some source code... |
Some programmers prefer to use this:
```
if (0 == Indx)
```
because this line
```
if (Indx == 0)
```
can "easily" be coded by mistake like an assignment statement (instead of comparison)
```
if (Indx = 0) //assignment, not comparison.
```
And it is completely valid in C.
Indx = 0is an expression returning 0 (wh... |
Here's the sample structure.
```
main.c
|
--------------
|
dir0-"sum.h","sum.c"
```
sumandsubare just two simple functions, located indir0. They're called inmain.c.
I'm trying to compile using gccgcc -Idir0 main.c sum.c -o main.
But it throws an error t... |
The command should be:
```
gcc -Idir0 main.c dir0/sum.c -o main
```
Notice that sum.c is in a sub-directory and you have to tell the compiler that.
|
I am writing two c files that one is to write(by stdout) and another is read(by stdin).
But the read code is always hangs with read(), I have tried fread function but useless.
Can someone give advice?
Write example:
```
int main() {
char *a_string="Hello";
write(fileno(stdout), a_string, strlen(a_string)+1... |
The read code is always hangs with read(), I have tried fread function but useless.
This is becausereadandfread, unlikefgetsand similar functions, do not quit reading when the user inputs a newline (pressesEnter). It waits until EOF is read or until the specified bytes have been read.
To send EOF toreadyou must pres... |
I was tracing a piece of code for a program works in embedded Linux and encountered this. I couldn't google out useful information to show me how it really works.
This piece of code is written like:
```
unsigned char foo(*someaddress){
unsigned long flags = 0; //why use a long?
flags = save_and_cli(); //what is this... |
IIRCsave_and_cliis an "ancient" version oflocal_irq_save
It saves the current state of local interrupt delivery and then disable it.
Functionlocal_irq_restoreis used to restore irq state saved bylocal_irq_save
Here for reference
|
How can I access piped parameter in c code?
test.c
```
int main( int argc, char *argv[] ) {
int i = 0;
for (i = 0; i < argc; i++) {
printf("argv[%d] = %s\n", i, argv[i]);
}
}
```
Bash:
```
cat file.txt | ./test
```
It prints just first argumentargv[0] = ./test. How can I access content of file.txt ... |
With the pipe, your program gets the content offile.txtin its stdin. So, read fromstdin. For example you can usefgets()to read line by line:
```
#include <stdio.h>
int main(int argc, char *argv[]) {
int i = 0;
char line[1024];
while(fgets(line, sizeof line, stdin)) {
printf("%s", line);
}
}
```
|
hi to all i have this problem i have a array of uint8_t
uint8_t command_Text[256]
i read some data from adc, i use snprintf for convert the data float in uint8_t
```
` float aux;
uint8_t value[4];
aux=(float)(HAL_ADC_GetValue(&hadc))
snprintf(value,4,"%.0f",aux); //convert the data float to uint8_t
strcat(co... |
Suggest something like:
```
uint8_t command_Text[256] = {'\0'};
....
uint8_t value[4] = {'\0'};
snprintf(value,3,"%3.3u", atoi( HAL_ADC_GetValue( &hadc ) ) );
strcat(command_Text, value); //append data
```
|
```
int sarl_n(int x, char n){
x <<= 2;
x >>= n;
return x;
```
}
When I assemble with "gcc -m32 -S sarl_n.c", it emits this code:
```
.cfi_startproc
movl 4(%esp), %eax
movsbl 8(%esp), %ecx
sall $2, %eax
sarl %cl, %eax #This is the part which I don't understand
ret
.cfi_endproc
```
Why is gcc ... |
The reason why the following line(previous version) in question
```
sarl %cl, 8(%ebp) #This is the part which I don't understand
```
or (current version)
```
sarl %cl, %eax #This is the part which I don't understand
```
is using the%cland not%ecxis, that theSARopcode only supports the%clregister as ... |
What is the exact equivalent of the following function for Ubuntu?
http://www.qnx.com/developers/docs/6.4.1/neutrino/lib_ref/e/endian_be16.html
|
What you need is:
```
#include <endian.h>
result_in_host_endianness = be16toh(my_big_endian_number)
```
Seehttp://man7.org/linux/man-pages/man3/endian.3.html
|
Got confused with the following peice of code.
```
#include <stdio.h>
void main()
{
int a=0100;
printf("%x",a);
}
```
The value I am getting is 40.
Can someone explain me whats going on here?
Note : When I removed the digit 0 before digit 1 then its coming 64 which is correct, when 100 is converted into hex.
Code... |
In C, a constant prefixed with a0is anoctalconstant. 0100 in base 8 is
1000000 in base 2, which is 40 in hexadecimal, which is 64 in base 10. So your program is printing exactly what it should.
|
What is the exact equivalent of the following function for Ubuntu?
http://www.qnx.com/developers/docs/6.4.1/neutrino/lib_ref/e/endian_be16.html
|
What you need is:
```
#include <endian.h>
result_in_host_endianness = be16toh(my_big_endian_number)
```
Seehttp://man7.org/linux/man-pages/man3/endian.3.html
|
Got confused with the following peice of code.
```
#include <stdio.h>
void main()
{
int a=0100;
printf("%x",a);
}
```
The value I am getting is 40.
Can someone explain me whats going on here?
Note : When I removed the digit 0 before digit 1 then its coming 64 which is correct, when 100 is converted into hex.
Code... |
In C, a constant prefixed with a0is anoctalconstant. 0100 in base 8 is
1000000 in base 2, which is 40 in hexadecimal, which is 64 in base 10. So your program is printing exactly what it should.
|
Learning C and need to populate array of five struct elements but I can't seem to figure out how to pass the struct array to a function and I keep getting error:
```
error: conflicting types for 'dealFiveHand'
```
Here is the code:
```
#define HAND_SIZE 5
void dealFiveHand(struct Card *wHand[]);
struct Card {
... |
At least you need to move the definition ofstruct CardBEFORE functiondealFiveHandprototype - that way the function knows about the type of its parameter.
```
struct Card {
char suit;
char face;
};
void dealFiveHand(struct Card *wHand[]);
```
|
I am writing some where I need to divide 29 by 10. But when I do so and store it in a double, it outputs 2.0000 instead of 2.9. Can someone explain why this is happening and how to fix it?
```
double a = 29/10;
output: 2.0000
```
|
Thedoubleworks as expected, it's just that you are not assigning it an expression of typedouble.
What you assign it is anint, a result of dividing29, anint, by10, anint. This is2, because the remainder is discarded when you divide integers.
Changing29to29.0or10to10.0will fix this problem.
|
```
schedule_accept(int fd,
int (*handler)(int, FdEventHandlerPtr, AcceptRequestPtr),
void *data)
```
Apologies for seeming to avoid searching for an answer here but I don't know what the constructs are in order to search intelligently for them. Specifically I'm interested in what the second p... |
```
int (*handler)(int, FdEventHandlerPtr, AcceptRequestPtr)
```
Defines a parameter namedhandlerwhich is a pointer (hence the*) to a function, which returns anint(hence the "outer"int) and takes three arguments, namely oneint, oneFdEventHandlerPtrand oneAcceptRequestPtr.
|
I want to know exactly, what is a null statement in C programming language? And explain a typical use of it.
I found the following segment of code.
```
for (j=6; j>0; j++)
;
```
And
```
for (j=6; j>0; j++)
```
|
From themsdnpage:
The "null statement" is an expression statement with the expression missing. It is useful when the syntax of the language calls for a statement but no expression evaluation. It consists of a semicolon.Null statements are commonly used as placeholders in iteration statements or as statements on which... |
I sawthisquestion but none of the answers were quite what I was looking for. I've triedstrstrbut it returns a pointer instead of an integer index.
I need to find if stringacontains stringband if so, where it's located, kind of like the index returned bystrcmp. Is there a function or easy way to do this in C?
For exa... |
You can usestrstrfor this, along with some pointer arithmetic.
```
char *result = strstr(a, b);
if (result != NULL) {
printf("index = %tu\n", result - a);
}
```
Here,resultpoints a particular number of bytes ahead ofa. So if you subtract the two, that's your index.
|
I'm making a project where I need to mirror an image vertically. The image is read by a function and then set into an array pixel by pixel, to move through this array I am usingarray[idy*w + idx](w being the width of the matrix or image in my case) now, since this will run concurrently I only need to find the opposite... |
This is what worked for me in the end:
```
outputImage[idy*w + idx] = inputImage[idy*w + (w - idx - 1)];
```
|
Although otherwise working with pointers, all Xlib functions I've seen so far pass their Window struct by value, not by reference. E.g.:
https://tronche.com/gui/x/xlib/ICC/client-to-window-manager/XGetClassHint.html
https://tronche.com/gui/x/xlib/window/XDestroyWindow.html
Is there any particular rationale for that... |
It looks likeWindowin those examples isn't a struct; it's just an unsigned long. That is, given:
```
#include <X11/X.h>
Window w;
```
If I pass that throughgcc -EI see:
```
$ gcc -E wintest.c | grep Window
typedef XID Window;
Window w;
```
AndXIDis:
```
$ gcc -E wintest.c | grep XID
typedef unsigned long XID;
``... |
I am trying to compile kernel for Cyanogenmod 13. I am getting error
```
ERROR: modpost: Found 2 section mismatch(es).
To see full details build your kernel with:
'make CONFIG_DEBUG_SECTION_MISMATCH=y'
To build the kernel despite the mismatches, build with:
'make CONFIG_NO_ERROR_ON_MISMATCH=y'
(NOTE: This is not re... |
I believe you need to setup gcc version 4.7 and use CC variable to set it as a compiler. E.g.make target CC=/bin/gcc4.7
More informationhereandhere.
|
I have a c file I've compiled with a executable called "run"
And want to run it with a argv[1] of testfile.txt that is in the uploads directory.
This here seems to work, but I don't understand why.
```
exec(__DIR__ . '/run uploads/testfile.txt',$output);
```
C programs are run as such:
```
./run uploads/testfile.t... |
Suppose__DIR__=='/foo/bar'.
Then,__DIR__ . './run'would evaluate to/foo/bar./runwhich does not exist.
|
I was studying ANSI C programming language and it says in introduction:
"Local variables are typically "automatic," or created anew with each invocation."
I'm guessing allocating and deallocating variables work with stack frame logic of Java. So are global variables automatic too? They would get in and out of stack ... |
No, these concepts don't play each other. The term global variable is an informal notion, that refers to variables with external linkage. By definition, the automatic variables have no linkage, hence it does not make sense to have variable, that is both automatic and global.
|
I sawthisquestion but none of the answers were quite what I was looking for. I've triedstrstrbut it returns a pointer instead of an integer index.
I need to find if stringacontains stringband if so, where it's located, kind of like the index returned bystrcmp. Is there a function or easy way to do this in C?
For exa... |
You can usestrstrfor this, along with some pointer arithmetic.
```
char *result = strstr(a, b);
if (result != NULL) {
printf("index = %tu\n", result - a);
}
```
Here,resultpoints a particular number of bytes ahead ofa. So if you subtract the two, that's your index.
|
I'm making a project where I need to mirror an image vertically. The image is read by a function and then set into an array pixel by pixel, to move through this array I am usingarray[idy*w + idx](w being the width of the matrix or image in my case) now, since this will run concurrently I only need to find the opposite... |
This is what worked for me in the end:
```
outputImage[idy*w + idx] = inputImage[idy*w + (w - idx - 1)];
```
|
When softwares such as ecryptfs use AES, it asks for a user password (such as "password123").
The AES algorithm by itself does not call for a user password. So where does the "password123" get thrown into the math?
I'm working to make a C function that encrypts some data using a password. I know the typical way of d... |
You need to use a key derivation function (KDF). Password-Based Key Derivation Function 2 (PBKDF2) is the current most common approach.
OpenSSL probably exposes PBKDF2, it typically takes in a password and an iteration count (modern systems should use something like 100000 or higher... crank up the number until it ta... |
Can anyone please explain me why is this code printing 1 3 0 0 0 -1, and not 1 2 3 0 0 0? How does this call of define work?
```
#include<stdio.h>
#define SOMETHINGDEFINED(i) A[i%4]
int main(void) {
int i, A[6] = { 1 };
SOMETHINGDEFINED(1) = 2;
SOMETHINGDEFINED(5) = 3;
SOMETHINGDEFINED(4 + 2) = SOME... |
#definedoes a textual replacement, so
```
SOMETHINGDEFINED(1 + 3 + 1)--
```
becomes
```
A[1 + 3 + 1%4]--
```
Now you can see that modulo is only applied to last operand, not to the whole expression. You have to define the macro as
```
#define SOMETHINGDEFINED(i) A[(i)%4]
```
to correctly apply it to the whole ex... |
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
```
int main()
{
... |
You need to look at the binary representation and remember that&is a bit-wise and-operator:
```
v = 5 = 101b
// First loop
v = 5 & (5-1) = 5 & 4 = 101b & 100b = 100b = 4
// Second loop
v = 4 & (4-1) = 4 & 3 = 100b & 011b = 000b = 0
// No more loops
```
|
● int vectorInsert(Vector * array, int index, Data value);
I am doing
If this can be corrected according to the given statement.
I am calling it using
```
Vector *vect = initVector();
Data data_array[20];
for(i = 0 ; i < 20 ; i++){
data_array[i].value = (rand() % 20) + 1;
vectorInsert(vect, i, data_array[i... |
There are a couple of errors in your code, but the most important one is in yourinitVectorfunction, you actually need to allocate memory for the vector.
You also need to do the following things:
ininitVectorreturnvinstead ofv->dataor&vinvectorInsertprintarray->data[index].valueinstead ofarray->data[index]invectorIns... |
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
```
int main()
{
... |
You need to look at the binary representation and remember that&is a bit-wise and-operator:
```
v = 5 = 101b
// First loop
v = 5 & (5-1) = 5 & 4 = 101b & 100b = 100b = 4
// Second loop
v = 4 & (4-1) = 4 & 3 = 100b & 011b = 000b = 0
// No more loops
```
|
● int vectorInsert(Vector * array, int index, Data value);
I am doing
If this can be corrected according to the given statement.
I am calling it using
```
Vector *vect = initVector();
Data data_array[20];
for(i = 0 ; i < 20 ; i++){
data_array[i].value = (rand() % 20) + 1;
vectorInsert(vect, i, data_array[i... |
There are a couple of errors in your code, but the most important one is in yourinitVectorfunction, you actually need to allocate memory for the vector.
You also need to do the following things:
ininitVectorreturnvinstead ofv->dataor&vinvectorInsertprintarray->data[index].valueinstead ofarray->data[index]invectorIns... |
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 have the following code:
```
if (a1 < a2)
a3=0;
else
a3=a1-a2;
if (b1 < b2)
... |
You can use a macro like:
```
#define COM(x,y) ((x<y)?0:(x-y))
...
a3 = COM(a1,a2);
b3 = COM(b1,b2);
c3 = COM(c1,c2);
```
or use a function instead.
```
int func(int x, int y)
{
return (x<y)?0:(x-y);
}
a3 = func(a1,a2);
b3 = func(b1,b2);
c3 = func(c1,c2);
```
If you can use an array (for storing a, b, and c e... |
Is there a way to catch a signal just once withsigactionstructure and function? To be more specific, I would like to simply reset to default a specific signal (SIGINT). Is it possible to achieve this in a handler?
Edit
So, something like this would be correct:
void sig_int(int sig)
{
printf(" -> Ctrl-C\n");
... |
The standard SA_RESETHAND flag, set in thesa_flagsmember ofstruct sigaction, does precisely this.
Set that flag when specifying your SIGINT handler, and the handler will be reset to SIG_DFL upon entry.
|
If I do this assignment
```
float x = 16.8;
unsigned int i = *(unsigned int*) &x;
```
What will be the value of the variablei? What it is the logic of this assignment?
|
With a code like this, you could have seen the answerin your precise case:
```
#include <stdio.h>
int main(void)
{
float x = 1;
unsigned int i = *(unsigned int*) &x;
printf("%d\n", i);
return 0;
}
```
This type of assignment is illegal, by casting a pointer to afloatinto a pointer to anunsign... |
Consider this snippet:
```
void init_seed(char *key)
{
char *seed = key;
size_t seed_len = strlen(seed);
// Make sure the seed is at least 12 bytes long
if (seed_len < 12) {
char new_seed[13];
for (int i = 0; i < 12; i++)
new_seed[i] = seed[i % seed_len];
new_se... |
Yes.
Oncenew_seedis out of scope, you no longer own any memory that was allocated for it.
So the behaviour on dereferencing the newly assigned value ofseedisundefined.
|
I am trying to add logging to the web proxy Polipo and as part of this need to log the url request in the following functionfollowing line:
```
httpClientRequest(HTTPRequestPtr request, AtomPtr url)
```
From compilation I see that AtomPtr is a struct of type_Atombut I cannot find where this is defined so that I can ... |
you can searchAtomPtrlikethisand see where AtomPtr is defined
```
typedef struct _Atom {
unsigned int refcount;
struct _Atom *next;
unsigned short length;
char string[1];
} AtomRec, *AtomPtr;
```
|
For a peripheral requirement in an embedded system, I have to declare a variable to read a register, but won't use the value later. Hence, I get compiler warning about my unused variable naturally.
How can I suppress the warning? I have 2 ways in mind:
using compiler directives, I hesitate because they are compiler-... |
If all you need to do is read the register (to clear some status flag for example), then you do not need a receiving variable at all just:
```
(void)peripheral_register ;
```
is sufficient assuming the register is itself is declared volatile so that it must be read.
Otherwise you could make your dummyvarglobal with... |
Is there a way to catch a signal just once withsigactionstructure and function? To be more specific, I would like to simply reset to default a specific signal (SIGINT). Is it possible to achieve this in a handler?
Edit
So, something like this would be correct:
void sig_int(int sig)
{
printf(" -> Ctrl-C\n");
... |
The standard SA_RESETHAND flag, set in thesa_flagsmember ofstruct sigaction, does precisely this.
Set that flag when specifying your SIGINT handler, and the handler will be reset to SIG_DFL upon entry.
|
If I do this assignment
```
float x = 16.8;
unsigned int i = *(unsigned int*) &x;
```
What will be the value of the variablei? What it is the logic of this assignment?
|
With a code like this, you could have seen the answerin your precise case:
```
#include <stdio.h>
int main(void)
{
float x = 1;
unsigned int i = *(unsigned int*) &x;
printf("%d\n", i);
return 0;
}
```
This type of assignment is illegal, by casting a pointer to afloatinto a pointer to anunsign... |
Take for instance the following example of calling a function, and assigning a value to one of its parameters at call time:
```
int MyFunction(int flag, float value);
MyFunction(myFlag=666, 3.14);
```
It's legal, though perhaps dangerous, to assign values to variables in a function call's parameter list.
How can I... |
You can assign a compound literal to the variable:
```
MyFunction(myValues = (my_struct) {myValues.i, .j=777, myValues.k});
```
|
I'm trying to execute this code:
```
signal(SIGALRM,handler);
alarm(1);
while(1){}
```
Thehandlerfunction just prints "test".
alarm(1)will eventually be executed only one time in this case. I tried to put it in the loop and it seems that it doesn't get executed at all!
I am kinda new to signals. Can someone explai... |
If you just putalarm(1)in the loop in your example, you'll callalarm(1)infinitely many times within a few microseconds of each invocation. And thenthishappens:
If an alarm has already been set with alarm() but has not been delivered, another call to alarm() will supersede the prior call.
I.e., the alarm gets cleared... |
I tried doing awhileloop with multiple conditions, but I just can't figure out how to make it work. I've made a short example of what I kind of tried:
```
#include <stdio.h>
int main () {
int Num;
printf("Please enter an odd integer between 5-20: ");
scanf("%d", &Num);
while ((Num % 2 == 0) && (5 >... |
Nope, you're wrong. Think of the logic
```
(5>Num) && (20<Num)
```
Numcannot be<5and>20at the same time. You either
need the logical OR operatorChange the range to something like(Num > 5) && (Num < 20)or something
|
I need to make a Julia type corresponding to a C struct that has a fixed size array:
```
struct cstruct {
...
int arr[N] //N known at compile time
...
};
```
I have defined Julia types corresponding to other C structs with arrays like this:
```
type jstruct
...
arr::Ptr{Cint}
...
end
```
B... |
When you define a C struct with a fixed size array (or with the array hack), the data are stored directly inline within that struct. It's not a pointer to another region. The equivalent Julia structure is:
```
type JStruct{N}
arr::NTuple{N,Int}
end
```
That will store the integers directly inline within the st... |
I have to write program that displays the nth roots of unity when given a positive integer n. It's a programming project 27.4 from K.N.King book on C programming.
my attempt:
```
#include <stdio.h>
#include <complex.h>
#include <math.h>
int main(void)
{
int n, k;
double complex nth;
printf("Enter positive integer:... |
Theexpfunction expects adouble, but you pass it adouble complex.
Usecexpinstead:
```
nth = cexp(2 * M_PI * I * k / n);
```
Output:
```
Enter positive integer: 5
k = 0, 1 + 0
k = 1, 0.309017 + 0.951057
k = 2, -0.809017 + 0.587785
k = 3, -0.809017 + -0.587785
k = 4, 0.309017 + -0.951057
```
|
I have a macro that I define at the beginning of a header and then undef at the end. However that macro (I'll call itfoo) depends on another macro (I'll call ittest). I was wondering whether I can remember the value to whichfooexpands. My first idea was the following, which obviously doesn't work:
```
#define foo tes... |
No, you can't.
Macros are expanded only at the moment they are inserted into the programming token stream. They are not expanded in the#definepreprocessing directive.
|
Take for instance the following example of calling a function, and assigning a value to one of its parameters at call time:
```
int MyFunction(int flag, float value);
MyFunction(myFlag=666, 3.14);
```
It's legal, though perhaps dangerous, to assign values to variables in a function call's parameter list.
How can I... |
You can assign a compound literal to the variable:
```
MyFunction(myValues = (my_struct) {myValues.i, .j=777, myValues.k});
```
|
I'm trying to execute this code:
```
signal(SIGALRM,handler);
alarm(1);
while(1){}
```
Thehandlerfunction just prints "test".
alarm(1)will eventually be executed only one time in this case. I tried to put it in the loop and it seems that it doesn't get executed at all!
I am kinda new to signals. Can someone explai... |
If you just putalarm(1)in the loop in your example, you'll callalarm(1)infinitely many times within a few microseconds of each invocation. And thenthishappens:
If an alarm has already been set with alarm() but has not been delivered, another call to alarm() will supersede the prior call.
I.e., the alarm gets cleared... |
I have third party C library. I want to use it in c++
Every function return error code.
when i have to use it I have to write code like this:
```
int err;
err=libFun1(....);
check(err);
err=libFun2(....);
check(err);
```
I want to wrap this functions and avoid code duplication of check. Every of this librabry functi... |
How about a templated function:
```
template <typename T>
int CallWrapper(T func)
{
int error = func();
check(error);
return error;
}
```
Then call it withCallWrapper(libFun1);.
|
This question already has answers here:Why must int pointer be tied to variable but not char pointer?(8 answers)Closed6 years ago.
Correct me if I am wrong, but I had assumed this line of code:
```
const char *foo = "Hello";
```
Meant that an array of chars filled with "Hello" are created somewhere on the stack, an... |
Because"Hello"is astring literalof typechar [N](in C) andconst char[N](in C++), which decays to a typechar*(in C) orconst char*(in C++), same as the pointer you are binding it to. On the other hand,5is a rvalue and its type is anint, so you cannot bind it to a pointer of typeconst int*.
You may findthisuseful.
|
I'm working on a webserver in UNIX environment with C language. Currently, I have done jailing the process but now I cannot use syslog and logging to a file option and that's basically due to the changed root path.
New root path for the program is it's directory. I could not escape from it to real root "/" in order t... |
The whole point of usingchroot()is to make the real root inaccessible, so easy formula: If you can break it, you don't need it.
So, you should make syslog accessible from within your chroot environment instead. How? Justopenlog()prior tochroot(). After that, you cansyslog()even though you wouldn't be able toopenlog()... |
I understand how pointers to pointers work, but I can't understandwhy using pointers to pointers over simple pointers, and when using them inC programming(not C++). I've read a lot of posts about it, but I can't found a satisfying answer. All examples I've seen can be turned into a one-level pointer solution. Can some... |
A simple is a case where you want to modify the pointer itself. For example,
```
void func(char **p)
{
*p = malloc(1024); / allocate 1024 bytes */
}
int main(void)
{
char *p = NULL;
func(&p);
/* Now, p points at memory block of 1024 bytes and do something with it */
return 0;
}
```
Of course, it's p... |
I have third party C library. I want to use it in c++
Every function return error code.
when i have to use it I have to write code like this:
```
int err;
err=libFun1(....);
check(err);
err=libFun2(....);
check(err);
```
I want to wrap this functions and avoid code duplication of check. Every of this librabry functi... |
How about a templated function:
```
template <typename T>
int CallWrapper(T func)
{
int error = func();
check(error);
return error;
}
```
Then call it withCallWrapper(libFun1);.
|
This question already has answers here:Why must int pointer be tied to variable but not char pointer?(8 answers)Closed6 years ago.
Correct me if I am wrong, but I had assumed this line of code:
```
const char *foo = "Hello";
```
Meant that an array of chars filled with "Hello" are created somewhere on the stack, an... |
Because"Hello"is astring literalof typechar [N](in C) andconst char[N](in C++), which decays to a typechar*(in C) orconst char*(in C++), same as the pointer you are binding it to. On the other hand,5is a rvalue and its type is anint, so you cannot bind it to a pointer of typeconst int*.
You may findthisuseful.
|
I'm working on a webserver in UNIX environment with C language. Currently, I have done jailing the process but now I cannot use syslog and logging to a file option and that's basically due to the changed root path.
New root path for the program is it's directory. I could not escape from it to real root "/" in order t... |
The whole point of usingchroot()is to make the real root inaccessible, so easy formula: If you can break it, you don't need it.
So, you should make syslog accessible from within your chroot environment instead. How? Justopenlog()prior tochroot(). After that, you cansyslog()even though you wouldn't be able toopenlog()... |
I am trying to figure out if there is a better way to test if a string being entered at the command line is a valid enum entry for a C program.
Is there a better way to test the entries in an enum instead of saying:
```
if((!strcmp(string, "NUM0")) && (!strcmp(string, "NUM1")))
{
printf("Invalid entry\n");
r... |
I do it this way:
```
enum opt {NUM0, NUM1, NUM2, OPT_END};
static const char *opt_str[OPT_END] = {"NUM0", "NUM1", "NUM2"};
enum opt i;
for (i = 0; i < OPT_END; ++i)
if (strcmp(string, opt_str[i]) == 0) break;
if (i == OPT_END) {
puts("Invalid entry");
return EXIT_FAILURE;
}
/* do something with i */
```... |
The segmentation fault error disappears after commenting out the scanf loop. Why is that loop giving me a segmentation fault?
```
char** nameArray = malloc(numNames * sizeof(char *));
for(i =0; i< 10; i++) {
nameArray[i] = malloc(25 * sizeof(char));
}
for (i = 0; i< numNames; i++) {
scanf("%s", &nameArray[i... |
First you need to change
```
for(i =0; i< 10; i++) {
```
to
```
for(i =0; i< numNames; i++) {
```
as you need to create enough entries.
Also you need to change this line
```
scanf("%s", &nameArray[i]);
```
to
```
scanf("%s", nameArray[i]);
```
asnameArray[i]is a character pointer as required.
Also it would b... |
```
void Tmr_Wait1us (uint16_t delay) {
uint16_t i;
TCNT0 = 0; // will start to count from 0 up to 255 (if 8-bit timer)
for (i = 0; i < delay / 256; i++)
while (TCNT0 < 255)
;
while (TCNT0 <= delay % 256)
;
}
```
This code is used to set a timer to wait pre... |
TCNT0is the current timer count for timer 0, a 8-bit timer. Since it counts asynchronously from your code, it will increment even if the CPU is in a spin wait.
But since avr-libc provides fairly precise spin waits inutil/delay.hyou are usually better off using those instead.
```
for (int i = 0; i < delay; i++)
_de... |
I'm trying to learn more about how computers store memory. So I've found information on how to represent binary numbers or hexadecimal numbers, but I found a question asking:
```
Given three n-bit unsigned ints: x, y, z, what is the min #
of bits required to represent x * y + z
```
So my thinking is: Do I have to j... |
The number of bits required isn + n. Taking an example using 8 bits and maximum unsigned values:
```
255 * 255 + 255 = 65280
```
The result is less then65536which would require more than 16 bits.
|
I tried the following code in gcc:
```
#include<stdio.h>
int main()
{
int a=3,2,1;//////////////////////ERROR!//////////////////////////
printf("%d", a);
return 0;
}
```
I expected it to compile successfully as:
a series of integer expressions seperated by commas will be evaluated from left to right and... |
That's parsed as a three-part variable declaration, with two invalid variables.
You need to wrap the entire initializer in parentheses so that it's parsed as a single expression:
```
int a=(3,2,1);
```
|
I am trying to convertASCIIhexadecimal value (0x61 or 61) to it'scharvalue (61 = a, etc..)withoutatoi,scanf,strcat.
I am savinggetchar()to temp variable, then I save first one (6) in array, then save second one (1) in array, now i want take these two and convert them to their ASCII value.
```
68656c6c6f0d0a = hello
... |
Not sure exactly what you are trying to do but this may help.
```
int main(int argc, char **argv)
{
int hex[6] = {0x68, 0x65, 0x6C, 0x6C, 0x6F};
int i = 0;
for(i = 0; i <6; i++)
{
printf("%c", hex[i]);
}
printf("\n");
}
```
|
I was recently doing some experiments with theforkfunction and I was concerned by a "simple" (short) question:
Doesforkuses concurrency or parallelism (if more than one core) mechanisms?Or, is it the OS which makes the best choice?
Thanks for your answer.
nb: Damn I fork bombed myself again!
Edit:
Concurrency: Ea... |
fork()duplicates the current process, creating another independent process. End of story.
How the kernel chooses to schedule these processes is a different, very broad question. In general the kernel will try to use all available resources (cores) to run as many tasks as possible. When there are more runnable tasks t... |
```
void Tmr_Wait1us (uint16_t delay) {
uint16_t i;
TCNT0 = 0; // will start to count from 0 up to 255 (if 8-bit timer)
for (i = 0; i < delay / 256; i++)
while (TCNT0 < 255)
;
while (TCNT0 <= delay % 256)
;
}
```
This code is used to set a timer to wait pre... |
TCNT0is the current timer count for timer 0, a 8-bit timer. Since it counts asynchronously from your code, it will increment even if the CPU is in a spin wait.
But since avr-libc provides fairly precise spin waits inutil/delay.hyou are usually better off using those instead.
```
for (int i = 0; i < delay; i++)
_de... |
I'm trying to learn more about how computers store memory. So I've found information on how to represent binary numbers or hexadecimal numbers, but I found a question asking:
```
Given three n-bit unsigned ints: x, y, z, what is the min #
of bits required to represent x * y + z
```
So my thinking is: Do I have to j... |
The number of bits required isn + n. Taking an example using 8 bits and maximum unsigned values:
```
255 * 255 + 255 = 65280
```
The result is less then65536which would require more than 16 bits.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.