question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I am writing a program and I want to write some hex addresses to the file. The problem is that when Ihexdump -C tempthe file, I only seebc aband the\x00were not written to the file for some reason I don't understand. Maybe they were recognized as EOF characters? Any help is really appreciated.
```
File *file;
char *buffer, *ptr;
ptr = buffer;
*(ptr++) = '\xbc';
*(ptr++) = '\xab';
*(ptr++) = '\x00'; // problem
*(ptr++) = '\x00';
file = fopen("temp", "w");
if (file == NULL) {
fprintf(stderr, "Opening file failed.\n");
exit(1);
}
fprintf(file, "%s", buffer);
fclose(file);
```
|
You tried to write null characters with fprintf's %s. Null character is the string terminator. It won't be written that way. Use fwrite or fputc.
|
I am writing a program and I want to write some hex addresses to the file. The problem is that when Ihexdump -C tempthe file, I only seebc aband the\x00were not written to the file for some reason I don't understand. Maybe they were recognized as EOF characters? Any help is really appreciated.
```
File *file;
char *buffer, *ptr;
ptr = buffer;
*(ptr++) = '\xbc';
*(ptr++) = '\xab';
*(ptr++) = '\x00'; // problem
*(ptr++) = '\x00';
file = fopen("temp", "w");
if (file == NULL) {
fprintf(stderr, "Opening file failed.\n");
exit(1);
}
fprintf(file, "%s", buffer);
fclose(file);
```
|
You tried to write null characters with fprintf's %s. Null character is the string terminator. It won't be written that way. Use fwrite or fputc.
|
The code below stores values in character array and outputs the integer value . can you please tell me how is it possible?
```
int main()
{
char p;
char buf[10]={1,2,3,4,5,6,9,8};
p=(buf+1)[5];
printf("%d",p);
return 0;
}
```
|
```
p=(buf+1)[5];
```
is the same as
```
p=*(buf+1+5);
```
and the same as
```
p=*(buf+6);
```
and the same as
```
p=buf[6];
```
So look atbuf
```
char buf[10]={1,2,3,4,5,6,9,8};
^ ^ ^ ^ ^ ^ ^ ^
0 1 2 3 4 5 6
^
^
The element read
```
Sopis set equal to 9
and therefore
```
printf("%d",p);
```
prints 9
This is because%dmeans "print integer value" and any integer with size less than int (like a char) is promoted (aka converted) to int when callingprintf
|
The code below stores values in character array and outputs the integer value . can you please tell me how is it possible?
```
int main()
{
char p;
char buf[10]={1,2,3,4,5,6,9,8};
p=(buf+1)[5];
printf("%d",p);
return 0;
}
```
|
```
p=(buf+1)[5];
```
is the same as
```
p=*(buf+1+5);
```
and the same as
```
p=*(buf+6);
```
and the same as
```
p=buf[6];
```
So look atbuf
```
char buf[10]={1,2,3,4,5,6,9,8};
^ ^ ^ ^ ^ ^ ^ ^
0 1 2 3 4 5 6
^
^
The element read
```
Sopis set equal to 9
and therefore
```
printf("%d",p);
```
prints 9
This is because%dmeans "print integer value" and any integer with size less than int (like a char) is promoted (aka converted) to int when callingprintf
|
The code below stores values in character array and outputs the integer value . can you please tell me how is it possible?
```
int main()
{
char p;
char buf[10]={1,2,3,4,5,6,9,8};
p=(buf+1)[5];
printf("%d",p);
return 0;
}
```
|
```
p=(buf+1)[5];
```
is the same as
```
p=*(buf+1+5);
```
and the same as
```
p=*(buf+6);
```
and the same as
```
p=buf[6];
```
So look atbuf
```
char buf[10]={1,2,3,4,5,6,9,8};
^ ^ ^ ^ ^ ^ ^ ^
0 1 2 3 4 5 6
^
^
The element read
```
Sopis set equal to 9
and therefore
```
printf("%d",p);
```
prints 9
This is because%dmeans "print integer value" and any integer with size less than int (like a char) is promoted (aka converted) to int when callingprintf
|
I want to store a java object in JNI. So I do
```
jobject gRefObj = (*env)->NewGlobalRef(env, obj);
```
After that I want to get back the jobject from other thread and from java call to jni to return object. So I do.
```
(*_env)->DeleteGlobalRef(_env, gRefObj ); // if remove this line, it will work
return gRefObj; // From jni return to java
```
Then I got classCastException, but if I remove the DeleteGlobalRef, it working fine. Will java delete it after use?
|
Based on @mkaes and @Michael comment, i've tried to do
```
JNIEXPORT jobject JNICALL Java_com_sample_getMyObject(JNIEnv *env, jobject obj) {
jclass clz = (*env)->GetObjectClass(env, obj);
// .. doing something
jobject lRefObj = (*env)->NewLocalRef(env, gRefObj);
(*env)->DeleteGlobalRef(env, gRefObj);
(*env)->DeleteLocalRef(env, clz);
return lRefObj;
}
```
|
So I built a program to find if a number is divisible by a perfect square (i.e 4, 9, 16, 25...). However, it seems that my number never gets checked after 4 as it exits the loop after getting checked by 4. But I need it need to be checked for all squares up to that initial number that I input. Here is the for loop that I used:
```
for(i=2; i < x; i++) {
if ( x%(i*i) == 0) {
printf("%d is divisible by a perfect square.\n", x);
break;
}
else {
printf("%d is not divisible by a perfect square.\n", x);
break;
}
}
```
Now how do I make my program check for all the squares?
|
Thefor loopends when you hit abreak. And you always hit abreak!
|
I'm using a system function which writes the output information into a stream of file pointer.
```
func(FILE *__fp)
```
I need to use this information in my program rather than printing this out to a file. For that I thought of creating atmpfile()and writing to it then reading back from it. But is there a better way to get this information?
|
There are OS-specific solutions to writing to a memory buffer instead of a file, like for example the POSIXfmemopenoropen_memstream(both which should be very useful considering yourlinuxtag).
You can also change the internal buffer to your own withsetvbuf.
On an unrelated note: Symbols starting with a leading underscore and followed by another underscore (like for example your__fpargument) arereserved. Such symbols may only be used by "the implementation", i.e. the compiler and library.
|
```
typedef struct Expected {
const int number;
const char operand;
} Expected;
Expected array[1];
Expected e = {1, 'c'};
array[0] = e;
```
I don't understand why you cannot add to a struct array like that. Do I have to calculate the positions in memory myself?
|
The element ofExpectedare declaredconst. That means they can't be modified.
In order to set the values, you need toinitializethem at the time the variable is defined:
```
Expected array[1] = { {1, 'c'} };
```
The fact that you're using an array doesn't matter in this case.
|
```
struct Node *prevX = NULL, *currX = *head_ref;
while (currX && currX->data != x)
{
prevX = currX;
currX = currX->next;
}
```
Why was currX placed here? How can it affect the outcome?
|
while (currX)tests the truthiness ofcurrX. It's effectively short forwhile (0!=currX).
|
The output of the following code is 0.
```
int account=2;
int main()
{
static int account;
printf("%d",account);
return 0;
}
```
Why it picked static variable over global variable? Because what I understand is that both global and static variables are stored in the heap and not in function stack , right? So what method it uses to use select one over another?
|
If multiple variables exist with the same name at multiple scopes, the one in the innermost scope is the one that is accessible. Variables at higher scope are hidden.
In this case you haveaccountdefined inmain. This hides the variable namedaccountdeclared at file scope. The fact that the inner variable insidemainis declaredstaticdoesn't change that.
While thestaticdeclaration on a local variable means that it is typically stored in the same place as a global variable, that has no bearing on which is visible when the names are the same.
|
```
int findHeight(struct BstNode* root)
{
if(root==NULL)
return -1;
return max(findHeight(root->left),findHeight(root->right))+1;
}
```
The function always returns 1 as the height.Here's the code link.https://github.com/ashwinidotx/OpenIssues/blob/master/Height%20Of%20Binary%20Tree.c
|
The code is buggy. When you are reaching beyond the leaf node, you are returning-1which is wrong. This is doing subtraction on the calculation of tree height. You should simply return0here because you hit the end, there is no node down there.
Here is the corrected method:
```
int findHeight(struct BstNode* root)
{
if(root == NULL)
return 0;
return 1 + max(findHeight(root->left), findHeight(root->right));
}
```
|
I'm a newbie who is trying to compile a simple code. This is the code I'm trying to compile.
```
#include <stdio.h>
int main()
{
int integer1;
int integer2;
int sum;
printf("Enter first integer\n");
scanf( "%d", integer1 );
printf( "Enter second integer\n" );
scanf( "%d", integer2 );
sum = integer1 + integer2;
printf( "sum is %d\n", sum );
return 0;
}
```
I am using the Visual Studio 2017 as compiler and I get the error below.
Run-Time Check Failure #3 - The variable 'integer1' is being used without being initialized.
Could you please help?
|
Your compiler is being really rather friendly.
You need to pass apointerto the variable to be set byscanf, and you shouldalwayscheck the return value ofscanf:
```
if (scanf("%d", &integer1) == 1){
// all read correctly; i.e. 1 variable set
} else {
// don't attempt to read `integer1`
}
```
|
```
typedef struct Expected {
const int number;
const char operand;
} Expected;
Expected array[1];
Expected e = {1, 'c'};
array[0] = e;
```
I don't understand why you cannot add to a struct array like that. Do I have to calculate the positions in memory myself?
|
The element ofExpectedare declaredconst. That means they can't be modified.
In order to set the values, you need toinitializethem at the time the variable is defined:
```
Expected array[1] = { {1, 'c'} };
```
The fact that you're using an array doesn't matter in this case.
|
```
struct Node *prevX = NULL, *currX = *head_ref;
while (currX && currX->data != x)
{
prevX = currX;
currX = currX->next;
}
```
Why was currX placed here? How can it affect the outcome?
|
while (currX)tests the truthiness ofcurrX. It's effectively short forwhile (0!=currX).
|
The output of the following code is 0.
```
int account=2;
int main()
{
static int account;
printf("%d",account);
return 0;
}
```
Why it picked static variable over global variable? Because what I understand is that both global and static variables are stored in the heap and not in function stack , right? So what method it uses to use select one over another?
|
If multiple variables exist with the same name at multiple scopes, the one in the innermost scope is the one that is accessible. Variables at higher scope are hidden.
In this case you haveaccountdefined inmain. This hides the variable namedaccountdeclared at file scope. The fact that the inner variable insidemainis declaredstaticdoesn't change that.
While thestaticdeclaration on a local variable means that it is typically stored in the same place as a global variable, that has no bearing on which is visible when the names are the same.
|
```
int findHeight(struct BstNode* root)
{
if(root==NULL)
return -1;
return max(findHeight(root->left),findHeight(root->right))+1;
}
```
The function always returns 1 as the height.Here's the code link.https://github.com/ashwinidotx/OpenIssues/blob/master/Height%20Of%20Binary%20Tree.c
|
The code is buggy. When you are reaching beyond the leaf node, you are returning-1which is wrong. This is doing subtraction on the calculation of tree height. You should simply return0here because you hit the end, there is no node down there.
Here is the corrected method:
```
int findHeight(struct BstNode* root)
{
if(root == NULL)
return 0;
return 1 + max(findHeight(root->left), findHeight(root->right));
}
```
|
I'm a newbie who is trying to compile a simple code. This is the code I'm trying to compile.
```
#include <stdio.h>
int main()
{
int integer1;
int integer2;
int sum;
printf("Enter first integer\n");
scanf( "%d", integer1 );
printf( "Enter second integer\n" );
scanf( "%d", integer2 );
sum = integer1 + integer2;
printf( "sum is %d\n", sum );
return 0;
}
```
I am using the Visual Studio 2017 as compiler and I get the error below.
Run-Time Check Failure #3 - The variable 'integer1' is being used without being initialized.
Could you please help?
|
Your compiler is being really rather friendly.
You need to pass apointerto the variable to be set byscanf, and you shouldalwayscheck the return value ofscanf:
```
if (scanf("%d", &integer1) == 1){
// all read correctly; i.e. 1 variable set
} else {
// don't attempt to read `integer1`
}
```
|
```
int findHeight(struct BstNode* root)
{
if(root==NULL)
return -1;
return max(findHeight(root->left),findHeight(root->right))+1;
}
```
The function always returns 1 as the height.Here's the code link.https://github.com/ashwinidotx/OpenIssues/blob/master/Height%20Of%20Binary%20Tree.c
|
The code is buggy. When you are reaching beyond the leaf node, you are returning-1which is wrong. This is doing subtraction on the calculation of tree height. You should simply return0here because you hit the end, there is no node down there.
Here is the corrected method:
```
int findHeight(struct BstNode* root)
{
if(root == NULL)
return 0;
return 1 + max(findHeight(root->left), findHeight(root->right));
}
```
|
I'm a newbie who is trying to compile a simple code. This is the code I'm trying to compile.
```
#include <stdio.h>
int main()
{
int integer1;
int integer2;
int sum;
printf("Enter first integer\n");
scanf( "%d", integer1 );
printf( "Enter second integer\n" );
scanf( "%d", integer2 );
sum = integer1 + integer2;
printf( "sum is %d\n", sum );
return 0;
}
```
I am using the Visual Studio 2017 as compiler and I get the error below.
Run-Time Check Failure #3 - The variable 'integer1' is being used without being initialized.
Could you please help?
|
Your compiler is being really rather friendly.
You need to pass apointerto the variable to be set byscanf, and you shouldalwayscheck the return value ofscanf:
```
if (scanf("%d", &integer1) == 1){
// all read correctly; i.e. 1 variable set
} else {
// don't attempt to read `integer1`
}
```
|
I noticed the following code in a code review:
```
for (int i = 0; i < 50; ++i) {
switch(i) {
case 0:
return f1();
case 1:
return f2();
...
case 49:
return f50();
}
}
```
and I'm wondering if there's any elegant way, such as using a macro to simplify this code (reduce it to few lines):
thanks.
|
```
for (int i = 0; i < 50; ++i) {
switch(i) {
case 0:
return f1();
...
```
can be reduced to
```
return f1();
```
No macros required.
|
I am trying to put together a C code, wherein a thread performs a specific operation when an event occurs. However, as soon as I create the task using pthread_create(), my code jumps to thread's function. Is it possible to somehow just initiate the thread but keeping it idle till an event occurs and meanwhile my other threads keep executing independently ?
|
You can use semaphore or condition variable.
SemaphoreThe event thread will have sem_post() operation, operation thread will have sem_wait() operation.
Condition variableSimilar to semaphore. Condition variable works with a mutex. When an event occurs, signal the operation thread(pthread_cond_signal()). Signal will be received by operation thread, which is waiting at pthread_cond_wait().
|
I am trying to read an entire line from the user including white space, however my code right now does the scanf correctly only on the first iteration of the for loop. After that it simply prints x 9 times rather than asking the user again for more input. It is as if the scanf doesn't get called on the subsequent iterations Why is this? How can I fix this? My code is below. Thanks
```
#include <stdio.h>
#include <stdlib.h>
int main(){
char x[1024];
for (int n=0; n<10; n++){
scanf("%[^\n]s",x);
printf("x = %s\n",x);
}
```
|
Thescanffamily has myriad problemsincluding leaving items in the buffer which it will then continue to re-read. That's what's happening to you. If you don't need to use it, don't use it.
Usefgetsto read whole lines. Then if you want to parse the line further usesscanf.
```
char line[BUFSIZ];
while( fgets(line, sizeof(line), stdin) != NULL ) {
...
}
```
|
This question already has answers here:Are 'addition' and 'bitwise or' the same in this case?(6 answers)Closed5 years ago.
Yeah. I would like to know this. programming on my new msp430g2553 and both seems to work. The first one is from an online tutorial and the second one is what I had already put in my code and seems to work...
Are they identical?
UPDATE
BIT0 = 0x01
BIT6 = 0x04
|
In this case, yes they are the same. The same can't be said for an expression where you have more than 2 'bits' or where the 2 'bits' are the same.
AssumingBIT0 = 00000001 and BIT6 = 01000000
ThenBIT0 | BIT6 = 01000001 and BIT0 + BIT6 = 01000001
But if we were using the same 'bits' twice ..
```
BIT0 | BIT0 = 00000001
```
BUT
```
BIT0 + BIT0 = 00000010
```
|
I went throughusb-serial.c, which is a source file in theusbserialmodule in the Linux kernel. I would like to implement some customization in this driver, e.g., blinking LED when a communication (Tx/Rx) happens. However, I am having trouble finding the functions which are responsible for that communication. I was able to findserial_writebut was not able to find aserial_read,serial_receive, or similar. Does anyone know about the receive data function in this driver? Thanks in advance..!
|
Tryusb_serial_generic_read_bulk_callback(from drivers/usb/serial/generic.c). I think the line in this function that hasport->read_urbsis basically when the USB read is starting from.
So if you make your own version of that function you can put it inusb_serial_operations_initin place ofusb_serial_generic_read_bulk_callback
|
```
#include <stdio.h>
void fun(int a,int b,int c){
int *ret;
ret = &a -1;
(*ret)+=8;
}
int main(){
int x;
x = 0;
fun(1,2,3);
x = 1;
printf("x is %d\n",x );
return 0;
}
```
I believe x should be 1, but it's actually 0. What causes this?
|
You are invoking some very undefined behavior. The variableain the function is at an address (probablyon the stack) that is normally only accessible to the function. Decrementing that address results in an undefined location. You don't know what's there at all, so you have no idea what incrementing it by 8 will do.
|
```
int __cdecl sub_920(char *s1)
{
void *v1; // esi
char *ptr; // esi
int v3; // edi
v1 = off_2048;
strlen((const char *)off_2048);
ptr = (char *)__strdup(v1);
memfrob(ptr);
v3 = strcmp(s1, ptr);
free(ptr);
return v3;
}
```
This code was written by IDA, and I am not sure whatptr = (char *)__strdup(v1);actually does?
|
As can be read here:http://refspecs.linuxbase.org/LSB_3.0.0/LSB-PDA/LSB-PDA/baselib---strdup-1.html
__strdup -- alias for strdup
Whatstrdupdoes can be read in this answer:https://stackoverflow.com/a/252802/6699433
The short version is, it creates a copy of the string passed as argument and returns a pointer to the copy.
|
I have found a similar form of machine code tester across on the web written in C.
The tester uses pointer arithmetic to run a buffer of machine code.
```
#include <stdio.h>
#include <string.h>
unsigned char code[] = \
"machine code to be executed";
void main() {
int (*ret)() = (int(*)())code;
ret();
}
```
Can anyone explain the logic behind the pointer arithmetic of the two
lines presented above?
|
Can anyone explain the logic behind the pointer arithmetic of the two lines presented above?
There is no pointer arithmetic.The code simply declares a variable (ret) whose type is a pointer to a function that takes no parameters and returns anint. It sets that variable to point tocode, which presumably contains the actual bytes of the machine code, and then uses it to make a function call.
|
What does this command mean in a .c/.cpp file?
```
uFlags &= ~CHN_PANNING;
```
as per my research uFlags are Bit-Wise flags.
|
~is bit negation. It turns011001into100110, etc. If you&with the bit negation of a number, you essentially remove the1-bits of the right hand side from the bits on the left hand side (1s turn to0s after the bit negation and no bit can stay1if it's&-ed with0.0s turn to1s and&-ing with1doesn't change the original bit).
bitset0 &=~ bitset1(orbitset0 &~ bitset) is therefore a kind of a C/C++ idiom for (bit)set subtraction. It subtractsbitset1frombitset0(i.e.bitset0 \ bitset1in math notation), possibly (in the=version) assigning the result tobitset0.
|
What is the difference between initializing achararray with a string in curly braces and without curly braces?
```
char arr[] = {"string"};
```
or
```
char arr[] = "string";
```
|
There is no difference. This is directly addressed by C99,6.7.8 Initialization:
An array of character type may be initialized bya character string literal, optionally
enclosed in braces. Successive characters of the character string literal (including the
terminating null character if there is room or if the array is of unknown size) initialize the
elements of the array.
(Emphasis mine.)
|
My program planning to looping for getting some element from the queue, however, keep looping might overhead CPU usage, I'm wonder to put a nanosleep with 1ms wait. Can I just makestruct timespec shared_time_wait;on global, and reuse it?
```
struct timespec shared_time_wait;
void wait1ms()
{
nanosleep(&shared_time_wait, NULL);
}
void init() {
unsigned int ms = 1;
shared_time_wait.tv_sec = ms / (1000 * 1000);
shared_time_wait.tv_nsec = (ms % (1000 * 1000)) * 1000;
for(;;) {
wait1ms();
}
}
```
|
Fromman 2 nanosleep:
```
int nanosleep(const struct timespec *req, struct timespec *rem);
```
It's perfectly fine to reusereq, since it's declared asconst. Since you aren't changing it yourself, and theconst-ness of the function means it's not changing it either, no harm can come of reusing it. (The above wouldn't be true forrem, since it is written to, but you're not using that so you don't have to worry about it.)
|
I have a very simple makefile, makefile.mak , that isn't being recognized by the makefile command.
When I enter "make mp3" Makefile spits out "No rule to make target 'mp3'. Stop."
However when I enter "make -f makefile.mak mp3" the command executes fine. Why is this?
```
mp3: addMP3.c deleteAllOccurOf.c deleteMP3.c main.c printBackward.c printForward.c
gcc -o mp3.out addMP3.c deleteAllOccurOf.c deleteMP3.c main.c printBackward.c printForward.c
```
|
Usually, a makefile is calledmakefile. In other words remove the.makfrom the filename.
|
I'm trying write a code that matrix 3*3 but it doesn't work correctly. it prints random numbers. what I did wrong?
```
int matrix[3][3];
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&matrix[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d ",&matrix[i][j]);
}
}
```
|
You should remove&while printing valuesUse below code for printing.
```
printf("%d ",matrix[i][j]);
```
|
```
#include<stdio.h>
void fun1(int **iptr){
printf("%d ", **iptr); //shows value
}
void fun2(char **sptr){
//printf("%s", **sptr); shows segmentation fault
printf("%s", *sptr); //shows string
}
int main(){
char *str = "Hi";
int *x, a = 10;
x = &a;
fun1(&x);
fun2(&str);
return 0;
}
```
Can anybody explain in short what's going on?
might be silly but i asked it anyway...
|
When printing an integer, you pass the integer itself toprintf.
When printing a string of characters, you pass the address of the first character. In other words, you pass the pointer to the string.
|
Is it somehow possible to set the opacity of a of aGdkPixbufto about 50%? The thing is i am writing in Gtk2 (cannot switch to Gtk3!) a filebrowser widget (for a remote file transfer) and I want the icons of the files to be 50% transparent if the file is hidden.
I get the icon usingGFileInfoand load it into aGdkPixbuf, but I do not know how to change the opacity.
|
Transparency is handled in the alpha channel. If your pixbuf isn't transparent (check withgdk_pixbuf_get_has_alpha), you may try to callgdk_pixbuf_add_alphato add the alpha channel. Then you iterate on the pixels and set the alpha value for each pixel to 50% (i.e. 128) as gdk-pixbuf usesunpremultiplied alpha. See the documentation for a way toiterate on the pixels.
|
I don't understand the logic behind this..I expect this program to output2but it outputs3Can you explain the working of the following code:
```
#include <stdio.h>
int main()
{ int a = - -3;
printf("a=%d", a);
return 0;
}
```
|
In
```
int a = - -3;
```
this statement there is no--(decrement operator), it isunary minusoperator, which makes- -3as3(cancelling negation). Hence it prints3.
Side note, if you think of this
```
int a = --3;
```
as prints2then you thinks wrong, as this causelvalue errorbecause--applicable on variable not on constant. Correct one is
```
int a = 3;
--a ;/* this is valid,this make a as 2 now */
```
|
ERROR: type should be string, got "\nhttps://github.com/ashwinidotx/Daily-Coding-Problmes/blob/master/Operations%20with%20names.c\n\nCheck out my code, I am able to Print a sentence but the Compiler is not executing the Reverse loop;\nHere's the code snippet I am using to reverse the string.\n\n```\nfor (i=0;i<size;i++)\n reverse[i]=name[size-i-1];\n\nprintf(\"\\nReverse: \");\nfor(i=0;i!='\\0';i++)\n printf(\"%c\",reverse[i]);\n```\n" |
You are checkingi!='\0', it should bereverse[i]!='\0'
```
printf("\nReverse: ");
for(i=0;reverse[i]!='\0';i++)
printf("%c",reverse[i]);
```
|
```
#include<stdio.h>
int main()
{
for(5;2;2) printf("Hello");
return 0;
}
```
I am trying to learn C. I encountered this for-loop. When I compiled this code I got an error 'Irreducible expression tree'.
The for loop I know looks like this
```
for(i=0;i<n;i++)
```
First assigning value, then checking condition, then changing initial value.
|
The correct code would be like this...
```
#include <stdio.h> //including the library
// Main Function
int main(){
int i; // Declaring the variable
// i = 0 Initializing variable i
// i < 5, so if i >= 5 it will not execute the for loop
// i ++, increment the variable i by 1 for every loop
for(i = 0; i < 5; i++){
printf("Hello");
}
}
```
In your code, you didn't declare any variable and put some unknown things. The compiler will take it as always true and executeprintf("Hello");infinite times.
|
I have a rather odd situation where I will have multiple interfaces connected to the same network. When I receive a broadcast or multicast message, I would like to know what interface it came from. It there a way to do that in C or ideally Python?
Thanks!
|
The most obvious one would be to bind several sockets, each toone interface only- do not listen to0.0.0.0.
|
I know you can't utilize pointer arithmetic on void pointers, but could you theoretically do pointer arithmetic on pointers to void pointers, sincesizeof(void *)would yield an answer of how many bytes a pointer takes on your system?
|
Pointer arithmetic is not permitted onvoid*becausevoidis an incomplete object type.
From C Committee draft N1570:
6.5.6 Additive operators...2. For addition, either both operands shall have arithmetic type, orone operand shall be a pointer to a complete object typeand the other shall have integer type.
But it is permitted onvoid**becausevoid*is NOT an incomplete object type. It is like a pointer to a character type.
6.2.5 Types...19. Thevoid typecomprises an empty set of values;it is an incomplete object typethat cannot be completed....28.A pointer to voidshall have the same representation and alignment requirementsas a
pointer to a character type.
|
```
struct x
{
char b;
short s;
char bb;
};
int main()
{
printf("%d",sizeof(struct x));
}
```
Output is : 6
I run this code on a 32-bit compiler. the output should be 8 bytes.
My explanation--> 1. Char needs 1 bytes and the next short takes multiple of 2 so short create a padding of 1 and take 2 bytes, here 4 bytes already allocated. Now the only left char member takes 1 byte but as the memory allocates is in multiple of 4 so overall memory gives is 8 bytes.
|
The alignment requirement of a struct is that of the member with the maximum alignment. The max alignment here is forshort, so probably2. Hence, two forb, two fors, and two forbbgives 6.
|
would someone please explain the difference between
```
char *names[3]
```
and
```
char (*names)[3]
```
and how to read this operators?If I want to allocate memory for them dynamically how to do so?
For the first case, I think it's just an array ofchar*of length 3, so no memory allocation not applicable. But in second case how to do memory allocation?
|
When faced with questions like this, you can usually turn tocdecl(online versionhere):
```
cdecl> explain char *names[3]
declare names as array 3 of pointer to char
cdecl> explain char (*names)[3]
declare names as pointer to array 3 of char
```
So the former creates array of three pointers-to-char:
```
+----------+
| names[0] | -> char
| [1] | -> char
| [2] | -> char
+----------+
```
And the latter creates asinglepointer to a char array of size three.
```
+-------+
| names | -> char, char, char - no, not a dance step :-)
+-------+
```
|
I just saw something like:
```
return (m(s1 + 1, s2) || m(s1 + 1, s2 + 1));
```
What does the||mean in areturnstatement?
Here,mis a function;s1ands2are strings.
|
There's nothing special about using the||operator in areturnstatement. A statement like:
```
return <expression>;
```
is equivalent to:
```
temp = <expression>;
return temp;
```
(wheretemphas the same type as the function's return type).
So your statement is equivalent to:
```
int temp = (m(s1 + 1, s2) || m(s1 + 1, s2 + 1));
return temp;
```
|
```
""" Sample python code representing multiple assignment """
a , b = 0 , 1
print a , b
```
The following code gives output :
0 1
and obviously does not raise any error. Does C support the same?
|
No, C does not support multiple-assignment, nor has it language-level support for tuples.
```
a, b = 0, 1;
```
The above is, considering tooperator precedence, equivalent to:
```
a, (b = 0), 1;
```
Which is equivalent to:
```
b = 0;
```
Seelive on coliru.
The closest C-equivalent to your Python code would be:
```
a = 0, b = 1;
```
In this case, using the value of an assignment-expression isn't useful.
|
I am trying to understand the internal working of pipes in C. I noticed if I run
```
int main() {
system("ls | grep d | wc");
}
```
Output:
```
3 3 53
```
But on running the same command with bash I get
```
3 3 104
```
Output of ls | grep d
question_1.pdf
question_2.pdf
question_2_dataset.txt
Can someone explain the cause of this discrepancy?
The same thing occurs if I use pipe viapipe()call in C.
|
Actually I figured out problem wasn't with ls but "grep --color=always d" which is alias of grep in my bash. The colored characters have extra length which increase the length of output.
|
I'm new to kernel programming and I was making changes in a Linux Driver. I want to block/wait in a Critical Section for user input(The communication between the Driver and the user-space Application work). The Problem is that when I used wait_event_timeout() the System is being crashed and I am gettingBUG: scheduling while atomic: swapper.
Is anybody have any idea how to solve this problem and can give me some advice where to start?
|
As explainedin other questions, you are calling wait_event_timeout in a context when you already have some lock acquired (inside a critical section). In this point your process can potentially deadlock with other processes and the scheduler complains about it. Please, review the point where you are calling wait_event_timeout and check if the I/O is performed in the correct place and if you have unlocked all synchronization primitives before sending your process to sleep.
|
I have two numbers represented in a hexadecimal format:
```
uint16_t NUM = 0xEEEE; // Numerator
uint16_t DENUM = 0XFFFF; // Denominator
```
I want to have the numeric value of the division. Let us declare adoublehere:
```
double divisonResult = (double)(NUM / DENUM); // Shall be 0.9333333333333333
```
When I debug, the value ofdivisonResultis always 0.
In my case, is casting allowed or not?
Is there another way to get the wanted result?
|
The notation is a red herring: the problem is that the cast happensafterthe integer division due to your enclosing that operation in parentheses.
Use simply
```
(double)NUM / DENUM
```
although I prefer
```
1.0 * NUM / DENUM
```
not only for clarity but in case NUM is ever changed to a wider type than a double whereupon a cast could cause truncation.
|
would someone please explain the difference between
```
char *names[3]
```
and
```
char (*names)[3]
```
and how to read this operators?If I want to allocate memory for them dynamically how to do so?
For the first case, I think it's just an array ofchar*of length 3, so no memory allocation not applicable. But in second case how to do memory allocation?
|
When faced with questions like this, you can usually turn tocdecl(online versionhere):
```
cdecl> explain char *names[3]
declare names as array 3 of pointer to char
cdecl> explain char (*names)[3]
declare names as pointer to array 3 of char
```
So the former creates array of three pointers-to-char:
```
+----------+
| names[0] | -> char
| [1] | -> char
| [2] | -> char
+----------+
```
And the latter creates asinglepointer to a char array of size three.
```
+-------+
| names | -> char, char, char - no, not a dance step :-)
+-------+
```
|
I just saw something like:
```
return (m(s1 + 1, s2) || m(s1 + 1, s2 + 1));
```
What does the||mean in areturnstatement?
Here,mis a function;s1ands2are strings.
|
There's nothing special about using the||operator in areturnstatement. A statement like:
```
return <expression>;
```
is equivalent to:
```
temp = <expression>;
return temp;
```
(wheretemphas the same type as the function's return type).
So your statement is equivalent to:
```
int temp = (m(s1 + 1, s2) || m(s1 + 1, s2 + 1));
return temp;
```
|
```
""" Sample python code representing multiple assignment """
a , b = 0 , 1
print a , b
```
The following code gives output :
0 1
and obviously does not raise any error. Does C support the same?
|
No, C does not support multiple-assignment, nor has it language-level support for tuples.
```
a, b = 0, 1;
```
The above is, considering tooperator precedence, equivalent to:
```
a, (b = 0), 1;
```
Which is equivalent to:
```
b = 0;
```
Seelive on coliru.
The closest C-equivalent to your Python code would be:
```
a = 0, b = 1;
```
In this case, using the value of an assignment-expression isn't useful.
|
I am trying to understand the internal working of pipes in C. I noticed if I run
```
int main() {
system("ls | grep d | wc");
}
```
Output:
```
3 3 53
```
But on running the same command with bash I get
```
3 3 104
```
Output of ls | grep d
question_1.pdf
question_2.pdf
question_2_dataset.txt
Can someone explain the cause of this discrepancy?
The same thing occurs if I use pipe viapipe()call in C.
|
Actually I figured out problem wasn't with ls but "grep --color=always d" which is alias of grep in my bash. The colored characters have extra length which increase the length of output.
|
I'm readingModern C(versionFeb 13, 2018.) and on page 42 it says
It says that the bit with index 4 is the least significant bit. Isn't the bit with index 0 should be the least significant bit? (Same question about MSB.)
Which is right? What's the correct terminology?
|
Their definition of "most significant bit" and "least significant bit" is misleading:
```
8 bit Binary number : 1 1 1 1 0 0 0 0
Bit number 7 6 5 4 3 2 1 0
| | |
| | least significant bit
| |
| |
| least significant bit that is 1
|
most significant bit that is 1 and also just most significant bit
```
|
Consider I have structure as below.
```
struct st
{
char c;
double d;
int i;
};
```
As per memory alignment size ofstruct stwill be (1+7(padded)+8+4+4(padded))=24bytes
When I domallocas below
```
struct st *p = malloc(sizeof(*p));
```
it will be same as
```
struct st *p = malloc(13);
```
How does malloc allocates 24 bytes to meet memory alignment since we are just passing the size of structure(13bytes)?
|
The question erroneously assumes that
```
struct st *p = malloc(sizeof(*p));
```
is the same as
```
struct st *p = malloc(13);
```
It is not. To test,
```
printf ("Size of st is %d\n", sizeof (*p));
```
which prints24, not 13.
The proper way to allocate and manage structures is withsizeof(X), and not by assuming anything about how the elements are packed or aligned.
|
Consider below function:
```
void foo(int n,...);
```
I need to call this function, "optionally" passing variable arguments.
Is it possible?
Something like this:
```
foo(10, (bIsJobDone ? "OK" : xxx) );
```
I am not able to figure out what to put in place of xxx (xxx should convert to nothing) and also how to avoid "," after 10, if I don't have to pass any variable arg to foo?
Note: i can't change signature of "foo".
|
As long as you got the called function correctly prototyped and defined (not easy...),calling it with one or two parameter, depending on a condition is easy:
```
if(bIsJobDone)
{ foo(10, "OK");
} else
{ foo(10);
}
```
The alternative, to squeeze it into a ternary operator, is possible, but considered unreadable by many (just a matter of opinion of course) and not needed for the void-returning prototype you have shown in your question.
|
I am making a compiler using Flex-Yacc and I am currently trying to make a buffer system to help me implement the for and while loops. I have read the Flex manual
(here) and when I use the YY_CURRENT_BUFFER in my yacc file and I compile it, I getundefined reference to YY_CURRENT_BUFFER. How can I declare/include this in my code? I have searched a lot but I cannot seem to find it.
|
"YY_CURRENT_BUFFER" is not a variable, but a macro local to the lexer (it's not exported in the header generated bylex --header-file, and it expands to an expression using static variables (ie variables that are local to lex.yy.c, not global, not accessible from other source files).
You should wrap all the code making use of "YY_CURRENT_BUFFER" in a function in the lexer (*.l) file, put its definition in a header included in the parser (*.y) file, and use that function instead of "YY_CURRENT_BUFFER" directly.
|
I'm trying to use libuvc in one of my C/C++ projects. I succesfully compiled and installed both libusb and libuvc from source and when I attempt to compile the following code using gcc:
```
#include "libuvc/libuvc.h"
int main (int argc, const char **argv) {
uvc_init(NULL, NULL);
}
```
I get the following error:
```
Undefined symbols for architecture x86_64:
"_uvc_init", referenced from:
_main in main-de2855.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
```
I'm on MacOS High Sierra 10.13.1 x64.
|
I used the command:
```
gcc main.c -luvc -o main
```
and it worked! Adding the-luvcflag solved my problem, but I don't understand why I need to use it. I've never needed flags before when working with other C/C++ dependencies.
|
I know that the size and alignment of structures aren't always the same but is there any guarantees for the size and alignment of the integer types? For example, is the size and alignment of anintalways the same or could they be different?
To demonstrate my question, will this assertion never fail?
```
int main() {
assert(_Alignof(int) == sizeof(int));
}
```
|
Alignment and size of integer types can be different. For example onGCC x86 32-bit:
```
_Alignof(long long) == 4
sizeof(long long) == 8
```
|
This question already has answers here:What are expressions with side effects and why should they be not passed to a macro?(3 answers)Closed5 years ago.
Using define preprocessor directive why following program outputs 4 instead of 3?
```
#include <stdio.h>
#define MAX(A,B)((A)>(B)) ? A : B
int max_t(int a, int b)
{
return ((a)>(b)) ? a : b;
}
int main()
{
int i=1;
int j=2;
int val = MAX(++i, ++j); // this outputs 4 but why?
//int val = max_t(++i, ++j);
printf("%d\n", val);
return 0;
}
```
|
Macros are just replacements by tokens so
```
MAX(++i, ++j);
```
expands to
```
((++i) > (++j)) ? ++i : ++j;
```
As you see the parameters are evaluated (and incremented) twice in this case and therefore the output is4.
|
I know its possible to generate integer random number using
(rand() % (difference_between_upper_and_lower_limit)) + lower_limit
I'm wondering if theres a way to generate a number between 0.1 and 0.01.
I've trieddouble speed = (rand() % 10)/100;But it always just gives me 0.0000000;
Thanks in Advance!`
|
You can create an uniform distribution on an arbitrary interval with
```
((double)rand()/RAND_MAX)*(i_end-i_start)+i_start
```
wherei_startandi_enddenote the start and end of the interval.
In your case try
```
((double)rand()/RAND_MAX)*0.09+0.01
```
|
There are a couple nice questions addressing use of structs in the Bison%union(notablyInclude struct in the %union def with Bison/Yacc), but I think they fail to specify that, if astructwith pointers is defined, and then those pointers are used (so I have to allocate some memory for them), who's responsibility is tofree(void *)them.
Am I responsible for freeing pointers in this situation?
If a memory error occurs then how do I debug it?
|
You need to free the pointers when you're done with them. That means that in an action that runs for a reduce with those pointers, you need to do it in that action (unless you copy the pointers elsewhere that will 'own' them).
The tricky part is dealing with error recovery -- after a syntax error, bison will pop and discard items in an attempt to recover. Fortunately, bison provides the%destructordirective which can be used to clean up, freeing these pointers as they are discarded.
|
The increment operator modifies the original value like,
```
int i = 5;
i++;
printf("%d",i); //prints 6
```
but the bit operator does not, example,
```
int x = 5;
x<<1;
printf("%d",x);//should print 10 but outputs the original value i.e. 5
```
|
x << 1is analogous to operations likex * 2. If you don't store the result anywhere, it is just discarded and the line may just get omitted entirely by an optimizing compiler.
If you want to store the result of an operation like that back intox, you have options like:
```
x = x * 2;
x *= 2;
```
The<<operator is the same:
```
x = x << 1;
x <<= 1;
```
|
I've used makefile to generate file.gcc -c hello.c -o helloand fixed the permission problem through:chmod a+x ./helloHowever, when I want to execute "hello" file../hellothe system told me that "cannot execute binary file"
Can someone help me? I am looking forward your reply badly.
|
The -c argument to gcc produces an object file which you later on must link in order to produce an executable. You can not execute the object file you produced.
Instead, to compile and link at the same time, suitable when you only have 1 .c file, do
```
gcc hello.c -o hello
```
Or if you want to break it down to separate compilation and linking steps, do
```
gcc -c hello.c -o hello.o
gcc hello.o -o hello
```
|
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed5 years ago.Improve this question
```
total+=!used[str[i]-'a'];
used[str[i]-'a']=1;
```
It is the condition for checking the characters and saving the value in the variable total.
|
Thetotalvariable will contain the number ofuniquecharacters in the arraystr.
This happens because you increment the count(total+=!used[str[i]-'a']) only if you haven't already marked the character as visited. If you incremented it, you mark it as such in the next line (used[str[i]-'a']=1) so that you wont count it again.
The notationstr[i]-'a'is used to shift the ascii values of the characters from0to25(instead of97to122) so that you can spare some space in the array.
|
There was such a problem. Requires conversion of*.RAWfiles received the camera4K NDVI CAMERAforGitUp G3.
I uselibraw.h,
which containsdcraw.c. She works with theGitUp Git2camera format.
My file she does not recognize it and deduces
Unsupported file format or not RAW file
I also tried theraw2dngutility, but also there is an
Unsupported file format
Help please find a way to convert this*.RAWfile.
I attach the file (https://yadi.sk/d/sdHHY4jw3aj4Ga).
Thank you in advance!
|
The problem is solved. For this, I added support for the camera in classes libraw library:
libraw_cxx.cppdcraw_common.cppdcraw.c
Here are the parameters:
```
{24000000, 4000, 3000, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "G3DUO 4:3"},
{18016000, 4000, 2250, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "G3DUO 16:9"}
```
After that, the project was re-compiled and now dcraw_emu can convert raw to tiff for this camera!
|
This question already has answers here:What are expressions with side effects and why should they be not passed to a macro?(3 answers)Closed5 years ago.
Using define preprocessor directive why following program outputs 4 instead of 3?
```
#include <stdio.h>
#define MAX(A,B)((A)>(B)) ? A : B
int max_t(int a, int b)
{
return ((a)>(b)) ? a : b;
}
int main()
{
int i=1;
int j=2;
int val = MAX(++i, ++j); // this outputs 4 but why?
//int val = max_t(++i, ++j);
printf("%d\n", val);
return 0;
}
```
|
Macros are just replacements by tokens so
```
MAX(++i, ++j);
```
expands to
```
((++i) > (++j)) ? ++i : ++j;
```
As you see the parameters are evaluated (and incremented) twice in this case and therefore the output is4.
|
I know its possible to generate integer random number using
(rand() % (difference_between_upper_and_lower_limit)) + lower_limit
I'm wondering if theres a way to generate a number between 0.1 and 0.01.
I've trieddouble speed = (rand() % 10)/100;But it always just gives me 0.0000000;
Thanks in Advance!`
|
You can create an uniform distribution on an arbitrary interval with
```
((double)rand()/RAND_MAX)*(i_end-i_start)+i_start
```
wherei_startandi_enddenote the start and end of the interval.
In your case try
```
((double)rand()/RAND_MAX)*0.09+0.01
```
|
There are a couple nice questions addressing use of structs in the Bison%union(notablyInclude struct in the %union def with Bison/Yacc), but I think they fail to specify that, if astructwith pointers is defined, and then those pointers are used (so I have to allocate some memory for them), who's responsibility is tofree(void *)them.
Am I responsible for freeing pointers in this situation?
If a memory error occurs then how do I debug it?
|
You need to free the pointers when you're done with them. That means that in an action that runs for a reduce with those pointers, you need to do it in that action (unless you copy the pointers elsewhere that will 'own' them).
The tricky part is dealing with error recovery -- after a syntax error, bison will pop and discard items in an attempt to recover. Fortunately, bison provides the%destructordirective which can be used to clean up, freeing these pointers as they are discarded.
|
This question already has answers here:Is #if defined MACRO equivalent to #ifdef MACRO?(5 answers)Closed5 years ago.
```
#include<stdio.h>
#define MAX 0
int main()
{
#ifdef MAX
printf("MAX defined");
#endif
#if defined (MAX)
printf("MAX is defined");
#endif
return 0;
}
```
Both the#ifdefand#if definedgive the same effect then what is the difference between them? I have not seen the disassembly code of these directives if you have seen then kindly try to explain that as well.
|
The difference is historical. Originally there was only#ifdef. The newer syntax is more flexible and allows combining tests with logical conditions, but in the simple form you can use them interchangeably.
|
I need to extract the odd number out and give the output, but when I execute the code, it gives me in reverse order (e.g. expected output is1234 = 13but my code gave me31).
```
int digit, num;
while (num > 0)
{
digit = num % 10;
if(digit % 2 != 0)
{
printf("%d" , digit);
}
num /= 10;
}
```
|
That is because you are first printing the remainder from the division operation in the following statement:
```
digit = num % 10;
```
You have to store it in an array and after all the divisions are complete only print it.
|
In C, if I declare a structure like so:
```
static struct thing {
int number;
};
```
and compile it (with gcc in this case), the compiler prints this warning:
warning: 'static' ignored on this declaration[-Wmissing-declarations]
Why is this?
My intention in making the struct static would be to keepthingout of the global namespace so that another file could declare its ownthingif it wanted.
|
You cant define the storage without defining the actual object.
```
static struct thing {
int number;
}obj1,obj2;
```
is ok and:
```
struct thing {
int number;
};
static struct thing x,y;
```
|
This question already has answers here:Reading in double values with scanf in c(7 answers)Closed5 years ago.
I have a piece of code in C, which is supposed to compute the circumference.
No matter what I put in for variable Z when asked for it, it always prints0.000000
Any ideas?
```
#include <stdio.h>
int main()
{
double pi = 3.1415926;
double z = 0.0;
printf("What is the radius of the circle? \n ");
scanf("%1f", &z);
double c = 2.0 * pi * z;
printf("The circumference is %1f", c);
return 0;
}
```
|
Change%1fto%lf.
Like so:
```
#include <stdio.h>
int main()
{
double pi = 3.1415926;
double z = 0.0;
printf("What is the radius of the circle? \n ");
scanf("%lf", &z);
double c = 2.0 * pi * z;
printf("The circumference is %lf", c);
return 0;
}
```
|
I have a program where I want to run the commandwcusing execvp().
The important bits are here:
```
char *argvNew[5];
argvNew[0] = "wc";
argvNew[1] = "/home/user/foo.txt";
argvNew[2] = NULL;
execvp(argvNew[0], arvgNew);
```
This works just fine and the terminal displays the output fromwc. However, when I change the line to:
```
argvNew[1] = "~/foo.txt"
```
I get this error in the terminal:
```
wc: '~/foo.txt': No such file or directory
```
Runningwc ~/foo.txtdirectly from the terminal behaves exactly as runningwc /home/user/foo.txt. Why doesexecvphave an issue with the~/part?
|
Tilde (~) expansion is done/understood by shells only - it's not expanded in C programs. Soexecvpattempts to interpret~as part of the filename (argument towc).
What you can do is get theHOMEdirectory value usinggetenvand prefix it with the filename (e.g., usingsnprintf).
|
The size ofBITMAPFILEHEADERshould be 14 bytes, but when I run the code I get 16 bytes. I thought, it was because of padding so I added the__attribute__((packed)), but I still get 16 bytes. Why?
```
#include<stdint.h>
#include <stdio.h>
#include <stdlib.h>
typedef uint8_t BYTE;
typedef uint32_t DWORD;
typedef int32_t LONG;
typedef uint16_t WORD;
typedef struct
{
WORD bfType;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfSize;
DWORD bfOffBits;
} __attribute__((packed))
BITMAPFILEHEADER;
int main(void){
printf(" %i \n",sizeof(BITMAPFILEHEADER));
return 0;
}
```
|
A bug was reported on the same problem in GCC 4.8.1.
attribute((packed)) does not pack struct containing uint16_t with uint32_t
A comment on the bug report states that:
(attribute((packed)) doesn't work on mingw32 targets since ms-bitfields became the default).
|
```
#include <stdio.h>
int main(){
int x = 2271560481; // 0x87654321
for (size_t i = 0; i < sizeof(x); ++i) {
unsigned char byte = *((unsigned char *)&x + i);
printf("Byte %d = %u\n", i, (unsigned)byte);
}
return 0;
```
}
For example I have this code right here displaying an output of :
```
Byte 0 = 33
Byte 1 = 67
Byte 2 = 101
Byte 3 = 135
```
How do I check the condition to see if the value is stored in the address?
|
Your code is loading one byte at a time intobyte, its not a pointer so you cannot index off it. Do
```
unsigned char *bytePtr = ((unsigned char *)&x);
for (size_t i = 0; i < sizeof(x); ++i) {
printf("Byte %d = %u\n", i, bytePtr[i]);
}
```
now you can do your test function using bytePtr
|
I wonder, just like there is
printf("%s",array);
to print a whole char array, is there a way to print a whole int array with one command instead of a for cycle printing it one by one?
|
Not out of the box in standard C.
When you pass an array of any type as an argument to a function likeprintfthen it decays to a pointer to its first element, losing information about its length.
Strings stored aschararrays are special in C, since they are null-terminated. Library functions can take pointers tochararrays as parameters and increment the pointer to the null-terminator to determine its length.
If you want to create an extension ofprintfthat has a new format specifier for arrays of typeint, you will need to pass length information to it as well. It's simpler to just have a helper function that also takes the length print out the entire array using aforloop, and use that to hide the looping in the calling code.
|
What is the intention to set handle to an object as pointer-to pointer but not pointer? Like following code:
```
FT_Library library;
FT_Error error = FT_Init_FreeType( &library );
```
where
```
typedef struct FT_LibraryRec_ *FT_Library
```
so&libraryis aFT_LIBraryRec_handle of typeFT_LIBraryRec_**
|
It's a way toemulatepass by reference in C, which otherwise only have pass by value.
|
The size ofBITMAPFILEHEADERshould be 14 bytes, but when I run the code I get 16 bytes. I thought, it was because of padding so I added the__attribute__((packed)), but I still get 16 bytes. Why?
```
#include<stdint.h>
#include <stdio.h>
#include <stdlib.h>
typedef uint8_t BYTE;
typedef uint32_t DWORD;
typedef int32_t LONG;
typedef uint16_t WORD;
typedef struct
{
WORD bfType;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfSize;
DWORD bfOffBits;
} __attribute__((packed))
BITMAPFILEHEADER;
int main(void){
printf(" %i \n",sizeof(BITMAPFILEHEADER));
return 0;
}
```
|
A bug was reported on the same problem in GCC 4.8.1.
attribute((packed)) does not pack struct containing uint16_t with uint32_t
A comment on the bug report states that:
(attribute((packed)) doesn't work on mingw32 targets since ms-bitfields became the default).
|
```
#include <stdio.h>
int main(){
int x = 2271560481; // 0x87654321
for (size_t i = 0; i < sizeof(x); ++i) {
unsigned char byte = *((unsigned char *)&x + i);
printf("Byte %d = %u\n", i, (unsigned)byte);
}
return 0;
```
}
For example I have this code right here displaying an output of :
```
Byte 0 = 33
Byte 1 = 67
Byte 2 = 101
Byte 3 = 135
```
How do I check the condition to see if the value is stored in the address?
|
Your code is loading one byte at a time intobyte, its not a pointer so you cannot index off it. Do
```
unsigned char *bytePtr = ((unsigned char *)&x);
for (size_t i = 0; i < sizeof(x); ++i) {
printf("Byte %d = %u\n", i, bytePtr[i]);
}
```
now you can do your test function using bytePtr
|
I wonder, just like there is
printf("%s",array);
to print a whole char array, is there a way to print a whole int array with one command instead of a for cycle printing it one by one?
|
Not out of the box in standard C.
When you pass an array of any type as an argument to a function likeprintfthen it decays to a pointer to its first element, losing information about its length.
Strings stored aschararrays are special in C, since they are null-terminated. Library functions can take pointers tochararrays as parameters and increment the pointer to the null-terminator to determine its length.
If you want to create an extension ofprintfthat has a new format specifier for arrays of typeint, you will need to pass length information to it as well. It's simpler to just have a helper function that also takes the length print out the entire array using aforloop, and use that to hide the looping in the calling code.
|
What is the intention to set handle to an object as pointer-to pointer but not pointer? Like following code:
```
FT_Library library;
FT_Error error = FT_Init_FreeType( &library );
```
where
```
typedef struct FT_LibraryRec_ *FT_Library
```
so&libraryis aFT_LIBraryRec_handle of typeFT_LIBraryRec_**
|
It's a way toemulatepass by reference in C, which otherwise only have pass by value.
|
My code at the moment only stores the last line of a .txt file. How would I go about storing all the lines into variables to access later? Thanks
```
int main() {
FILE *ptr_fp;
char Line[600];
ptr_fp = fopen("messages.txt","r");
if(ptr_fp != NULL){
while(fgets(Line,600,ptr_fp)){
printf("%s",Line);
}
printf("\n");
}
return 0;
}
```
|
How about assign Line to a two-dimensional array and then you can access the lines later on. Here is the sample code
```
int main() {
FILE *ptr_fp;
char Line[600][600];
ptr_fp = fopen("messages.txt","r");
int i = 0;
if (ptr_fp != NULL){
while(fgets(Line[i],600,ptr_fp )&& i <600){
i++;
}
}
for (int j = 0; j < i; j++){
printf("%s",Line[j]);
}
return 0;
}
```
|
I'm struggling to find a way to generate a random number only between 20 and 30. I have this so far but its getting numbers below 20.
```
int num1 = 30;
int num2 = 20;
int num_random = rand()%num1;
while (num_random < num2){
num_random = rand()%30;
}
```
|
To get numbers between 20 and 30 use:
```
(rand() % 10) + 20
```
General formula would be:
```
(rand() % (difference_between_upper_and_lower_limit)) + lower_limit
```
The resultant of Difference between upper and lower limit will be:
```
(0, no_of_numbers_between_upper_and_lower_limit)
```
|
This question already has answers here:srand() — why call it only once?(7 answers)Closed5 years ago.
so I am trying to fill an array with random integers.
```
for (int i = 0; i < 2; i++){
srand(time(NULL));
array[i]=rand()%30; }`
```
Here is my code so far. I am currently getting the same random number twice. Would like to know if there is a way around this?
|
You seed the PRNG multiple times in the loop. It should be done only once.
By callingsrandin the loop youresetthe seed. And if you pass the same value tosrandthen the next call torandwill generate the exact same value.
|
I have a simple number division. I have this two number:
39.6548.381903173E-8
So, if I do the division on C:
```
// ...
float ii = 39.654;
double bb = 8.381903173E-8;
printf("\n%.20f\n", ii/bb);
// ...
```
The output is:473090639.56200009584426879883
But, if I work on Python3:
```
39.654/8.381903173E-8
```
The output is:473090647.5719557
If I use a calculator, indeed, the true value is that of Python3
What is wrong with my C code?
Thanks!
Regards!
|
You must compare apples to apples. In Python, all floating-point variables are of typedouble, so you should use the same data type in your C program:
```
double ii = 39.654;
double bb = 8.381903173E-8;
printf("\n%.20f\n", ii/bb);
```
|
I am reading out of a TCP-socket:
```
int read_result = recv(socket_fd, &some_struct, some_size, 0);
```
Ifread_resultwould be equal to-1, should I still callcloseon that file descriptor or just leave it?
|
According to therecvman page there are a host of reasons for whichrecvmight return-1(EAGAIN, EBADF, EINVAL, ENOMEM etc). I would suggest checkingerrnoagainst these expected return values and modifying your code to act accordingly. If you are writing a library, you might want to return an library specific error code. If you are application, you might want to perhaps die or return an error code to the caller. It would depend on the context.
The first step to solving this however, would be to understand the various error codes that can be returned and handle them accordingly.
|
Link to theProblem- LuckyFour
The code works fine on my own system, but while submitting shows wrong answer?
```
#include <stdio.h>
void main()
{
int t, n, count;
scanf("%d", &t);
while(t--)
{
count=0;
scanf("\n%d",&n);
while(n>0)
{
if(n%10==4)
{
count++;
}
n=n/10;
}
printf("\n%d", count);
}
}
```
|
I think you must write outputs in end.
and also use "%d\n" instead of "\n%d"
first change these lines and check:
```
scanf("\n%d",&n);
```
to
```
scanf("%d",&n);
```
and
```
printf("%d\n", count); // instead of \n%d
```
if dont work save results in an array and print they in another "while"
|
If there is a broken VHD chain (for example the parent VHD was modified, that's why the child no longer mounts), there's a way to fix it by using Hyper-V "Reconnect" feature. How do I do the same programmatically?
|
I think you wantAttachVirtualDisk, but I'm not sure if that's what you are after with regards to VHD chains.
|
Link to theProblem- LuckyFour
The code works fine on my own system, but while submitting shows wrong answer?
```
#include <stdio.h>
void main()
{
int t, n, count;
scanf("%d", &t);
while(t--)
{
count=0;
scanf("\n%d",&n);
while(n>0)
{
if(n%10==4)
{
count++;
}
n=n/10;
}
printf("\n%d", count);
}
}
```
|
I think you must write outputs in end.
and also use "%d\n" instead of "\n%d"
first change these lines and check:
```
scanf("\n%d",&n);
```
to
```
scanf("%d",&n);
```
and
```
printf("%d\n", count); // instead of \n%d
```
if dont work save results in an array and print they in another "while"
|
If there is a broken VHD chain (for example the parent VHD was modified, that's why the child no longer mounts), there's a way to fix it by using Hyper-V "Reconnect" feature. How do I do the same programmatically?
|
I think you wantAttachVirtualDisk, but I'm not sure if that's what you are after with regards to VHD chains.
|
I have a problem with a void pointer in use with a ternary condition operator.
In case of:
```
int x = 5;
void * pointer = &x;
printf("x: %d \n", 1 == 1 ? (*((int*)pointer)) : (*((char*)pointer)));
```
It writes to console the number 5, whitch is correct activity. But when I change in last line char to double:
```
printf("x: %d \n", 1 == 1 ? (*((int*)pointer)) : (*((double*)pointer)));
```
Then it writes 0 and I don't know why. I know I can use if-else instead of it but I'm just curious why it is working that way. Could anyone help me?
|
The result of a ternary expression is thecommon typeof the two branches. In the case of one branch being anintand the other adoublethen the result will be adoubleas well.
And you don't print adoublevalue, you attempt to print anintvalue. Mismatching format specifier and value will lead toundefined behavior.
For more information see e.g.this conditional operator reference.
|
I have tried the following code but am getting anerror:conflicting types for fun.Is there any solution that doesn't require the use of malloc.
```
#include <stdio.h>
int main()
{
printf("%s",fun());
return 0;
}
char* fun()
{
static char str[]="Hello";
return str;
}
```
|
It is because you have not declared prototype forfun.
```
#include <stdio.h>
char* fun(void);
int main()
{
printf("%s",fun());
return 0;
}
char* fun(void)
{
static char str[]="Hello";
return str;
}
```
|
I have an emebedded project that contains several images to be displayed on the screen. The images are stored in binary color in header files.
I want to use the image in two different places in the project. But including the header file in both c files causes the linking to fail since it wants to link the image twice.
how do i organize it to be linked only once?
|
First of all the header file should not contain any code or data.
In the header file just have the external declarations.
Image.h
```
extern char image[];
```
Image.c
```
char image[] = {/* image data */};
```
|
Recall the declaration of a socket in C has the following signature:
```
int socket(int domain, int type, int protocol);
```
I met some reverse-engineered code where protocol = 17. Does anyone know what protocol this refers to? The net seems to be lacking of suchintvalues; they have only the names, at best.
|
Protocol 17 would be UDP perIANA specifications, which is referred to at least in the Linuxsocketdocumentation. The name of the protocol should also be available viagetprotoentif it’s supported by the platform.
Microsoft also uses same numbers for the protocols insocket.
|
It takes in a word and a number, I can't seem to understand why the number variable won't receive the input, help please.
```
#include <stdio.h>
int main(void) {
char userWord[20];
int userNum;
scanf("%s", userWord);
printf("%s_", userWord);
scanf("%s", userNum);
printf("%d\n", userNum);
return 0;
}
```
Should be:
Input: Stop 7
Output: Stop_7
What I get:
Input: Stop 7
Output: Stop_0
|
Change
```
scanf("%s", userNum);
```
to
```
scanf("%d", &userNum);
```
|
I am using thinger.io for my project.
I send request to fetch registered devices in thinger.IO and its details by using following URL
http://{myip}/v1/users/username/devices?authorization={mytoken}
and i get the following response
```
[
{
"device":"nodemcu",
"description":"NodeMCU With ESP8266",
"connection":{
"active":true,
"ts":1486047553711
}
}
]
```
I want to convert the ts "1486047553711" to proper date time by using Javascript or with anything possible.
As I am beginner inthinger.io. Its getting hard for me to understand their document.
Any help.
|
The number 1486047553711 is the date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. You can convert it to javascript date by passing it in the constructor.
For example
```
new Date(1486047553711);
```
|
I'm currently writing a Blackjack simulator, and I'm generating n decks of cards to play with:
```
int i;
int value = 1;
for (i = 0; i < deck->n_cards; i++) {
deck->cards[i] = value;
value++;
if (value == 14) value = 1;
}
```
(deck->n_cards % 52 == 0)
I tried an approach to write the same with modulo operations, but I can't get it away using more than 1 deck. I think that using that if is really ugly. Is there a more elegant solution to this?
|
I'm not familiar with Blackjack play, however I understand from your code, the values range is 1 to 13.
Try this code:
```
int i;
for (i = 0; i < deck->n_cards; i++) {
deck->cards[i] = (i % 13) + 1;
}
```
i%13 range is 0 to 12, adding one to this, makes this range 1 to 13
|
I was curious and find out the current piece of code does not work however I can not figure out why:
```
#include <stdio.h>
void main(){
int a = 42;
printf("%d\n", ++a++);
}
```
It does not seem like a wrong syntax to me. Could somebody explain the error output?
```
first.c: In function ‘main’:
first.c:5:17: error: lvalue required as increment operand
printf("%d\n", ++a++);
```
|
++a++is equal to++(a++)(because ofoperator precedence), and the value returned bya++is anon-lvalue object expression(also known asrvalues).
Such values are (in essence) ephemeral and can not be modified by the prefix++operator.
|
Recall the declaration of a socket in C has the following signature:
```
int socket(int domain, int type, int protocol);
```
I met some reverse-engineered code where protocol = 17. Does anyone know what protocol this refers to? The net seems to be lacking of suchintvalues; they have only the names, at best.
|
Protocol 17 would be UDP perIANA specifications, which is referred to at least in the Linuxsocketdocumentation. The name of the protocol should also be available viagetprotoentif it’s supported by the platform.
Microsoft also uses same numbers for the protocols insocket.
|
It takes in a word and a number, I can't seem to understand why the number variable won't receive the input, help please.
```
#include <stdio.h>
int main(void) {
char userWord[20];
int userNum;
scanf("%s", userWord);
printf("%s_", userWord);
scanf("%s", userNum);
printf("%d\n", userNum);
return 0;
}
```
Should be:
Input: Stop 7
Output: Stop_7
What I get:
Input: Stop 7
Output: Stop_0
|
Change
```
scanf("%s", userNum);
```
to
```
scanf("%d", &userNum);
```
|
I am using thinger.io for my project.
I send request to fetch registered devices in thinger.IO and its details by using following URL
http://{myip}/v1/users/username/devices?authorization={mytoken}
and i get the following response
```
[
{
"device":"nodemcu",
"description":"NodeMCU With ESP8266",
"connection":{
"active":true,
"ts":1486047553711
}
}
]
```
I want to convert the ts "1486047553711" to proper date time by using Javascript or with anything possible.
As I am beginner inthinger.io. Its getting hard for me to understand their document.
Any help.
|
The number 1486047553711 is the date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. You can convert it to javascript date by passing it in the constructor.
For example
```
new Date(1486047553711);
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.