question
stringlengths
25
894
answer
stringlengths
4
863
Until recently, I thought CPU caches (at least, some levels) were 4kb in size, so grouping my allocations into 4kb slabs seemed like a good idea, to improve cache locality. However, readingLine size of L1 and L2 cachesI see that all levels of CPU cache lines are 64 bytes, not 4kb. Does this mean my 4kb slabs are usel...
4KB does have a significance: it is a common page size for your operating system, and thus for entries in your TLB. Memory-mapped files, swap space, kernel I/Os (write to file, or socket) will operate on this page size even if you're using only 64 bytes of the page. For this reason, it can still be somewhat advantag...
I'm trying to match strings like this:"labels": [{"name": "labelname"where labelname can contain any amount of letters, numbers or whitespaces. I tried"labels": \[\{"name": "(.*?)",which works in regex101.com but i dont get any matches using the posix regex.h. If i do"labels": \[\{"name": "it matches the string up to ...
Just do a class that select everything apart from the closing character, like that : ``` "labels": \[\{"name": "([^"]*)" ```
I get an error "conflicting types for 'abs' in my function. The code is very simple. ``` double abs (double x) { // Returns absolute value if (x<0) return (x*(-1)); else return x; } ``` This is on a C proyect on codeblocks. I already tried casting the returns but the error remains anyway.
My guess is you have<stdlib.h>included becauseabsis already declared there and has the signatureint abs(int), so your definition produces "conflicting types".
If condition inside thefindsetis not giving correct comparison. It is always shows not equal. Where did I make a mistake? ``` #include<stdio.h> struct node { struct node *p; int rank; }; void makeset(struct node x) { x.p = &x; x.rank = 0; } void findset(struct node x) { if (x.p == &x) { printf("It ...
``` void findset(struct node x) { if (x.p == &x) { ``` thatxis a copy of the one passed in... x is always brand new and&xwont match any previous address. Note that this is true not just of structs but all values... ``` int i = 3; void f( int j) { // &j != &i // j == i // j and I have the same ...
Everyone knows theabs()function togetthe absolute value of variables. Is there a similar function or efficient way of setting it ignoring the sign? Practical example:Force minimum value for motor speed control ``` if (abs(speed) < 50 && speed != 0) { if (speed < 0) speed = -50; else speed = 5...
It's basically thesignumfunction ``` speed = 50*sgn(speed); ``` There's astandard functionfor this ``` speed = copysign(50, speed); ``` however this isn't quite efficient for integer types. Thesgn()function can be implemented using various other ways that you can findhere ``` speed = ((speed > 0) - (speed < 0))*...
A weird interview question I had yesterday Given avoid *ppointer, and a inta = 1;how to dereference to any level pointers? For example, if input is 1, then you can get the data by*(int *)p if input is 2, then you can get the data by**(int **)p if input is 3, then you can get the data by***(int ***)p but what if ...
Something like this: ``` int dereference(void *p, int n) { for (int i = 0; i < n; i++) { p = *((void **) p); } return (int)p; } ```
Everyone knows theabs()function togetthe absolute value of variables. Is there a similar function or efficient way of setting it ignoring the sign? Practical example:Force minimum value for motor speed control ``` if (abs(speed) < 50 && speed != 0) { if (speed < 0) speed = -50; else speed = 5...
It's basically thesignumfunction ``` speed = 50*sgn(speed); ``` There's astandard functionfor this ``` speed = copysign(50, speed); ``` however this isn't quite efficient for integer types. Thesgn()function can be implemented using various other ways that you can findhere ``` speed = ((speed > 0) - (speed < 0))*...
A weird interview question I had yesterday Given avoid *ppointer, and a inta = 1;how to dereference to any level pointers? For example, if input is 1, then you can get the data by*(int *)p if input is 2, then you can get the data by**(int **)p if input is 3, then you can get the data by***(int ***)p but what if ...
Something like this: ``` int dereference(void *p, int n) { for (int i = 0; i < n; i++) { p = *((void **) p); } return (int)p; } ```
This question already has answers here:simple c program keeps crashing(2 answers)Closed5 years ago. I was trying to show alternating series usingifstatement nested in awhileloop. That's the code. ``` main() { printf( "Enter a number: " ); int n1; scanf( " %d", n1 ); int temp = 1; while( temp <= ...
You need to providescanf()with the address of the variable you are assigning to, use the address-of operator&: ``` scanf(" %d", &n1); ```
I'm not sure why this is happening but I am getting a "Segmentation fault (core dumped)" from this very simple code. Any ideas as to why? I have to use a string to tell fopen() what file to open. ``` #include <stdio.h> #include <string.h> int main(void) { char *small = "small.ppm"; FILE * fp; char word[5...
If the file does not existfpwill be NULL and sofscanf(fp, ...)will segfault. It's important to check all file operations for success. The usual pattern goes something like... ``` FILE *fp = fopen(filename, "r"); if( fp == NULL ) { fprintf(stderr, "Couldn't open %s: %s\n", filename, strerror(errno)); exit(1);...
I am getting the following compilation error:request for member ‘threeds’ in something not a structure or union here is my struct: ``` struct pthread_arg { int size; int threeds; int the_threads; }; ``` Here is the line causing the issue: ``` int first = *(arg.threeds) * N/number_of_the_threads; ``` I have looke...
It appearsargis an arugment passed to a thread function (which is a pointer to your struct). In that case, you can't directly dereferenceargbecause it's avoid*. Convert it to appropriate type (which must match the argument passed to pthread_create API) and then use: ``` void *multiplication(void *arg) { struct p...
I am getting the following compilation error:request for member ‘threeds’ in something not a structure or union here is my struct: ``` struct pthread_arg { int size; int threeds; int the_threads; }; ``` Here is the line causing the issue: ``` int first = *(arg.threeds) * N/number_of_the_threads; ``` I have looke...
It appearsargis an arugment passed to a thread function (which is a pointer to your struct). In that case, you can't directly dereferenceargbecause it's avoid*. Convert it to appropriate type (which must match the argument passed to pthread_create API) and then use: ``` void *multiplication(void *arg) { struct p...
I'm using the Bochs emulator and for my class we're using gcc 4.2.1. I believe I've gotten Bochs running, but now I need to compile our programs which are compatible with gcc 4.2/.1. I understand OSX uses an alias for gcc 4.2.1, but how can I use gcc specifically and not clang? Edit: GCC 4.6.3 not 4.2.1 sorry
You can install previous version of gcc pretty easily usinghomebrew. If you have homebrew installed you can get gcc 4.9 by running ``` brew install gcc@4.9 ``` After it is installedgccwill still map to the clang that came with your mac. The newly installedgccwill be installed at/usr/local/binand be called something...
Consigne: each integer is in the inclusive range 1 - 109. I use variable with the typeunsigned long long int Is it enough for the stated range?
10^9 is way smaller than 2^32 So in your case, no need to useunsigned long long(it fits, yes), which is overkill and can lead to slower operation. Use the proper type, normalized instdint.hinclude:uint32_toruint_least32_t(uint32_t vs uint_fast32_t vs uint_least32_t) longis also guaranteed to beat least 32 bits, so ...
I am using theEVP high-level functions in OpenSSL. I haven't found any examples online showing how to use these functions (e.g.EVP_EncryptInit_ex(),EVP_EncryptUpdate(),EVP_EncryptFinal_ex()) to encrypt data using an RSA public key. Specifically, I do not see aEVP_CIPHERtype that matches RSA, similar to what you see fo...
To do asymmetric encryption you need to use different EVP routines than for symmetric crypto. In particular see the EVP_PKEY_encrypt() function. The man page is here, and it contains an example. https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_encrypt.html
What will happen in below case?What will happen if I writeif (p == NULL) { break; }?#include <stdio.h> void main() { int *p; while (1) { p = malloc(1024); // allocating memory in infinite while loop // if (p == NULL) { break; } } }
You might expect to run out of memory eventually, andmallocmust returnNULLin that case. But note that some C runtime libraries and operating systems will not actually allocate the memory until you use it. Since you're not using the memory, you might find that the loops runs forever, but not due to the explicit failure...
I am trying to use JNI to integrate a .C code with my Java project. While trying to generate the .dll file using vcvars32.bat in visual studio 2017 it gives me an error message tells: "C:\Program Files\Java\jdk1.8.0_151\include\jni.h(39): fatal error C1083: Cannot open include file: 'stdio.h': No such file or direct...
After sometime of searching and failing I had to generate it by VS13 vsvars32.bat note that vsvars not VS17's vcvars that generated 32-bit dll and because my platform is 64-bit I had to install and switch to 32-bit JVM and problem is resolved.
I'm running onOSXand trying to compile following c code to webAssembly: ``` void test(){ //do stuff } ``` I've looked atthis exampleand tried running the following commands: ``` clang -emit-llvm --target=wasm32 -Oz test.c -c -o test.bc llc -asm-verbose=false -o test.s test.bc ``` First command works fine and c...
It looks like your version of llvm was not compiled with support for the WebAssembly backend. This backend is still experimental so you need to enable it at cmake time with:-DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=WebAssembly
This question already has answers here:printf anomaly after "fork()"(3 answers)Closed5 years ago. So as far as i know fork creates a duplicate of the process it's called from but it also copy's it's program counter so it continues from the line after it's called but why is this code printing hello world twice when it...
printfdoesn't actually print -- it actually just puts data into a buffer to be printed later. It will actually be printed when the buffer gets flushed, which can happen in a variety of ways. In your case, the buffer flush doesn't happen until after the fork, so both the parent and the child have a copy of the string...
I'm trying to figure out the correct way to pass database connection parameters to this libpq connection control function. PQconnectdbParams ``` PGconn *PQconnectdbParams(const char * const *keywords, const char * const *values, int expand_dbname); ```
Fromthe documentation: This function opens a new database connection using the parameters taken from two NULL-terminated arrays. The first, keywords, is defined as an array of strings, each one being a key word. The second, values, gives the value for each key word. I have never used this function in practice (asPQc...
I have a structure defined as ``` struct Bod{ int x, y; }; ``` Then I have a function ``` void add(struct Bod* s) { h[++nh] = s; } ``` And in next function, I tried to pass array into the previous function, which gives me errorIncompatible type for argument 1 of function add() ``` void bfs(struct Bod* body,...
Sincebody[start_index]gives youoneelement ofbodyat indexstart_index, you end up passing in that single element toadd(). If you want to pass in the array itself, you just need to pass inbodyas-is: ``` add(body); ``` Or, to pass in the array starting at a given index: ``` add(&body[start_index]); ```
This question already has answers here:printf anomaly after "fork()"(3 answers)Closed5 years ago. So as far as i know fork creates a duplicate of the process it's called from but it also copy's it's program counter so it continues from the line after it's called but why is this code printing hello world twice when it...
printfdoesn't actually print -- it actually just puts data into a buffer to be printed later. It will actually be printed when the buffer gets flushed, which can happen in a variety of ways. In your case, the buffer flush doesn't happen until after the fork, so both the parent and the child have a copy of the string...
I'm trying to figure out the correct way to pass database connection parameters to this libpq connection control function. PQconnectdbParams ``` PGconn *PQconnectdbParams(const char * const *keywords, const char * const *values, int expand_dbname); ```
Fromthe documentation: This function opens a new database connection using the parameters taken from two NULL-terminated arrays. The first, keywords, is defined as an array of strings, each one being a key word. The second, values, gives the value for each key word. I have never used this function in practice (asPQc...
I have a structure defined as ``` struct Bod{ int x, y; }; ``` Then I have a function ``` void add(struct Bod* s) { h[++nh] = s; } ``` And in next function, I tried to pass array into the previous function, which gives me errorIncompatible type for argument 1 of function add() ``` void bfs(struct Bod* body,...
Sincebody[start_index]gives youoneelement ofbodyat indexstart_index, you end up passing in that single element toadd(). If you want to pass in the array itself, you just need to pass inbodyas-is: ``` add(body); ``` Or, to pass in the array starting at a given index: ``` add(&body[start_index]); ```
``` #include <stdio.h> void main(){ FILE *fp[1024]; char FILENAME[1024]; int i; for(i=0;i<1024;i++){ sprintf(FILENAME,"file%d.txt",i); fp[i]=fopen(FILENAME,"w"); if(fp[i]==NULL){ printf("file %d cannot be opened\n",i); exit(0); } } } ``` In the...
You need to close each file after you create it. You are likely running into the limit on the maximum number of files you can have open per process (I am guessing that for you it will be 512). On linux/unix/BSD you can find out what the limit is with 'ulimit -l' More info here:https://unix.stackexchange.com/questions...
My code on codefights works well for all the test cases but doesn't pass one hidden test case. The problem is to convert the given year from 1<=year<=2005 into century. I wrote all the code. I just don't get what I should change to get the hidden test passed. This is my code: ``` int centuryFromYear(int year) { ...
Corrected Code - ``` int centuryFromYear(int year) { int x=year/100; if(year%100==0) { return(x); } else { return(x+1); } } ``` You were almost there too. Hope this helps.
I can declare a function taking a function pointer as argument, ``` int bar(int (* a)()) { } // this works ``` I can apply the const qualifier to this argument, ``` int bar(int (* const a)()) { } // this works ``` But when I apply the restrict qualifier to this argument, I get an error ``` int bar(int (* restrict...
Only pointers to objects may berestrictqualified: §6.7.3 Type qualifiersTypes other than pointer types whose referenced type is an object type shall not be restrict-qualified. A function is not an object: §3.15.1 objectregion of data storage in the execution environment, the contents of which can represent values...
I just know how to add system calls to kernel of Linux. My system call (like lots of other system calls) takes a pointer to a struct created by me. If I want to add the struct to kernel source how and where should I add it?
Place a header containing the newstructininclude/uapi/linux. Avoid namespace pollution by using the appropriate types e.g.__u16instead ofunsigned short/uint16_t,__kernel_time_tinstead oftime_t...etc. Check outstruct mii_ioctl_datafor an example. By adding aheader-y += new_header.hentry toinclude/uapi/linux/Kbuild, yo...
Objective To generate the hash of a image file. I am usingpHashlibrary for this task. pHash library has below method used for generating the image hash. ``` int ph_dct_imagehash(const char* file,ulong64 &hash); ``` Datatype ulong64 is not present in android stdint.h. Due to which I am getting"cannot resolve type ul...
This type is specific to pHash, and it is defined inside pHash.h by the following snippet: ``` #if defined( _MSC_VER) || defined(_BORLANDC_) typedef unsigned _uint64 ulong64; typedef signed _int64 long64; #else typedef unsigned long long ulong64; typedef signed long long long64; #endif ``` To use this type, just#inc...
How to delete all the nodes in singly circular linked list? Is this code the right one ? I don't get the output in codeblocks when I tried for it. What is the mistake? ``` void deleteall() { struct node *temp1=head,*temp2; do { while(temp1->next!=head) { temp1=temp1->next; ...
To delete a singly circular linked list, start from thenextofheadand keep on deleting until you reach toheadand then deleteheadof the list, like this: ``` struct node *temp1 = head->next, *temp2; while (temp1 != head) { temp2 = temp1->next; free(temp1); temp1 = temp2; } free (head); head = NULL; ```
I'm using the function__builtin_clzprovided by GCC, which should count the number of leading zero bits in anunsigned int. But__builtin_clzreturns an incorrect value for input0: ``` #include <stdio.h> int main(void) { unsigned int x = 0; int lz = __builtin_clz(x); printf("%d\n", lz); return 1; } ``` I expect ...
Is this my fault? Have I invoked some undefined behavior somewhere? Yes, by passing 0 to__builtin_clz. From theGCC documentation: Returns the number of leading 0-bits in x, starting at the most significant bit position.If x is 0, the result is undefined.
I am trying to use a simpleDHCP clientfrom GitHub. When I try to run this client it fails with ``` eth0 MAC : C8:6B:00:E5:52:5E Couldn't open device eth0: eth0: socket: Invalid argument ``` Any advices? Thanks!
Clearlypcap_open_live()returns withNULL. pcap_open_live()returns apcap_t *on success andNULLon failure. IfNULLis returned,errbufis filled in with an appropriate error message.errbufmay also be set to warning text whenpcap_open_live()succeds; to detect this case the caller should store a zero-length string ine...
I just know how to add system calls to kernel of Linux. My system call (like lots of other system calls) takes a pointer to a struct created by me. If I want to add the struct to kernel source how and where should I add it?
Place a header containing the newstructininclude/uapi/linux. Avoid namespace pollution by using the appropriate types e.g.__u16instead ofunsigned short/uint16_t,__kernel_time_tinstead oftime_t...etc. Check outstruct mii_ioctl_datafor an example. By adding aheader-y += new_header.hentry toinclude/uapi/linux/Kbuild, yo...
Objective To generate the hash of a image file. I am usingpHashlibrary for this task. pHash library has below method used for generating the image hash. ``` int ph_dct_imagehash(const char* file,ulong64 &hash); ``` Datatype ulong64 is not present in android stdint.h. Due to which I am getting"cannot resolve type ul...
This type is specific to pHash, and it is defined inside pHash.h by the following snippet: ``` #if defined( _MSC_VER) || defined(_BORLANDC_) typedef unsigned _uint64 ulong64; typedef signed _int64 long64; #else typedef unsigned long long ulong64; typedef signed long long long64; #endif ``` To use this type, just#inc...
How to delete all the nodes in singly circular linked list? Is this code the right one ? I don't get the output in codeblocks when I tried for it. What is the mistake? ``` void deleteall() { struct node *temp1=head,*temp2; do { while(temp1->next!=head) { temp1=temp1->next; ...
To delete a singly circular linked list, start from thenextofheadand keep on deleting until you reach toheadand then deleteheadof the list, like this: ``` struct node *temp1 = head->next, *temp2; while (temp1 != head) { temp2 = temp1->next; free(temp1); temp1 = temp2; } free (head); head = NULL; ```
I'm using the function__builtin_clzprovided by GCC, which should count the number of leading zero bits in anunsigned int. But__builtin_clzreturns an incorrect value for input0: ``` #include <stdio.h> int main(void) { unsigned int x = 0; int lz = __builtin_clz(x); printf("%d\n", lz); return 1; } ``` I expect ...
Is this my fault? Have I invoked some undefined behavior somewhere? Yes, by passing 0 to__builtin_clz. From theGCC documentation: Returns the number of leading 0-bits in x, starting at the most significant bit position.If x is 0, the result is undefined.
I am trying to use a simpleDHCP clientfrom GitHub. When I try to run this client it fails with ``` eth0 MAC : C8:6B:00:E5:52:5E Couldn't open device eth0: eth0: socket: Invalid argument ``` Any advices? Thanks!
Clearlypcap_open_live()returns withNULL. pcap_open_live()returns apcap_t *on success andNULLon failure. IfNULLis returned,errbufis filled in with an appropriate error message.errbufmay also be set to warning text whenpcap_open_live()succeds; to detect this case the caller should store a zero-length string ine...
How to delete all the nodes in singly circular linked list? Is this code the right one ? I don't get the output in codeblocks when I tried for it. What is the mistake? ``` void deleteall() { struct node *temp1=head,*temp2; do { while(temp1->next!=head) { temp1=temp1->next; ...
To delete a singly circular linked list, start from thenextofheadand keep on deleting until you reach toheadand then deleteheadof the list, like this: ``` struct node *temp1 = head->next, *temp2; while (temp1 != head) { temp2 = temp1->next; free(temp1); temp1 = temp2; } free (head); head = NULL; ```
I'm using the function__builtin_clzprovided by GCC, which should count the number of leading zero bits in anunsigned int. But__builtin_clzreturns an incorrect value for input0: ``` #include <stdio.h> int main(void) { unsigned int x = 0; int lz = __builtin_clz(x); printf("%d\n", lz); return 1; } ``` I expect ...
Is this my fault? Have I invoked some undefined behavior somewhere? Yes, by passing 0 to__builtin_clz. From theGCC documentation: Returns the number of leading 0-bits in x, starting at the most significant bit position.If x is 0, the result is undefined.
I am trying to use a simpleDHCP clientfrom GitHub. When I try to run this client it fails with ``` eth0 MAC : C8:6B:00:E5:52:5E Couldn't open device eth0: eth0: socket: Invalid argument ``` Any advices? Thanks!
Clearlypcap_open_live()returns withNULL. pcap_open_live()returns apcap_t *on success andNULLon failure. IfNULLis returned,errbufis filled in with an appropriate error message.errbufmay also be set to warning text whenpcap_open_live()succeds; to detect this case the caller should store a zero-length string ine...
PVS-Studio gave me a warning about this : ``` char c; sscanf(line, "%d", &c); ``` I changed %d to %c but this created a bug because "c" now contains the ASCII value of the number and not the decimal one, so I went back to "%d". So what's the correct specifier to ? is there another solution ?
cis achar. You asked to scan anint. PVS-Studio did right in warning you. Change the type ofctointand scan for a%d.
I am just started C programming and installed minGW. While doing my Hello world test program, I am getting an error as below while compiling my 'test.c' hello world file using - g++ test.c. test.c:1:5: error:'i' does not name a type y_# i n c l u d e My code - ``` #include <stdio.h> int main () { printf ("Hello...
The messagey_# i n c l u d eand the double line end suggest that the filetest.cis encoded in UTF-16 encoding. Change the file encoding to ascii, it will solve your problem.
In my program I need to detect if the spacebar is pressed 3 times and then replace it whit a \n. I am using getchar for getting my input and detecting one space is no problem but if I enter 3 spaces to check it does not work. Any help is very appreciated This is my code so far witch works perfectly fine if I only ch...
You can count the number of consecutive spaces. Something like: ``` int c; int spaces = 0; while((c = getchar()) != EOF) { if (c == ' ') { ++spaces; if (spaces == 3) { putchar('\n'); spaces = 0; } } else { spaces = 0; } } ```
Is it wrong at all and there is no way, or i have to do it somewhat else? For example: ``` typedef void (*UserFunc)(Test *tx); typedef struct{ int a; char b; UserFunc func; } Test; ``` i get this error: ``` c.c:5:26: error: unknown type name ‘Test’ typedef void (*UserFunc)(Test *tx); ^~...
You have to declare Test first, and define it later : ``` typedef struct Test Test; typedef void (*UserFunc)(Test *tx); typedef struct Test { int a; char b; UserFunc func; } Test; ```
Hello i just need to see why my Gcc stopped working after execution. ``` #include<stdio.h> int main() { static char *s[] = {"black", "white", "pink", "violet"}; char **ptr[] = {s+3, s+2, s+1, s}, ***p; p=ptr; ++p; printf("the value of **p is %s\n\t",**p); // printed on screen pink printf("the value of **ptr[1] is %s\...
**ptr[1]is achar. You are passing it toprintffor a%sconversion.%srequires a pointer tochar, not achar. Pass*ptr[1]instead. Similarly, instead of*s[2], passs[2].
I'm trying to write a method in C that accepts three integers: start, end, and mask. If mask is 1, all bits except the bits in the range of start to end are set to 0, and the bits in the range are set to 1. I have this part working at the moment: ``` for (int i = 0; i < (end - start + 1); i++) { if (mask == 1) { ...
Since flipping the mask from 1 to 0 simply inverts the result, you can ignore the mask, build the return formask == 1, and flip its bits at the end if the mask is zero: ``` int ret = 0; for (int i = start ; i <= end ; i++) { ret |= 1 << i; } if (!mask) { ret = ~ret; } ```
I had to test if my machine is using the little or the big endian. For this reason i wrote this code. I can see that my machine is using the little endian. But i dont know why the output from my first byte is only D. Should it not be 0D? ``` union int2byte { unsigned char bytes[4]; unsigned int hex; }; int m...
%Xdoes not output leading zeros. Use%02Xinstead. The2tells it to output at least 2 digits, and the0tells it to pad the output on the left side with a'0'character if the output is less than 2 digits.
while going through the first chapter I found a question *to remove all comments from a code" - I really don't know what the author expects, whether I am supposed to use File handling (which in later chapters) or am I supposed to type in the entire file as an input?
You don't need file handling, you can use "getline" like in the later examples in chapter 1 to parse lines. Then if you want to use your code on a file you can pipe the file as input to the executable you have written. You could also use "getchar" as in the "wc" example (line, word, and character counting example) gi...
I recently learned thatsizeofis not a function and actually evaluates at compile time. But I still haven't been able to figure out howsizeof(*NULL)is equal to 1. EDIT: I'm talking about gcc here specifically.
It depends on the compiler and standard library. With GCC and glibc,NULLis defined as(void*)0and GCC hasan extensionthat allows pointer arithmetic onvoidpointers usingsizeof(void) == 1. Without this extension, the compiler would produce an error. A standard library could also defineNULLas0. In this casesizeof(*NULL)w...
I have a nested struct, which I am attempting to fill with user data. The struct: ``` typedef struct gameInfo { char title[MAX]; char platform[MAX]; char developer[MAX]; unsigned int year; struct borrowerInfo { bool borrowed; char nameOfBorrower[MAX]; ...
gameis the name of a type, not a variable. You need to declare a variable of that type: ``` game mygame; ``` Then populatemygame. Also, never usergets, as the function can overrun the buffer it's writing to. Better to usefgetsinstead.
I would like to allocate a buffer within 32-bit address space on 64-bit ARM. In other words, I would like to ensure that my buffer is bound to the lower 32-bit address space. Do you know a nice C function which does that?
There is no C standard function to do so. However, since you tagged the question as Linux, take a look atmmap(2)and theMAP_ANONYMOUSandMAP_32BITflags, e.g.: ``` mmap( 0, 1, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_32BIT, -1, 0 ); ``` Another option is passing an explicit address in t...
In the terminal for my autocomplete implementation, the commands are displaying after pressing theENTER.But I want to change the terminal behavior such that the commands will be displayed without pressing enter. My question is how to change the terminal settings for displaying the commands when I pressTABwithout pres...
You need to use an OS-specific way to control the terminal, like theConsole API for Windows. There are also cross-platform libraries that you can use as well, like thencurses library. Read also aboutTerminal capabilitiesfor more information.
I had to test if my machine is using the little or the big endian. For this reason i wrote this code. I can see that my machine is using the little endian. But i dont know why the output from my first byte is only D. Should it not be 0D? ``` union int2byte { unsigned char bytes[4]; unsigned int hex; }; int m...
%Xdoes not output leading zeros. Use%02Xinstead. The2tells it to output at least 2 digits, and the0tells it to pad the output on the left side with a'0'character if the output is less than 2 digits.
while going through the first chapter I found a question *to remove all comments from a code" - I really don't know what the author expects, whether I am supposed to use File handling (which in later chapters) or am I supposed to type in the entire file as an input?
You don't need file handling, you can use "getline" like in the later examples in chapter 1 to parse lines. Then if you want to use your code on a file you can pipe the file as input to the executable you have written. You could also use "getchar" as in the "wc" example (line, word, and character counting example) gi...
I recently learned thatsizeofis not a function and actually evaluates at compile time. But I still haven't been able to figure out howsizeof(*NULL)is equal to 1. EDIT: I'm talking about gcc here specifically.
It depends on the compiler and standard library. With GCC and glibc,NULLis defined as(void*)0and GCC hasan extensionthat allows pointer arithmetic onvoidpointers usingsizeof(void) == 1. Without this extension, the compiler would produce an error. A standard library could also defineNULLas0. In this casesizeof(*NULL)w...
I have a nested struct, which I am attempting to fill with user data. The struct: ``` typedef struct gameInfo { char title[MAX]; char platform[MAX]; char developer[MAX]; unsigned int year; struct borrowerInfo { bool borrowed; char nameOfBorrower[MAX]; ...
gameis the name of a type, not a variable. You need to declare a variable of that type: ``` game mygame; ``` Then populatemygame. Also, never usergets, as the function can overrun the buffer it's writing to. Better to usefgetsinstead.
I would like to allocate a buffer within 32-bit address space on 64-bit ARM. In other words, I would like to ensure that my buffer is bound to the lower 32-bit address space. Do you know a nice C function which does that?
There is no C standard function to do so. However, since you tagged the question as Linux, take a look atmmap(2)and theMAP_ANONYMOUSandMAP_32BITflags, e.g.: ``` mmap( 0, 1, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_32BIT, -1, 0 ); ``` Another option is passing an explicit address in t...
In the terminal for my autocomplete implementation, the commands are displaying after pressing theENTER.But I want to change the terminal behavior such that the commands will be displayed without pressing enter. My question is how to change the terminal settings for displaying the commands when I pressTABwithout pres...
You need to use an OS-specific way to control the terminal, like theConsole API for Windows. There are also cross-platform libraries that you can use as well, like thencurses library. Read also aboutTerminal capabilitiesfor more information.
I would like to replace the'character with\'I use the following code: ``` #include <stdio.h> #include <string.h> int main() { int i, j = 0; char str[] = "HELLO'All"; char pch[128] = { 0 }; for (i = 0; i < strlen(str); i++) { if (str[i] == '\'') { pch[j] = '\\'; printf...
It seems you miss an increment ofj Try like this ``` pch[j++]='\\'; printf(" pch[%d] = *%c* \n",j-1, pch[j-1]); pch[j++]=str[i]; ``` or like this ``` pch[j]='\\'; printf(" pch[%d] = *%c* \n",j, pch[j]); ++j; pch[j++]=str[i]; ```
I have encountered a terse piece of code which I am finding very difficult to decipher. ``` for (int k = 0; k < count; k++) { C[p=w[T[k]]++] = Y1[k]; CC[p] = Y2[k] } ``` w and T look like this: ``` w = [0 3 6 8] T = [2 0 3 2 1 0 1 3 0 1] ``` I am unable to figure what is the index that the arrayCandCCare g...
Rewrite it. This code is equivalent to: ``` for (int k = 0; k < count; k++) { p = w[T[k]]++; C[p] = Y1[k]; CC[p] = Y2[k] } ``` which is the same as ``` for (int k = 0; k < count; k++) { p = w[T[k]]; // For k=0 => w[2]=6 => p=6 w[T[k]]++; // For k=0 => increment w[2], so w[2] is 7 C[p] ...
I recently noticed that ``` void foo(int array[10]); ``` Does not load the stack with the content of array whenfoois called, so the declaration is equivalent to: ``` void foo(int *array): ``` I would like to find the section in the C99 standard that assert this behavior, but I don't find anything or I don't know w...
C11 6.7.6.3 §7. (C99 6.7.5.3 §7) A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation. The term is formally named "array adjustment". Informally outside the C s...
I have written a simple command-line based audio player in C using libVLC library. Every time a audio file is played, an album art (.jpg format) and a directory in the track's name will be created for each track, inside '~/.cache/vlc' folder which is taking up significant disk space and creating lots of directories. I...
The easiest way I found around this knotty little issue was to create the directory$HOME/.cache/vlc/artand simply make itread only.If vlc can't write to it:a. The issue disappearsb. vlc doesn't complain about it.
ing_hash_table_new(HashFunc hash_func, GEqualFunc key_equal_func) HashFunc they have this types: g_direct_hash()g_int_hash()g_int64_hash()g_double_hash()g_str_hash() GEqualFunc they have this types: g_direct_equal()g_int_equal()g_int64_equal()g_double_equal()g_str_equal() Which type can i use to have a key that i...
Summarizing from comments: Assuming you build for a system where a pointer is at least as many bits as a long (true on most systems), yes, you can cast it to agconstpointerand useg_direct_*. You do build in a dependency on that fact into your code that way though. Otherwise: do not uselongbut eithergintorgint64for y...
I am facing difficulty in converting a binary array to a decimal number: ``` bin[8] = {10,00,00,10}; ``` I want the equivalent of this array element as a decimal number, i.e.130.
A standard solution goes like this: ``` int f(char s[]) { int n = 0; int i; for (i = 0; i < 8; ++i) { n <<= 1; n += s[i] - '0'; } return n; } ```
I am trying to dynamically show a specific number of decimals. I use this : ``` char graduationText[1024]; sprintf("%.*f", graduationText, decimalsToShow, graduation); ``` However when the program run I get a memory violation error. So I was wondering if sprintf can manage the "%.*f" or if it an error of me. Tha...
Thedocumentation forsprintfreads like: int sprintf(char *str, const char *format, ...);sprintf()[et al.] ... write to the character stringstr. You suffered undefined behavior due tosprintfattempting to read uninitialized memory to use as the format string, and attempting to write to a string literal. However, you s...
I have encountered a terse piece of code which I am finding very difficult to decipher. ``` for (int k = 0; k < count; k++) { C[p=w[T[k]]++] = Y1[k]; CC[p] = Y2[k] } ``` w and T look like this: ``` w = [0 3 6 8] T = [2 0 3 2 1 0 1 3 0 1] ``` I am unable to figure what is the index that the arrayCandCCare g...
Rewrite it. This code is equivalent to: ``` for (int k = 0; k < count; k++) { p = w[T[k]]++; C[p] = Y1[k]; CC[p] = Y2[k] } ``` which is the same as ``` for (int k = 0; k < count; k++) { p = w[T[k]]; // For k=0 => w[2]=6 => p=6 w[T[k]]++; // For k=0 => increment w[2], so w[2] is 7 C[p] ...
I recently noticed that ``` void foo(int array[10]); ``` Does not load the stack with the content of array whenfoois called, so the declaration is equivalent to: ``` void foo(int *array): ``` I would like to find the section in the C99 standard that assert this behavior, but I don't find anything or I don't know w...
C11 6.7.6.3 §7. (C99 6.7.5.3 §7) A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation. The term is formally named "array adjustment". Informally outside the C s...
I have written a simple command-line based audio player in C using libVLC library. Every time a audio file is played, an album art (.jpg format) and a directory in the track's name will be created for each track, inside '~/.cache/vlc' folder which is taking up significant disk space and creating lots of directories. I...
The easiest way I found around this knotty little issue was to create the directory$HOME/.cache/vlc/artand simply make itread only.If vlc can't write to it:a. The issue disappearsb. vlc doesn't complain about it.
ing_hash_table_new(HashFunc hash_func, GEqualFunc key_equal_func) HashFunc they have this types: g_direct_hash()g_int_hash()g_int64_hash()g_double_hash()g_str_hash() GEqualFunc they have this types: g_direct_equal()g_int_equal()g_int64_equal()g_double_equal()g_str_equal() Which type can i use to have a key that i...
Summarizing from comments: Assuming you build for a system where a pointer is at least as many bits as a long (true on most systems), yes, you can cast it to agconstpointerand useg_direct_*. You do build in a dependency on that fact into your code that way though. Otherwise: do not uselongbut eithergintorgint64for y...
I am facing difficulty in converting a binary array to a decimal number: ``` bin[8] = {10,00,00,10}; ``` I want the equivalent of this array element as a decimal number, i.e.130.
A standard solution goes like this: ``` int f(char s[]) { int n = 0; int i; for (i = 0; i < 8; ++i) { n <<= 1; n += s[i] - '0'; } return n; } ```
I'm exploring regex, but I simply could not achieve exactly what I want yet. I'm using NetBeans and I need to swap allstrncpy(... , sizeof(x))tostrncpy(... , sizeof(x) -1 ), i.e, add the"-1"between the last parenthesis. An example should be: ``` strncpy(data->error, t_result[ID(data->modulo)].status, sizeof(data->er...
See regex in use here ``` (strncpy\(.*?sizeof\([^)]*\)) ``` (strncpy\(.*?sizeof\([^)]*\))Capture the following into capture group 1strncpy\(Matchesstrncpy(literally.*?Matches any character any number of times, but as few as possiblesizeof\(Matchessizeof(literally[^)]*Matches any character except)any number of times\...
I have .so file which I take from apk. With command nm -D libnative-lib.so I took list of functions. I need to call function namedJava_com_example_nativelib_utils_Constants_getStringFromJNI. I wrote the code below: ``` #include <stddef.h> #include <dlfcn.h> #include <stdio.h> int init_library() { void* hdl = dlo...
It is not possible to use android .so files in non-android project. similar question ishere
I have the following code (simplified for here). ``` #include <stdio.h> #include <stdlib.h> struct inner { int a; int b; }; struct outer { struct inner *next; struct inner *prev; }; int main(int argc, char *argv[]) { struct outer *c = malloc(sizeof(struct outer)); if (c->next) { p...
A.malloc()does not initialize memory to zero, so your pointers are not necessarilyNULL B. accessing an uninitialized pointer results in undefined behavior C.c->nextandc->next != NULLare basically the same condition check
Suppose I have the variable declarationchar **p. Does that mean thatpis a pointer to acharpointer or thatpis a pointer to a pointer of some type that points to achar? There is a subtle difference between these two chains of pointers. In other words, what I am trying to ask is given acharpointer to a pointerchar **p,...
The type of*pis alwayschar *. It cannot be avoid*that happens to be pointing to achar.
Why does the first printf() output 1 and the second one 8589934593? EDIT: Why does the second one output exactly 8589934593 and not some other number? ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]){ int *intPtr = NULL; long *longPtr = NULL; int array[5] = {0,1,2,3,4}; in...
Because it's undefined behavior. Pointing along*to the address of anintand acting like it's alongviolates the strict aliasing rule, giving you undefined behavior.
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.Closed5 years ago.Improve this question How to store a symmetric key safely? Can I use pkcs12 to store this symmetric key?
Simple Answer: It is impossible. As soon as "you" store the key, it is unsafe as your program is just a usual program running on a computer. Some better ways (depending on your use-case) - use hardware tokens and their associated drivers / APIs - use the operating system's crypto APIs and credential stores - encryp...
Being a Javascript programmer, I'm really not quite familiar with the compiling process. My problem is locating source files during compilation with Emscripten. My "include"-commands refer to source code, such as "Core/main.h", which in turn refers to other source files in the same folder, yet using a similar address,...
It's the one argument that is the same on virtually every C/C++ compiler: -I ``` emcc -Idir1 -Idir2 ... foo.c ``` Where the file is at dir1/Core/app.h.
I need to write a function which gets an array, it's size and a pointer, I need to check if the pointer exists in the array and if so, print all the elements after it and i'm not allowed to create local variables or use []. This is what i did to find whether the pointer exists or not. ``` void printAfterX(int* arr, i...
I'll give you two hints: (1) Function parameters are l-values. (2) Eventually recursion. You should try both, even if recusion is an overkill here.
I'm confused. Why in this programagives me0xFFFFFFA0butbgives me0xA0? It's weird. ``` #include <stdio.h> int main() { char a = 0xA0; int b = 0xA0; printf("a = %x\n", a); printf("b = %x\n", b); } ```
Default type ofaissignedinchar a = 0xA0;and in anysigned data typewhether itschar of intyou should be careful ofsign bit, ifsign bitissetmeans number will be negative and store astwo's complimentway. ``` char a = 0xA0; /* only 1 byte for a but since sign bit is set, it gets copied into remaining bytes ...
``` #include <stdio.h> int main() { int i[ ] = {3, 5}; int *p = i; int j = --*p++; printf("j = %d\n\n", j); return 0; } ``` Can someone explain to me why the answer is "j = 2"? This code from the course notebook; they didn't explain it in the book.
This behavior can be described asoperator precedenceand it's something to do with how C compiler processed your code. In this case, the postfixed++operator takes precedence over*operator and incremented the pointer-to-arrayafteryou decremented the value of the dereferenced pointer with prefixed--, safe to say it's sim...
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.Closed5 years ago.Improve this question How to store a symmetric key safely? Can I use pkcs12 to store this symmetric key?
Simple Answer: It is impossible. As soon as "you" store the key, it is unsafe as your program is just a usual program running on a computer. Some better ways (depending on your use-case) - use hardware tokens and their associated drivers / APIs - use the operating system's crypto APIs and credential stores - encryp...
Being a Javascript programmer, I'm really not quite familiar with the compiling process. My problem is locating source files during compilation with Emscripten. My "include"-commands refer to source code, such as "Core/main.h", which in turn refers to other source files in the same folder, yet using a similar address,...
It's the one argument that is the same on virtually every C/C++ compiler: -I ``` emcc -Idir1 -Idir2 ... foo.c ``` Where the file is at dir1/Core/app.h.
I need to write a function which gets an array, it's size and a pointer, I need to check if the pointer exists in the array and if so, print all the elements after it and i'm not allowed to create local variables or use []. This is what i did to find whether the pointer exists or not. ``` void printAfterX(int* arr, i...
I'll give you two hints: (1) Function parameters are l-values. (2) Eventually recursion. You should try both, even if recusion is an overkill here.
I'm confused. Why in this programagives me0xFFFFFFA0butbgives me0xA0? It's weird. ``` #include <stdio.h> int main() { char a = 0xA0; int b = 0xA0; printf("a = %x\n", a); printf("b = %x\n", b); } ```
Default type ofaissignedinchar a = 0xA0;and in anysigned data typewhether itschar of intyou should be careful ofsign bit, ifsign bitissetmeans number will be negative and store astwo's complimentway. ``` char a = 0xA0; /* only 1 byte for a but since sign bit is set, it gets copied into remaining bytes ...
``` #include <stdio.h> int main() { int i[ ] = {3, 5}; int *p = i; int j = --*p++; printf("j = %d\n\n", j); return 0; } ``` Can someone explain to me why the answer is "j = 2"? This code from the course notebook; they didn't explain it in the book.
This behavior can be described asoperator precedenceand it's something to do with how C compiler processed your code. In this case, the postfixed++operator takes precedence over*operator and incremented the pointer-to-arrayafteryou decremented the value of the dereferenced pointer with prefixed--, safe to say it's sim...
Being a Javascript programmer, I'm really not quite familiar with the compiling process. My problem is locating source files during compilation with Emscripten. My "include"-commands refer to source code, such as "Core/main.h", which in turn refers to other source files in the same folder, yet using a similar address,...
It's the one argument that is the same on virtually every C/C++ compiler: -I ``` emcc -Idir1 -Idir2 ... foo.c ``` Where the file is at dir1/Core/app.h.
I need to write a function which gets an array, it's size and a pointer, I need to check if the pointer exists in the array and if so, print all the elements after it and i'm not allowed to create local variables or use []. This is what i did to find whether the pointer exists or not. ``` void printAfterX(int* arr, i...
I'll give you two hints: (1) Function parameters are l-values. (2) Eventually recursion. You should try both, even if recusion is an overkill here.
I'm confused. Why in this programagives me0xFFFFFFA0butbgives me0xA0? It's weird. ``` #include <stdio.h> int main() { char a = 0xA0; int b = 0xA0; printf("a = %x\n", a); printf("b = %x\n", b); } ```
Default type ofaissignedinchar a = 0xA0;and in anysigned data typewhether itschar of intyou should be careful ofsign bit, ifsign bitissetmeans number will be negative and store astwo's complimentway. ``` char a = 0xA0; /* only 1 byte for a but since sign bit is set, it gets copied into remaining bytes ...
``` #include <stdio.h> int main() { int i[ ] = {3, 5}; int *p = i; int j = --*p++; printf("j = %d\n\n", j); return 0; } ``` Can someone explain to me why the answer is "j = 2"? This code from the course notebook; they didn't explain it in the book.
This behavior can be described asoperator precedenceand it's something to do with how C compiler processed your code. In this case, the postfixed++operator takes precedence over*operator and incremented the pointer-to-arrayafteryou decremented the value of the dereferenced pointer with prefixed--, safe to say it's sim...
I want there to be no border at all. I tried the following code: ``` GtkCssProvider *provider = gtk_css_provider_new (); gtk_css_provider_load_from_data (GTK_CSS_PROVIDER (provider), "entry, .entry, GtkEntry { border-width:0px ; }", -1, NULL); GdkDisplay *display = gdk_display_get_default (); GdkScreen *screen = ...
I fixed it withentry { border:none }
In this program (which basically copies the input into an array & finally display it) --> ``` #include<stdio.h> int main() { int c,i=0; char arr[100]; while((c=getchar())!=EOF) { if((((c>=65)&&(c<=90))||((c>=97)&&(c<=122)))||(c==' ')||(c=='\t')) arr[i]=c; i++; } prin...
printf%stakes a string. You're passing itarr, which is not a string. A string needs a'\0'terminator to mark the end.
I wrote this C code to find the value for 3 squared. ``` #include <stdio.h> #include <math.h> int main( void ) { float a; a = powf( 3, 2 ); printf( "\n%f\n", a ); return 0; } ``` I get the warningimplicit declaration of function 'powf'even withmath.hlibrary included and-lmin the terminal command: ``...
powfis added in C99. Option-ansiis equivalent to-std=c89. You need to use-std=c99flag. ``` gcc -o test.exe -std=c99 -Wall test.c -lm ```
I know that it is possible to close an application by calling theexit(0)function. And that by using it, all heap-allocated memory prior to the call is cleared. So you do not have to worry about it. But to debug your program and investigate better if there is a memory leak, it is not practical to close the program wit...
You can use WINAPISendMessagewithWM_CLOSEfor theMsgparameter. Here more about this function:SendMessage
``` typedef int score; typedef struct tnode *ptrtonode; typedef ptrtonode tree; struct tnode{ score s; tree next; bool know; }; scanf("%d",&n); tree t[n]; for(i=0;i<n;i++){ scanf("%d",&x); t[i]->s=x; t[i]->next=NULL; t[i]->know=false; } ``` This is a code snippet. When it runs 't[i...
treeis of typestruct tnode *.tree t[n];declarestas an array ofnpointer tostruct tnode(struct tnode *). You need to allocate memory to these pointers before accessing memory they points to.
I'm new to C and wanted to know, what does a bitwise shift 1 << 9 in an enum definition do in this case below: ``` static enum { DEAD, LIVE } state[1 << 9]; ```
The expression1<<9is the same as 29, which is 512. So an array of 512 enums is declared.
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 How does gcc manage to compile printf in ANSI-C? Every printf prototype I saw used varargs, but that is no...
You assumptions are all wrong. First, there is nothing called "ANSI-C" after the year 1990. Americans may refer to the C standard as INCITS/ISO/IEC 9899:2011, but nobody outside the US cares. We just call it ISO C. The C language has (unfortunately) always supported variadic functions, for the past 40 years or so. I...
What happens when I have multiple#defines with the same name in one sourcefile: for example: ``` #define Dummy 1 #define Dummy 2 ``` I do NOT intend to use it, but saw something similar in production code. Is this covered by the standard?
It's constraint violation and as such, a conforming compiler is required to issue a diagnostic. C11, 6.10.3 Macro replacementstates: An identifier currently defined as an object-like macro shall not be redefined by another #define preprocessing directive unless the second definition is an object-like macro definitio...
This question already has an answer here:Is it OK to name a variable with the same name as a structure tag?(1 answer)Closed5 years ago. In C, can a field of a struct and a variable have the same name? Are there gonna be any issues? For example: ``` struct foo { int x } main() { struct foo j; int x = 666...
In C, can a field of a struct and a variable have the same name? Yes. That's becausestructs have their own namespace.C11 §6.2.3 Name spaces of identifiers [...] Thus, there are separate name spaces for various categories of identifiers, as follows:— the members of structures or unions; each structure or union has a ...
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 So I used this code in order to pass a variable in to my struct: ``` strcpy(s[i].orderName, Name); ``` an...
You can use a simple assignment=for theintvariables: ``` struct abc { int a; int b; }; void foo(int b) { struct abc x; x.a = 8; x.b = b; printf("x.a: %d\n, x.b: %d\n", x.a, x.b); } ```
I allocated 5 bytes of memory using malloc and I was able to use those 5 bytes to store characters or integers. For example,use the first byte to store a character and the next four bytes to store an integer. How does malloc takes care of memory allignment issues?
malloc If allocation succeeds, returns a pointer to the lowest (first) byte in the allocated memory block that is suitably aligned for any object type. So the memory block is aligned for any object type. use the first byte to store a character and the next four bytes to store an integer. That's not valid. Yo...