question
stringlengths
25
894
answer
stringlengths
4
863
I have following code in packet sniffer: ``` struct ip_header { unsigned char ip_ver:4; ... }; ... printf("Version: %i\n", (int)ip_hdr->ip_ver) ``` The output of ths is "Version: 5". I think version can onl be 4 or 6, right?
I got it it is just the Header length first 4 bits and version is second 4bits, so it should be ``` struct ip_header { unsigned char ip_hl:4; unsigned char ip_ver:4; ... }; ```
I am a newbie in C progrmming and I have looked at the following code: ``` struct iphdr *iph = (struct iphdr *)Buffer; ``` What does the expression mean? here is the link to the codehttp://www.binarytides.com/packet-sniffer-code-c-linux/
It castsbufferto a pointer tostruct iphdrand then initializesiphto that pointer. This is used becausebufferis a pointer to a buffer of raw bytes, but in this function it is known that the bytes stored in the buffer follow the format of astruct iphdr. Hence thestruct iphdrcan be used to access the contents of the buffe...
I'm new to c. Is there any simple way to redirect all the console's output (printfs etc.) to a file using some general command line \ linkage parameter (without having to modify any of the original code)? If so what is the procedure?
Use shell output redirection your-command > outputfile.txt The standard error will still be output to the console. If you don't want that, use: your-command > outputfile.txt 2>&1 or your-command &> outputfile.txt You should also look into theteeutility, which can make it redirect to two places at once.
This function which I received from a third party contains the following code which does not compile in MS Visual Studio 10. I think there is a casting problem but do not know how to fix this. ``` void dump_ffmpeg_pad16(FILE *stream, uint32_t timestamp, void *data, int data_size) { unsigned int...
``` void *end = data + data_size; ``` Should be: ``` void *end = ((char *) data) + data_size; ``` Adding to avoid*is a GCC extension.
This is my code: ``` struct bacchetta { bool in_uso; }; int main() { key_t key; if ((key = ftok(".", 'a')) == -1) { perror("ftok"); exit(1); } int shmid; if ((shmid = semget(key, sizeof(struct bacchetta)*5, 0600 | IPC_CREAT )) == -1) { perror("Errore creazione dell'area di memoria per le ba...
You need to callshmget, notsemget.
I have downloadedopenssh-6.4p1for Linux and I want to compile it usingclanginstead ofgcc. How can I tell the compilation engine to do this? Do I need to modifyconfigure?
You can try to use the option command like this: ``` option(USE_CLANG "build application with clang" ON) # OFF is the default ``` and then you can wrap the clang-compiler settings in the if() condition like this: ``` if(USE_CLANG) SET (...) //... endif(USE_CLANG) ```
The header file is in the same folder as the other files, it's #include'ed and all, but some reason the other source files just can't find it. Same with compiler. Help?
May be you should try#include "funcs.h"instead of#include <funcs.h>
Iss1=s2valid statement? It give me error: lvalue required My code: ``` #include<stdio.h> #include<conio.h> void main() { char s[1]="integ"; char s[2]="systems"; s1=s2; printf("%s", s1); getch(); } ```
You haven't defined a variable calleds2. You have two variables,s1, ands. Also, you can't assign character arrays like that. Declare them as pointers if you need to change the array the variable points to after initialization, or else usestrcpy()to copy one string's contents into another (being careful about overflow ...
This question already has answers here:Strange behaviour of macros C/C++(5 answers)Closed9 years ago. Why do I get 27? Can't#definetake executable statement 5+2? ``` #include<stdio.h> #include<conio.h> #define x 5+2 void main() { int i; i=x*x*x; printf("%d",i): getch(); } ``` Output: 27 I should g...
First, this isnotan executable statement, it is anexpression. An no, it shouldn't be 343, because the expression is not parenthesized. Because of that, multiplication takes precedence over addition, so the expression being evaluated is ``` 5+2*5+2*5+2 ``` which is ``` 5+(2*5)+(2*5)+2 = 27 ``` This little example i...
The following code works fine in user mode: ``` #include <stdio.h> #include <ctype.h> int main() { // // 0x7f51 is the unicode code of Chinese character '网' // int n = tolower(0x7f51); // n will equal 0x7f51 } ``` However, if we are in kernel mode,nwill equal0x7f71!!! The simplest sample code: ```...
tolower(int c)is defined only for integersc, that are EOF or representable as an unsigned char.0x7f51is neither. Therefore, the behaviour oftolower(0x7f51)is undefined.
I have this typedef struct and a "constructor": ``` typedef struct database { char key; char value; struct database *next; } Database; Database db_createDb() { Database *db; db = malloc(sizeof(struct database)); return *db; } ``` And I am making a call from the main function: ``` int main...
ChangedatabasebyDatabase, and keep pointer for later free: ``` Database * db_createDb() { Database *db; db = (Database *)malloc(sizeof(Database)); return db; } int main(int argc, char *argv[]) { Database * database = db_createDb(); .... free(database); } ```
``` #include <stdio.h> /* replacing tabs and backspaces with visible characters */ int main() { int c; while ( (c = getchar() ) != EOF) { if ( c == '\t') printf("\\t"); else if ( c == '\b') printf("\\b"); else if ( c == '\\') printf("\\\\"); else ...
Run the program and enterCtrlH. The key-code send by thebackspacekey (also: <---)is most probably eaten by the shell. This depends on how the terminal is configured. Read here for details:http://www.tldp.org/HOWTO/Keyboard-and-Console-HOWTO-5.html
I need some help to understand the following piece of C code : Lets say I have a structure as : ``` typedef struct { char *letter; int dataSize; int Number; }Page; ``` then : I have in the same code the following line , assume x is a defined variable : ``` Page *window[x], *it = 0 ; ``` I am wondering ...
The*means "pointer". You should know this, if you are writing C code. Otherwise you really need to get some basic tutorial or introductory text. In your code, the struct field meansletteris of typechar *, i.e. it's a pointer to character data. The second one means thatwindowis an array ofxvalues of typePage *, and t...
This question already has answers here:Calling an executable program using awk(10 answers)Closed9 years ago. I want to call Code.c from within awk. Note that the Code.c takes current record (i.e. $0) as argument. I am new to shell scripting so any help would be appreciated. Best Regards
``` #!/bin/bash while read line do para=`echo $line | awk '{print $0}'` ./c_code $para done < your_process_file ```
what I want to do is open a file(which is huge) and read from a certain point of bytes to an offset. in c# this can be done with: ``` File.ReadAllBytes(file).Skip(50).Take(10).ToArray(); ``` the problem with this is that it reads the entire file but since my files can be huges this also takes a long time. is there ...
Yes, use thefseek()standard library function to move ("seek") to the desired position: ``` FILE *in = fopen("myfancyfile.dat", "rb"); if(fseek(in, 50, SEEK_SET) == 0) { char buf[10]; if(fread(buf, sizeof buf, 1, in) == 1) { /* got the data, process it here */ } } fclose(in); ```
At C language: I have a father that make two sons at a loop byfork(), I want that each son will have (at pid_t type) the process ID of his brother. I try do this via pipe but I didn't success. Do you have any idea how can I do this? I did this via(write(pos[1],getpid(),sizeof(pid_t))(this son send to his brother hi...
Write needs a pointer to the data to write.getpidreturns a process id, not a pointer to a process id. You need to store the return value fromgetpidin variable: ``` pid_t pid = getpid(); write(pos[1], &pid, sizeof(pid_t); ``` I am assuming that pos[1] holds the file descriptor of the pipe to the sibling.
I'm compiling a .c program using gcc compiler on linux, But , i received the error shown as "error: lvalue required as left operand of assignment" The error is due to the line of code as shown below ``` (socklen_t*)saddr_size=*(data2.ssize); ``` May I know how to debug this problem ? They are declared in the stru...
Your code is nonsensical. Try ``` saddr_size = (int)(*data2.ssize); ``` But ... why is saddr_size declared int? Try ``` socklen_t saddr_size; ... saddr_size = *data2.ssize; ``` I also wonder why ssize is a pointer, rather that the size itself.
This question already has answers here:sequence points in c(4 answers)Closed9 years ago. My code is : ``` #include<stdio.h> int main() { char c='8'; int d=8; printf("%d %d %d",d,d+=c>='0'&&c<='9',c++); return(0); } ``` The output of this question is : 9 9 56. I'm unable to understand this. Please so...
You are observing undefined behaviour.dis passed as an argument twice, and once with side effects. If done in sequence your code should be equivalent to ``` char c='8'; int d=8; printf("%d",d); d+= (c>='0)' && (c<='9'); printf(" %d", d); printf(" %d",c); c++; ``` But since it is undefined in what order the argument...
The following code works fine in user mode: ``` #include <stdio.h> #include <ctype.h> int main() { // // 0x7f51 is the unicode code of Chinese character '网' // int n = tolower(0x7f51); // n will equal 0x7f51 } ``` However, if we are in kernel mode,nwill equal0x7f71!!! The simplest sample code: ```...
tolower(int c)is defined only for integersc, that are EOF or representable as an unsigned char.0x7f51is neither. Therefore, the behaviour oftolower(0x7f51)is undefined.
I have this typedef struct and a "constructor": ``` typedef struct database { char key; char value; struct database *next; } Database; Database db_createDb() { Database *db; db = malloc(sizeof(struct database)); return *db; } ``` And I am making a call from the main function: ``` int main...
ChangedatabasebyDatabase, and keep pointer for later free: ``` Database * db_createDb() { Database *db; db = (Database *)malloc(sizeof(Database)); return db; } int main(int argc, char *argv[]) { Database * database = db_createDb(); .... free(database); } ```
``` #include <stdio.h> /* replacing tabs and backspaces with visible characters */ int main() { int c; while ( (c = getchar() ) != EOF) { if ( c == '\t') printf("\\t"); else if ( c == '\b') printf("\\b"); else if ( c == '\\') printf("\\\\"); else ...
Run the program and enterCtrlH. The key-code send by thebackspacekey (also: <---)is most probably eaten by the shell. This depends on how the terminal is configured. Read here for details:http://www.tldp.org/HOWTO/Keyboard-and-Console-HOWTO-5.html
I need some help to understand the following piece of C code : Lets say I have a structure as : ``` typedef struct { char *letter; int dataSize; int Number; }Page; ``` then : I have in the same code the following line , assume x is a defined variable : ``` Page *window[x], *it = 0 ; ``` I am wondering ...
The*means "pointer". You should know this, if you are writing C code. Otherwise you really need to get some basic tutorial or introductory text. In your code, the struct field meansletteris of typechar *, i.e. it's a pointer to character data. The second one means thatwindowis an array ofxvalues of typePage *, and t...
This question already has answers here:Calling an executable program using awk(10 answers)Closed9 years ago. I want to call Code.c from within awk. Note that the Code.c takes current record (i.e. $0) as argument. I am new to shell scripting so any help would be appreciated. Best Regards
``` #!/bin/bash while read line do para=`echo $line | awk '{print $0}'` ./c_code $para done < your_process_file ```
what I want to do is open a file(which is huge) and read from a certain point of bytes to an offset. in c# this can be done with: ``` File.ReadAllBytes(file).Skip(50).Take(10).ToArray(); ``` the problem with this is that it reads the entire file but since my files can be huges this also takes a long time. is there ...
Yes, use thefseek()standard library function to move ("seek") to the desired position: ``` FILE *in = fopen("myfancyfile.dat", "rb"); if(fseek(in, 50, SEEK_SET) == 0) { char buf[10]; if(fread(buf, sizeof buf, 1, in) == 1) { /* got the data, process it here */ } } fclose(in); ```
I have a dll (ansi c) that has some string litarals defined. ``` __declspec(dllexport) char* GetSomeString() { return "This is a test string from TestLib.dll"; } ``` When compiled this string is still visible in "notepad" for example. I'm fairly new to C, so I was wondering, is there a way to safely store string...
Don't put your secrets on anyone else's computer if you want them to stay secret. See my related answer,The #1 Law of Software Licensing AndEric Lippert's similar answer
I wanted to know how can I check if the value -1 returned ofgetpriority()is an error or a legitimate value. From the manual: RETURN VALUESince getpriority() can legitimately return the value -1, it is neces- sary to clear the external variable errno prior to the call, then check it afterwards to determine if...
Do what it says! Clear the value of errno, then call, then do your check. ``` #include <errno.h> #include <sys/time.h> #include <sys/resource.h> errno = 0; int val = getpriority(); if (val == -1 && errno) { // we have an error! } ```
I am trying to understand the concept of struct and typedef in C. SO i created this simple program, but for some reason it is not working. ``` #include <stdio.h> #include <stdlib.h> typedef struct testT{ int number; } testT; int main() { testT.number=10; printf("%d", testT->number); } ``` However, i...
testTis a type, just likeint, you need to use a variable: ``` testT t; t.number=10; printf("%d", t.number); ``` Also note that you should use dot operator.because the arrow operator->is used on a pointer tostruct.
So I wrote a POSIX Threads application in C (linux) in which you get as command line args the number of threads , and the filename which the threads will work on.It works. Now I also need to make it work in windows. I've changed all the necessary names and headers , but since I'm trying to do it in VS2012 , I don't ...
You can useOutputDebugStringfunction, but the VS output window should work only for debugger output. For console output, you should createWindows 32 Console Applicationproject. Other way is to allocate console yourself: ``` AllocConsole(); freopen("CONIN$", "r",stdin); freopen("CONOUT$", "w",stdout); freopen("CONOUT...
I want to check if the value that the user entered is integer number (I mean an integer, not a number as character (like char)).I have usedisdigitfunction, andis...sisters, but does not work good. For example: ``` int digits = 220; // Or scanf("%d", digits); Or any way to take the input from user if(digits == `inte...
``` int digits = 220; // Or scanf("%d", &digits); ``` That's it. You are done! Or, rather, ifscanf("%d", &digits)returns1then an integer has been successfully read and stored in digits. Note the the declarationint digitsensures that only integer values can be stored indigits. So: ``` int digits; if (scanf("%d", ...
I have a source file where a typedef struct is defined: ``` typedef struct node { char *key; char *value; struct node *next; } *Node; ``` In this module, there are some functions that operate on a Node and have Node as return type. What am I supposed to write in the header file for this typedef? Is it c...
You can use: ``` typedef struct node * Node; ``` But I would advise against hiding the pointer in type declaration. It is more informative to have that information in variable declaration. module.c: ``` #include "module.h" struct node { char *key; char *value; struct node *next; }; ``` module.h: ``` ...
I have a dll (ansi c) that has some string litarals defined. ``` __declspec(dllexport) char* GetSomeString() { return "This is a test string from TestLib.dll"; } ``` When compiled this string is still visible in "notepad" for example. I'm fairly new to C, so I was wondering, is there a way to safely store string...
Don't put your secrets on anyone else's computer if you want them to stay secret. See my related answer,The #1 Law of Software Licensing AndEric Lippert's similar answer
I wanted to know how can I check if the value -1 returned ofgetpriority()is an error or a legitimate value. From the manual: RETURN VALUESince getpriority() can legitimately return the value -1, it is neces- sary to clear the external variable errno prior to the call, then check it afterwards to determine if...
Do what it says! Clear the value of errno, then call, then do your check. ``` #include <errno.h> #include <sys/time.h> #include <sys/resource.h> errno = 0; int val = getpriority(); if (val == -1 && errno) { // we have an error! } ```
I am trying to understand the concept of struct and typedef in C. SO i created this simple program, but for some reason it is not working. ``` #include <stdio.h> #include <stdlib.h> typedef struct testT{ int number; } testT; int main() { testT.number=10; printf("%d", testT->number); } ``` However, i...
testTis a type, just likeint, you need to use a variable: ``` testT t; t.number=10; printf("%d", t.number); ``` Also note that you should use dot operator.because the arrow operator->is used on a pointer tostruct.
So I wrote a POSIX Threads application in C (linux) in which you get as command line args the number of threads , and the filename which the threads will work on.It works. Now I also need to make it work in windows. I've changed all the necessary names and headers , but since I'm trying to do it in VS2012 , I don't ...
You can useOutputDebugStringfunction, but the VS output window should work only for debugger output. For console output, you should createWindows 32 Console Applicationproject. Other way is to allocate console yourself: ``` AllocConsole(); freopen("CONIN$", "r",stdin); freopen("CONOUT$", "w",stdout); freopen("CONOUT...
I want to check if the value that the user entered is integer number (I mean an integer, not a number as character (like char)).I have usedisdigitfunction, andis...sisters, but does not work good. For example: ``` int digits = 220; // Or scanf("%d", digits); Or any way to take the input from user if(digits == `inte...
``` int digits = 220; // Or scanf("%d", &digits); ``` That's it. You are done! Or, rather, ifscanf("%d", &digits)returns1then an integer has been successfully read and stored in digits. Note the the declarationint digitsensures that only integer values can be stored indigits. So: ``` int digits; if (scanf("%d", ...
I have a source file where a typedef struct is defined: ``` typedef struct node { char *key; char *value; struct node *next; } *Node; ``` In this module, there are some functions that operate on a Node and have Node as return type. What am I supposed to write in the header file for this typedef? Is it c...
You can use: ``` typedef struct node * Node; ``` But I would advise against hiding the pointer in type declaration. It is more informative to have that information in variable declaration. module.c: ``` #include "module.h" struct node { char *key; char *value; struct node *next; }; ``` module.h: ``` ...
I'm trying to understand a c code, (SimpleScalar, bpred.c), there is the thing that confuses me a lot: ``` int *shiftregs; shiftregs = calloc(1, sizeof(int)); int l1index, l2index; l1index = 0; l2index = shiftregs[l1index]; ``` I delete some code that might not help. After thecalloccall,*shiftregsb...
Sinceshiftregsis a pointer to anint,*shiftregsis anint. Sincecallocguarantees that the memory it allocates is set to0, and you've allocated enough memory to refer toshiftregs[0],l2indexwill be0(assumingcallocdidn't fail and returnNULL).
If I have the code on a 32-bit word machine: ``` struct myStruct { //structure that occupies six bytes uint32_t value1; uint16_t value2; } *p = (myStruct *)0x10; ``` How much does p++ equal? 0x14? 0x11? or 0x16?
It is incremented by the sizeof(myStruct). Pointer arithmetic is in units of the size of what is pointed at. for char *, p++; p = p + sizeof(char);
I'm pretty new to Makefiles in C. I am trying to figure out where I would put -lpthread in my makefile so I can implement posix threads in my C program. Below is my Makefile, thanks in advance. ``` CFLAGS = -g -Wall LDFLAGS = CC = gcc LD = gcc TARG1 = calc OBJS1 = calc.o $(TARG1): $(OBJS1) $(LD)...
I would recommend not using-l. Instead give GCC-pthreadon both the CFLAGS and LDFLAGS variables. This will make sure that preprocessor defines are properly set during the compile and it will link the correct libraries. This assumes GCC of course. If using Intel icc or LLVM check for the right parameters.
``` uint32_t var32; uint8_t var8; var32 = 0xFEEDABCD; var8 = 0; var8 = var32; ``` Will the above code always (meaning platform dependent such as Windows vs Linux etc) have the following values: var32 = 0xFEEDABCD var8 = 0xCD
Yes, it will. Unsigned integer overflow is well-defined by the standard and it is required to follow modulo-2^nsemantics.
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.Closed9 years ago.Improve this question From what i understand i need to use the the strtok function but i have no idea what to d...
I would usestrtokto split the input string into words. Then, I will add each word to ahashtable: the keys would be the words, and the values would be the word's first occurrence position. When inserting a new word into thehashtable, if the world is already there, then I'd compute the distance between the current posit...
So in my c file I have a variable: ``` static int32_t currentAddress = 0x00000000; ``` I was wondering if I use currentAddress to set fields within say struct A as 0. Then say I increment currentAddress elsewhere, will the field within A also change? Basically I don't understand what static does in this case and w...
The field within A will get the current value of currentAddress, which is 0. Changing currentAddress later won't affect the field of A unless you assign the field with currentAddress again, at which point the field of A will have the new value of currentAddress. Thestaticdeclarator sets the scope and lifetime of the ...
I'm working on a code that combines nibbles. I got one working where I combine two nibbles. However, I also need to combine three nibbles into one 12 bit. Does anyone know how to do this? Thanks! example: nibble 1: F nibble 2: 1 nibble 3: 3 The result is F31. EDIT: As others have requested, this is my two nibble...
``` int8u nibble1 = 0xF; int8u nibble2 = 0x1; int8u nibble3 = 0x3; int16u combined; combined = (nibble1 << 8) | (nibble2) | (nibble3 << 4); ```
In C Language i'm creating a array ( 2 Dimensional ) in which all the elements are zeros I do it the following way : ``` int a[5][5],i,j; //a is the required array for(i=0;i<5;i++) for(j=0;j<5;j++) a[i][j]=0; ``` I know some other way also : ``` int a[5][5]={0}; ``` Are both the same or is there any di...
The second method is more concise. Also consider: ``` memset(&a, 0, sizeof(a)); ```
Shouldn't 0x00000100 = 4. I understand that 0x00000001 = 1 since 2^0 and 0x00000010 = 2 since 2^1. What is wrong with my thinking? ``` initVariable(&variable1, "variable1", "1, 2, 3", 0x00000100); assertIntegerEquals(variable1.address, 4); // 0x00000100 = 4? ``` My assertion fails because it says that 256 != 4
Numbers that begin with0xare interpreted as hexadecimal (base 16) in C. So0x10 == 16, and0x100 == 256,0x10000 == 65536, etc. Powers of two are: 20= 0x121= 0x222= 0x423= 0x824= 0x1025= 0x2026= 0x4027= 0x8028= 0x100
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.Closed9 years ago.Improve this question From what i understand i need to use the the strtok function but i have no idea what to d...
I would usestrtokto split the input string into words. Then, I will add each word to ahashtable: the keys would be the words, and the values would be the word's first occurrence position. When inserting a new word into thehashtable, if the world is already there, then I'd compute the distance between the current posit...
So in my c file I have a variable: ``` static int32_t currentAddress = 0x00000000; ``` I was wondering if I use currentAddress to set fields within say struct A as 0. Then say I increment currentAddress elsewhere, will the field within A also change? Basically I don't understand what static does in this case and w...
The field within A will get the current value of currentAddress, which is 0. Changing currentAddress later won't affect the field of A unless you assign the field with currentAddress again, at which point the field of A will have the new value of currentAddress. Thestaticdeclarator sets the scope and lifetime of the ...
I'm working on a code that combines nibbles. I got one working where I combine two nibbles. However, I also need to combine three nibbles into one 12 bit. Does anyone know how to do this? Thanks! example: nibble 1: F nibble 2: 1 nibble 3: 3 The result is F31. EDIT: As others have requested, this is my two nibble...
``` int8u nibble1 = 0xF; int8u nibble2 = 0x1; int8u nibble3 = 0x3; int16u combined; combined = (nibble1 << 8) | (nibble2) | (nibble3 << 4); ```
In C Language i'm creating a array ( 2 Dimensional ) in which all the elements are zeros I do it the following way : ``` int a[5][5],i,j; //a is the required array for(i=0;i<5;i++) for(j=0;j<5;j++) a[i][j]=0; ``` I know some other way also : ``` int a[5][5]={0}; ``` Are both the same or is there any di...
The second method is more concise. Also consider: ``` memset(&a, 0, sizeof(a)); ```
Shouldn't 0x00000100 = 4. I understand that 0x00000001 = 1 since 2^0 and 0x00000010 = 2 since 2^1. What is wrong with my thinking? ``` initVariable(&variable1, "variable1", "1, 2, 3", 0x00000100); assertIntegerEquals(variable1.address, 4); // 0x00000100 = 4? ``` My assertion fails because it says that 256 != 4
Numbers that begin with0xare interpreted as hexadecimal (base 16) in C. So0x10 == 16, and0x100 == 256,0x10000 == 65536, etc. Powers of two are: 20= 0x121= 0x222= 0x423= 0x824= 0x1025= 0x2026= 0x4027= 0x8028= 0x100
I'm working on a code that combines nibbles. I got one working where I combine two nibbles. However, I also need to combine three nibbles into one 12 bit. Does anyone know how to do this? Thanks! example: nibble 1: F nibble 2: 1 nibble 3: 3 The result is F31. EDIT: As others have requested, this is my two nibble...
``` int8u nibble1 = 0xF; int8u nibble2 = 0x1; int8u nibble3 = 0x3; int16u combined; combined = (nibble1 << 8) | (nibble2) | (nibble3 << 4); ```
In C Language i'm creating a array ( 2 Dimensional ) in which all the elements are zeros I do it the following way : ``` int a[5][5],i,j; //a is the required array for(i=0;i<5;i++) for(j=0;j<5;j++) a[i][j]=0; ``` I know some other way also : ``` int a[5][5]={0}; ``` Are both the same or is there any di...
The second method is more concise. Also consider: ``` memset(&a, 0, sizeof(a)); ```
Shouldn't 0x00000100 = 4. I understand that 0x00000001 = 1 since 2^0 and 0x00000010 = 2 since 2^1. What is wrong with my thinking? ``` initVariable(&variable1, "variable1", "1, 2, 3", 0x00000100); assertIntegerEquals(variable1.address, 4); // 0x00000100 = 4? ``` My assertion fails because it says that 256 != 4
Numbers that begin with0xare interpreted as hexadecimal (base 16) in C. So0x10 == 16, and0x100 == 256,0x10000 == 65536, etc. Powers of two are: 20= 0x121= 0x222= 0x423= 0x824= 0x1025= 0x2026= 0x4027= 0x8028= 0x100
I know about the difference between betweenreturnvsexit().I want to know how they are different fromFreeConsole(). FreeConsole()is an API Function(scope: main function) returnis a statement in C.exit (EXIT_SUCCESS)is a function call. Which would you like to use in C to exit a program and why?
In C, callingexitis equivalent to returning frommain. In C++, callingexitwill bypass stack unwinding, so destructors will not be invoked properly (IOW, you almost always want to avoid it). FreeConsolefrees a console without exiting the program. The process can continue to execute detached after freeing the console. ...
if I need to rename a function or a variable on Eclipse I can just right-click on it and refactor->rename This does not seem to work for Macro. Is there a way of doing itwithoutusing another external tool or command? System: Eclipse Standard/SDK Version: Kepler Release Build id: 20130606-0932 OS: ubuntu 12.04
I don't think Eclipse supports Macro refactoring since implementing a feature such as renaming a function is easier than implementing the same thing for, say a macro. I also looked at the Eclipsedocumentationand the rename action does not seem to have support for Macros.
I've wrote a small C program, which takes 3 integers as arguments. If I am running it like this:myapp 1 2 3runs fine,argcshows correctly 4, but if I do:echo 1 2 3 | myapp, argc shows just 1. The relevant part of the C code is: ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char **...
echo 1 2 3 | myappcallsmyappwith no arguments. Values are passed throughstdin. You may want to use this instead (if using bash in Unix): ``` myapp `echo 1 2 3` ``` Or, if you have a list of numbers in a file called numbers.txt, you can do this as well: ``` myapp `cat numbers.txt` ```
I'm seeing some code like this: ``` int foo() { int sz = call_other_func(); char array[sz]; /* whatever */ } ``` I'm baffled at how this would work and even compile withgcc. The size of the array is supposed to bestaticand determined at compile time, no?
This type of arrays are calledvariable length arrays(you would also like to raed:Arrays of Variable Length - GCC) and are allowed in C99 only. By using VLAs, the size of the array can be determine at runtime.
I know how arrays stored on the heap. But how are arrays stored on the stack? Is the complete array pushed to the stack?
Arrays are stored the same no matter where they are. It doesn't matter if they are declared as local variables, global variables, or allocated dynamically off the heap. The only thing that differs iswherethey are stored.
I'm trying to figure out a way to split a byte into two (eg.F8toFand8) to be later recombined with other bytes. I read up on bit masking but I still don't quite understand it. This is what I'm trying to do. F8 FF FF- Split the bytes into two. I'll use variables to distinguish the bytes u=F,v=8,w=F,x=F,y=F,z=F, which...
If you have a variablexwith a value known to fit into one byte, you can split it into twonibbles like this: ``` x_lo = x & 0xf; x_hi = (x >> 4) & 0xf; ``` To combine twonibblesy_loandy_hiinto one byte you shift and or: ``` y = y_lo | (y_hi << 4); ```
I can read a LTO Tape without problem in C#. There is also a Cartridge Memory (LTO-CM) in each cartridge.http://en.wikipedia.org/wiki/Linear_Tape-Open How can I read/write some bytes in this chip in C#, or C?
There's this project in C:https://github.com/scangeo/lto-cm It is made to read and write the "text attribute" that is supposed to be used by applications or users. Most of the other fields are reserved for the drive and tape vendors and manufacturers. It uses the reader integrated in the tape drives through SCSI com...
I have the following Code ``` #ifdef ENV_TI typedef struct timespecT { Uint32 tv_sec; Uint32 tv_nsec; }timespec; #endif #ifndef ENV_TI struct timespec currentTime; // This Line #else timespec currentTime; #endif ``` How is thecurrentTimeaccessible if i have NOT definedENV_TIflag and the timespec is defined...
struct timespecis a type name used in e.g. Linux, seethe manual page forclock_gettime(). You get the type declaration by doing#include <time.h>on systems that support it. According to the manual page, this is POSIX standard functionality. I think the code you're looking at is using the#ifdefto declare the type for en...
I don't understand why output is a strange number when I run my code: ``` int main(int argc, char** argv) { Mat im; im = imread("lena.png", CV_LOAD_IMAGE_GRAYSCALE); cout << im.at<uchar>(0, 0) << endl; waitKey(0); } ``` If I visualize image I see the correct image. Where am I wrong?
Because it shows the symbol, likecout << char(123) << endl; You have to use int cast: ``` cout << (int) im.at<uchar>(0, 0) << endl; ```
After compiling my code in C, I use “time ./main” from the terminal (Mac OS X) and get ``` real 0m0.004s user 0m0.001s sys 0m0.002s ``` But using<time.h>as describedhere, I get an elapsed time of0.000217seconds. So I’m just wondering how these two measurements differ.
time ./exewill measure more things - loading the exe, starting the program, finishing the program, etc. These are a lot of things, especially of there are loading of dynamic libraries and things like this. Usingtime.hyou can measure the time from linexto liney- this willnotinclude anything else (like startup time, et...
I have a program that prints five prime numbers within a user input range(m,n). My problem is i want to print numbers greater than m. and print only next five numbers. I don't want to use upper limit.How can I do it so? ``` #include <stdio.h> #include <conio.h> int main() { int m,n,i,j,k,flag; printf("\nEnter T...
Why not simply count the number of primes you have printed? int count = 0; : for(i=m ; (i<=n) && (count<5) ; i++) : if(flag) { printf("%3d \n",i); count++; } PS, using longer names than single characters will help make your program more understandable.
I originally had this in my makefile: ``` all: gcc myFunctions1.h myFunctions1.c myFunctions2.h myFunctions2.c main.c -o main ``` which worked for some reason until I restarted the terminal. Now I get this error: ``` clang: error: cannot specify -o when generating multiple output files ``` So what's the proper...
You don't specify header files when compiling. You don't need to as they are included in the source files, and can't be used by themselves. You might also want to learn abouttranslation units, and how they relate to source and header files.
Suppose we have definedUp(),Down()andPeek()operations for semaphore and thePeek()operation returns the semaphore's value. What are pros and cons ofPeek()operation? How can I effectively usePeek()operation?
Apeekfunction is useless for synchronisation. It only allows to see the current state, but no actions should be taken, because immediately after the peek, the semaphore can already be changed. It could be used for monitoring to solve deadlocks, but this is very tricky. As mentioned in the comments, it can help with...
I know how to set pixels to "Console Windows" by using "SetPixel()" http://msdn.microsoft.com/en-us/library/windows/desktop/dd145078(v=vs.85).aspx But it wastesa lot of timeto call this function and draw every pixels to it. Is there any feasible way to set every pixels by passing string (pointer), and call function...
Not sure what you mean by "Console Windows" or "String", and what they have to do with SetPixel(). However it is true that modifying bitmaps using repeated calls to SetPixel() is very inefficient because it has high overhead. Instead, copy out the bitmap data to a buffer usingGetDIBits(), modify the buffer, and once ...
I must be doing something monumentally stupid here but I can’t figure out what. If I printf the values within the foo function, it displays the correct values. But if I try to print them in main, I get nonsense results (0 and 1, respectively). ``` void foo(int a, int b){ a = 1; b = 2; } int main(void){ ...
You need to change your foo method to take pointers: ``` void foo(int *a, int *b) { *a = 1; *b = 2; } ``` Then your call to foo must change to: ``` foo(&a, &b); ``` This basically says: Pass the address of 'a' and 'b' to the function foo, so it has the ability to change their values. Your previous code just...
In my programm I have several float variables that I need to compare to 0. Those variables are being read in through printf. ``` float a; scanf("%f", &a); if (a=0) { printf("a is zero"); return 0; } ``` But it doesn't work when I give in a 0 through scanf. "a is zero" isn't displayed. It doesn't work with (a=0.0) an...
Just change "=" to "==". You can write "if" statement to following style: ``` if (CONSTANT == variable) ```
Whenever I send in a number from the command line it errors and gives me a wrong number ``` edgeWidth=*argv[2]; printf("Border of %d pixels\n", edgeWidth); fileLocation=3; ``` ./hw3 -e 100 baboon.ascii.pgmis what I send in through the command line and when I print the number to the screen I get 49 as the number int...
argvcontains an array of strings. Soargv[1]is a string, you need to convert it to an integer: ``` edgeWidth = atoi(argv[1]); ```
I have a C program "main" which gets the following parameters: "a b c d ..." e f g That's a total of 4 parameters, because of the quotation. I have a text file which each line has these 4 parameters. I made a shell script to run the C program for each of the parameters: ``` #!/bin/bash while read line do ./main...
``` #!/bin/bash while read line do eval set -- $line ./main "$@" done < $1 ```
I need to write linux application that will monitor specified process. Is it possible to be informed about every change of process state? I mean every change of fieldstateintask_struct
enable ftrace and keep logging it ``` cat /sys/kernel/debug/tracing/trace cat /sys/kernel/debug/tracing/tracing_on 1 cat /sys/kernel/debug/tracing/current_tracer function cat /sys/kernel/debug/tracing/available_tracers blk function_graph mmiotrace wakeup_rt wakeup function nop ``` Follow:http://lwn.net/Articles/2...
Is there any single instruction or function that caninvert the signof every float inside a __m128? i.e.a = r0:r1:r2:r3 ===> a = -r0:-r1:-r2:-r3? I know this can be done by_mm_sub_ps(_mm_set1_ps(0.0),a), but isn't it potentially slow since_mm_set1_ps(0.0)is a multi-instruction function?
In practice your compiler should do a good job of generating the constant vector for 0.0. It will probably just use_mm_xor_ps, and if your code is in a loop it should hoist the constant generation out of the loop anyway. So, bottom line, use your original idea of: ``` v = _mm_sub_ps(_mm_set1_ps(0.0), v); ``` or anot...
i need to use winpcap library in my c++11/qt5 project, and just after including library i'm getting errors like on the screenshot:click.In pro file i have ``` QMAKE_CXXFLAGS += -std=c++11 -lwpcap INCLUDEPATH += D:/Qt/Pr_inz1/WpdPack/Include LIBS += -L D:/Qt/Pr_inz1/WpdPack/Lib -lwpcap -lpacket ``` I'm including this...
try to#include <winsock2.h>before#include <pcap.h>
Since a variable of typeinterface{}can have any value, does that mean it is essentially a general pointer like a void* in C?
While C'svoid *pointers and Go'sinterface{}variables share the property that you can store arbitrary types, there is one big difference: Go interface variables also store the type of the value they hold. So while a C programmer is expected to make sure that any casts fromvoid *pointers to specific types are safe, the...
I've got astd::vectorand I need to get the hash of its contents from libgcrypt. How do I get the contents ofstd::vector<int-type> vecintogcry_md_hash_buffer(GCRY_MD_MD5, (void*)&digest, (void*)buffer, vec.size());wherebufferis thedatainvec?
If you are using C++11, pass ``` vec.data() ``` forbuffer. Reference:Vector::data() If not, pass&(vec.front()). The elements ofvecare guaranteed to be in contiguous storage.
Since a variable of typeinterface{}can have any value, does that mean it is essentially a general pointer like a void* in C?
While C'svoid *pointers and Go'sinterface{}variables share the property that you can store arbitrary types, there is one big difference: Go interface variables also store the type of the value they hold. So while a C programmer is expected to make sure that any casts fromvoid *pointers to specific types are safe, the...
I've got astd::vectorand I need to get the hash of its contents from libgcrypt. How do I get the contents ofstd::vector<int-type> vecintogcry_md_hash_buffer(GCRY_MD_MD5, (void*)&digest, (void*)buffer, vec.size());wherebufferis thedatainvec?
If you are using C++11, pass ``` vec.data() ``` forbuffer. Reference:Vector::data() If not, pass&(vec.front()). The elements ofvecare guaranteed to be in contiguous storage.
So I wrote the following method: ``` void removeEndingColon(char *charArrayWithColon) { // remove ':' from variableName size_t indexOfNullTerminator = strlen(charArrayWithColon); charArrayWithColon[indexOfNullTerminator - 1] = '\0'; // replace ':' with '\0' } ``` But when I test it with the following cod...
``` char *charArray1 = "ThisHasAColonAtTheEnd:";` ``` Here you point charArray1 to a string literal. In C, you cannot modify a literal. See e.gthis question You can store the string in an array which you can modify. So just do ``` char charArray1[] = "ThisHasAColonAtTheEnd:"; ```
There is a function, I want to call ``` (void) get_bytes (void * ptr, int length) ``` function takes two arguments the first is buffer (by that argument data will be recieved) second length of the data that I want to read. The task is to reading 10 bytes using this function, and print buffer on the screen (in the f...
You probably meant to write ``` printf("%02x", (unsigned char)buffer[i]); ``` As is you are passing characters as addresses for strings which won't quite work.
In theUNIX® System Threads Reference, under the heading of "Thread-safety" is a list of functions are "not guaranteed to be thread-safe on all UNIX systems." The function scandir() is absent from this list, while readdir() appears on the list. However the glibcsourcefor scandir() clearly appears to call readdir(), no...
I think, this list covers POSIX functions only.scandir(3)is BSD/SVID and might not be listed there hence. The new, thread-safe functions are probably the focus of this list but not listing old, thread-unsafe functions.
I have the following code ``` char *str = (char *) malloc(sizeof(char)*5); printf("Enter a string: "); scanf("%s", str); printf("%s\n", str); ``` This code supposed will reserve 5 places in memoryex: 5 * 8 bit, this mean that will stores five characters.Now, when enter any number of characters (not up to five only),...
C will not prevent you from shooting yourself in the foot.scanfwill happily overwrite the buffer given to it, invoking undefined behavior. This error is not reliably detectable at runtime and will silently corrupt memory and break the runtime of your application in unpredictable ways. It is your responsibility as the...
I have to write if statement for structure for person which: Is older or equal 16 and younger or equal 20 First letter of name and surname must be 's' or 'n' My code: ``` if(x.name[0]=='s' || x.name[0]=='n' && x.surname[0]=='s' || x.surname[0]=='n' && (x.age>=16 && x.age<=20)) { /* print person */ } `...
Enclose each||section in brackets. Keep in mind&&has higher priority than||. Like so: ``` if((x.name[0]=='s' || x.name[0]=='n') && (x.surname[0]=='s' || x.surname[0]=='n') && (x.age>=16 && x.age<=20)) ``` Splitting the code on several lines is not needed it just makes the code more readable.
Says you had a character array in C. Like this: ``` char array[]; ``` Now, which of the statements below will print out the address. I know that 1) and 2) will, but does 3) also print out the address? ``` 1) printf("Arrays adress is %x\n", array); 2) printf("Arrays adress is %x\n", &array[0]); 3) printf("Arrays adr...
None of them. All of them will print garbage value, i.e, yourprogram's behavior is undefined EDIT:As OP has changed his question now the answer is: All of them will print address by using%pspecifier and casting each ofarray,&arrayand&array[0]withvoid *. ``` char array[5]; //let's assume an array of 5 chars pri...
So I wrote the following method: ``` void removeEndingColon(char *charArrayWithColon) { // remove ':' from variableName size_t indexOfNullTerminator = strlen(charArrayWithColon); charArrayWithColon[indexOfNullTerminator - 1] = '\0'; // replace ':' with '\0' } ``` But when I test it with the following cod...
``` char *charArray1 = "ThisHasAColonAtTheEnd:";` ``` Here you point charArray1 to a string literal. In C, you cannot modify a literal. See e.gthis question You can store the string in an array which you can modify. So just do ``` char charArray1[] = "ThisHasAColonAtTheEnd:"; ```
There is a function, I want to call ``` (void) get_bytes (void * ptr, int length) ``` function takes two arguments the first is buffer (by that argument data will be recieved) second length of the data that I want to read. The task is to reading 10 bytes using this function, and print buffer on the screen (in the f...
You probably meant to write ``` printf("%02x", (unsigned char)buffer[i]); ``` As is you are passing characters as addresses for strings which won't quite work.
In theUNIX® System Threads Reference, under the heading of "Thread-safety" is a list of functions are "not guaranteed to be thread-safe on all UNIX systems." The function scandir() is absent from this list, while readdir() appears on the list. However the glibcsourcefor scandir() clearly appears to call readdir(), no...
I think, this list covers POSIX functions only.scandir(3)is BSD/SVID and might not be listed there hence. The new, thread-safe functions are probably the focus of this list but not listing old, thread-unsafe functions.
I have the following code ``` char *str = (char *) malloc(sizeof(char)*5); printf("Enter a string: "); scanf("%s", str); printf("%s\n", str); ``` This code supposed will reserve 5 places in memoryex: 5 * 8 bit, this mean that will stores five characters.Now, when enter any number of characters (not up to five only),...
C will not prevent you from shooting yourself in the foot.scanfwill happily overwrite the buffer given to it, invoking undefined behavior. This error is not reliably detectable at runtime and will silently corrupt memory and break the runtime of your application in unpredictable ways. It is your responsibility as the...
I have to write if statement for structure for person which: Is older or equal 16 and younger or equal 20 First letter of name and surname must be 's' or 'n' My code: ``` if(x.name[0]=='s' || x.name[0]=='n' && x.surname[0]=='s' || x.surname[0]=='n' && (x.age>=16 && x.age<=20)) { /* print person */ } `...
Enclose each||section in brackets. Keep in mind&&has higher priority than||. Like so: ``` if((x.name[0]=='s' || x.name[0]=='n') && (x.surname[0]=='s' || x.surname[0]=='n') && (x.age>=16 && x.age<=20)) ``` Splitting the code on several lines is not needed it just makes the code more readable.
Says you had a character array in C. Like this: ``` char array[]; ``` Now, which of the statements below will print out the address. I know that 1) and 2) will, but does 3) also print out the address? ``` 1) printf("Arrays adress is %x\n", array); 2) printf("Arrays adress is %x\n", &array[0]); 3) printf("Arrays adr...
None of them. All of them will print garbage value, i.e, yourprogram's behavior is undefined EDIT:As OP has changed his question now the answer is: All of them will print address by using%pspecifier and casting each ofarray,&arrayand&array[0]withvoid *. ``` char array[5]; //let's assume an array of 5 chars pri...
When compiling this code: ``` PCONSOLE_FONT_INFOEX Font_Info; //Adjust heights Font_Info.dwFontSize.X = 9; Font_Info.dwFontSize.Y = 9; SetCurrentConsoleFontEx( StdHandle, FALSE, Font_Info); ``` GCC reports ``` undefined reference to 'SetCurrentConsoleFontEx' ``` But MSDN says that the header is#include<windows.h> ...
This would not be the first time a function is missing from MinGW's SDK, and especially not a recent function likeSetCurrentConsoleFontExwhich is only exposed from Vista onwards. Your libkernel32.a is too old for it; if you want to use this function from MinGW, you may need to access it dynamically instead.
The documentation didnt say anything...but this, but cvCapture is a C type. " Note ``` In C API, when you finished working with video, release CvCapture structure with cvReleaseCapture(), or use Ptr<CvCapture> that calls cvReleaseCapture() automa tically in the destructor." ``` I figure VideoCapture is a...
The destructor for VideoCapture is ``` VideoCapture::~VideoCapture() { cap.release(); } ``` So it is not necessary to release it. If you want to release without destructing the object calling the release() method on a VideoCapture object you well get the same effect: ``` void VideoCapture::release() { cap...
I found that Console Application compiled from GCC on Windows always terminate when pressingCtrl+C. Is there any feasible way to prevent Console Application from terminating when pressingCtrl+C?
When the user presses control C, a signal (SIGINT) is sent to your process. When most signals are sent to a process, that process must either handle the signal or the operating system will kill it. So... all you need to do is install a signal handler for SIGINT. The following is untested: ``` #include <signal.h> sta...
I have searched in the MSDN, but nothing meet my needs. Could anyone help me? THANKS. ``` #include <windows.h> int main (void) { // HOW TO ? } ```
To get info on the console's font use: GetConsoleFontSize()GetCurrentConsoleFont()orGetCurrentConsoleFontEx() To set font info use: SetCurrentConsoleFontEx()
I have a little question: ``` struct point {int x ; int y;}; int main(){ struct point p = {10,20}; struct point *pp = &p; (∗ pp).x = 10; // what is happening here int y= (∗ pp).y; return 0} // what is happening here ``` and more general , why is the () required? (its from a tutorial but they g...
Because.has higher precedence than*. That is, without the parenthesis, ``` *pp.x = 10; ``` stands for ``` *(pp.x) = 10; ``` However,ppis a pointer. Thus, the.operator does not work on it. You need to either use->operator to access the member of a pointer to struct, or use parenthesis to dereference the pointer bef...
I need it because I have to modify the linker, specifically that part where it resolves the symbols in plt section and updates them in GOT.
As I've already posted in my previous answer to your question,this page is great. Read it carefully — there is also a number of references and books in the beginning (Useful books and referencesheading). You may also want to look atLinkers and Loadersby Levine for reference.
Is there a simple way to split one 64-bit (unsigned long long) variable into eightint8_tvalues? For example: ``` //1001000100011001100100010001100110010001000110011001000110011111 unsigned long long bigNumber = 10455547548911899039; int8_t parts[8] = splitULongLong(bigNumber); ``` partswould be something along the ...
``` { uint64_t v= _64bitVariable; uint8_t i=0,parts[8]={0}; do parts[i++]=v&0xFF; while (v>>=8); } ```
``` FILETIME Kernel_Time; HANDLE Process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, 0); GetProcessTimes(Process, NULL, NULL, &Kernel_Time, NULL); SYSTEMTIME Sys_Time; FileTimeToSystemTime(&Kernel_Time, &Sys_Time); printf("%d", Sys_Time.wYear); // WHY ? ``` WhySys_Time.wYearis not 2013? Could anyone help me?
``` HANDLE Process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, 0); ``` As per thedocumentation, If the specified process is the System Process (0x00000000), the function fails and the last error code is ERROR_INVALID_PARAMETER. So, yourOpenProcessfails withERROR_INVALID_PARAMETER, and theHANDLE ProcessisNULL. Always c...
I'm using the following C code: ``` #include <unistd.h> #include <fcntl.h> #include <sys/types.h> int main() { int file=0; if((file=open("testfile.txt",O_RDONLY)) < -1) return 1; char buffer[19]; if(read(file,buffer,19) != 19) return 1; printf("%s\n",buffer); if(lseek(file,10,SE...
You need to add#include <stdio.h>to the top of your file.
I have searched in the MSDN, but nothing meet my needs. Could anyone help me? THANKS. ``` #include <windows.h> int main (void) { // HOW TO ? } ```
To get info on the console's font use: GetConsoleFontSize()GetCurrentConsoleFont()orGetCurrentConsoleFontEx() To set font info use: SetCurrentConsoleFontEx()