question
stringlengths
25
894
answer
stringlengths
4
863
I was studying the book "Data Structure and algorithms made easy" and but I got confused while learning "Comparing Linked Lists and Unrolled Linked list"... what is overhead? Why he is only stating 8 bytes of overhead for 100 elements array?
Overhead is all the stuff that is not part of the data that you want to store. Like the pointers to the next and previous element. The block list is a list of arrays. Each array contains a number of elements. In principle your entire list could consist of a single block node with an array of all your elements. So les...
Let's assume we have 2 programs written in C, one program allocates memory with malloc and launches the second program passing the address of allocated memory and size as arguments. Now the question, is it possible for the second program to cast the first argument to a pointer and read/write to that memory. Why, why ...
No, because on modern operating systems processes running in user mode seeVirtual Memory. The same virtual address will translate to a different physical address or page file location between processes. Fortunately, most operating systems do have APIs that allow for inter-process communication, so you can research th...
I've got an array of unsigned chars that I'd like to output to a file using the C file I/O. What's a good way to do that? Preferably for now, I'd like to output just one unsigned char. My array of unsigned chars is also non-zero terminated, since the data is coming in binary.
I'd suggest to use functionfwriteto write binary data to a file; obviously the solution works for arrays ofSIZE==1as well: ``` int main() { #define SIZE 10 unsigned char a[SIZE] = {1, 2, 3, 4, 5, 0, 1, 2, 3, 4 }; FILE *f1 = fopen("file.bin", "wb"); if (f1) { size_t r1 = fwrite(a, sizeof a[0], SIZ...
I'm doing a homework assignment in C and I've run into a little trouble. After calculating two values, I have to be able to print the highest of two valueswithoutusing logical operators, relational operators, or selection constructs. I've already used calculations that determine the larger of the two values, but I d...
I would use the functionfmax. It takes doubles as arguments, so you may have to cast your numbers into doubles.
I need a way to implement a doubly linked list using only an array and no pointers in C. There's is a mention of this in Thomas Cormen but I can't think of a way to actually implement it.
Instead of using pointers which, in C, are usually numbers that index into the address space, use integer indexes into your array as references to the previous and next members e.g. ``` struct Element { int next; int prev; // Any data you want for this element in the list }; struct Element array[MAX_EL...
how do I perform a signed right shift in c? like -25 >> 3. I tried like this: 10011001 >> 3 == 00010011 But the result is -4.
According to the standard 6.5.7p5 The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 /2E2. If E1 has a signed type and a negative value, the resulting value is ...
I was studying the book "Data Structure and algorithms made easy" and but I got confused while learning "Comparing Linked Lists and Unrolled Linked list"... what is overhead? Why he is only stating 8 bytes of overhead for 100 elements array?
Overhead is all the stuff that is not part of the data that you want to store. Like the pointers to the next and previous element. The block list is a list of arrays. Each array contains a number of elements. In principle your entire list could consist of a single block node with an array of all your elements. So les...
result of printf("%d\n", 5.0 + 2); is 0 but ``` int num = 5.0 + 2; printf("%d\n", num); ``` is 7 What's the difference between the two?
The result of5.0 + 2is7.0and is of typedouble. The"%d"format is to printint. Mismatching format specification and argument type leads toundefined behavior. To print afloatordoublevalue withprintfyou should use the format"%f". With ``` int num = 5.0 + 2; ``` you convert the result of5.0 + 2into theintvalue7. Th...
I'm trying to practice with left child-right sibling representation of a tree and I really can't figure out how to find the number of nodes given a certain height. ``` 10 | 2 -> 3 -> 4 -> 5 | | 6 7 -> 8 -> 9 ``` For example if I choose height 0 than the function should r...
Recurse: If the tree is empty, it is 0.If the heightHis0, it is 1 + the number of siblings.Otherwise, it is the sum of the nodes at heightH-1in the child and at heightHin the siblings.
One of member of theWNDCLASSstructure is handle to the class background brush. From description: This member can be a handle to the physical brush to be used for painting the background, or it can be a color value. A color value must be one of the following standard system colors (the value 1 must be added to the ch...
It may be because thehbrBackgroundfield acceptNULLvalue. It's forRegisterClass()function to make the difference betweenCOLOR_SCROLLBARwhich is0andNULLwhich is an acceptable value.
One of member of theWNDCLASSstructure is handle to the class background brush. From description: This member can be a handle to the physical brush to be used for painting the background, or it can be a color value. A color value must be one of the following standard system colors (the value 1 must be added to the ch...
It may be because thehbrBackgroundfield acceptNULLvalue. It's forRegisterClass()function to make the difference betweenCOLOR_SCROLLBARwhich is0andNULLwhich is an acceptable value.
Consider the given 2d array allocation: ``` int (*some)[10] = malloc(sizeof(int[10][10])); ``` This allocates a 10 x 10 2d array. Apparently its type isint (*)[10]. I want to write a functioninitialize()that will allocate it, initialize it and then return a pointer to the array, so that the constructionsome[i][j]wou...
``` int (*initialize(void))[10] { ... } ``` initializeis a function, which takes no parameters and returns a pointer to an array of10int. You should use atypedeffor that.
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.Closed4 years ago.Improve this question I am writing a socket programming in C to transfer files from Server to Client. where client sends a filena...
In your communication model, you are missing a layer of meta-data or control messages. at the minimum, you need to pass a status code before you return the file. I suggest that you implement a simplified version of HTTP client. you can find an example at: GitHub - reagent/http: Simple HTTP client in C
I am trying to send/receive data with J1939 protocol. So in PIC18F26K83 there are 3 modes for can bus Mode 0: Legacy, Mode 1: Enhanced Legacy and Mode 2: FIFO. I want to use 29 bit extended identifier messages but I am not sure if i can use Mode 0 for this operation. In datasheet it is not really clear and in some lin...
I can not see why you can't use 29 bits identifiers in Mode 0. Literally, I can't see in the datasheet where it says anything about it. Besides, what it does say is that Mode 0 is made to be fully compatible with PICs like 18Fxx8, which are actually compatible with 29 bits identifiers.
This question already has answers here:What does "%3d" mean in a printf statement?(8 answers)Closed4 years ago. can someone explain what the 25 in front of d does in an printf command ? I have searched the web but don't find a good answer. e.g.: printf("%-30s %10lu %25d - %ud\n", "unsigned int", sizeof(unsigned...
%d indicates decimal value.25 total field width.
I am new to the C programming language and I am trying to understand the intent of a function which takes a pointer argument but uses the address of operator on it as though it was a variable name in the function's body? The parameters being passed are of type struct. In other words, why did the author choose to use ...
The address-of operator is not being applied to the pointerlibbut to thefatfsmember of the pointed to object. The->operator has higher precedence then the unary&operator. That means that&lib->fatfsis the same as&(lib->fatfs). This should make it more clear what&is taking the address of.
I am trying to convert NV12 raw data to H264 using hw encoder of FFMPEG. to pass raw data to encoder I am passing AVFrame struct using below logic: ``` uint8_t * buf; buf = (uint8_t *)dequeue(); frame->data[0] = buf; frame->data[1] = buf + size; frame->data[2] = buf + size; frame->pts = frameCoun...
I solved color mismatch issue by passing correct linesize and data value of AVFrame struct. Let's say NV12 has YYYYUVUV plane for 4x4 image, then in ffmpeg, we need to pass linesize[0] = start location of y linesize[1] = 4 because location of u started at 4 and we dont need to specify linesize[2] because uv are pac...
I am trying to send/receive data with J1939 protocol. So in PIC18F26K83 there are 3 modes for can bus Mode 0: Legacy, Mode 1: Enhanced Legacy and Mode 2: FIFO. I want to use 29 bit extended identifier messages but I am not sure if i can use Mode 0 for this operation. In datasheet it is not really clear and in some lin...
I can not see why you can't use 29 bits identifiers in Mode 0. Literally, I can't see in the datasheet where it says anything about it. Besides, what it does say is that Mode 0 is made to be fully compatible with PICs like 18Fxx8, which are actually compatible with 29 bits identifiers.
This question already has answers here:What does "%3d" mean in a printf statement?(8 answers)Closed4 years ago. can someone explain what the 25 in front of d does in an printf command ? I have searched the web but don't find a good answer. e.g.: printf("%-30s %10lu %25d - %ud\n", "unsigned int", sizeof(unsigned...
%d indicates decimal value.25 total field width.
Hi I am working on a monty hall generator and in part of my code I need it to generate random number 2 or 3. It cannot be 1,2,3 but the computer needs to select between 2 or 3. Thanks! I have triedrandomCarDoor = ( rand() % 3 ) + 1;but does not work. randomCarDoor = ( rand() % 3 ) + 1; It gives me the number1,2,3b...
You can use the low order bit of the random value, but it is very risky as some pseudo-random number generators do not provide adequate dispersion on low order bits: ``` int two_or_three = 2 + rand() % 2; ``` A much better way is to use the magnitude of the random number which is specified as having a flat distribut...
I need a Raspberry Pi - which I am coding in C - to be able to communicate with an HTTP server, similar to how a dynamic web page can use AJAX to interact with its origin server. How do I do that? Do I callsystem()with a URL as parameter? Or it there some other way to do it?
The very simplest way would be to use asystem()call with curl. For example: ``` #include <stdlib.h> int main() { system("curl http://example.com/"); } ``` This will send aGETrequest to example.com and print the output. Depending on your application, that might be enough. (See themanpagefor more options.) Howev...
This question already has answers here:Resize an Array while keeping current elements in Java?(12 answers)Closed4 years ago. I don't know how should I type the new resized array. I create this in C... ``` void main() { int=1; int h[a]; a++; h[a]; h[1]=2; printf("%d",h[1]); } ```
You can't do it like that. If you want to dynamically change the size of the array, you would have to usenewoperator. You have allocate a new array with higher size and then copy all the old elements. Something like below. ``` int sz = 1; int[] h = new int[sz]; sz++; int h1 = new int[sz]; for (int i = 0; i < h.length...
This question already has answers here:What can happen if printf is called with a wrong format string?(5 answers)Closed4 years ago. Below is the C program and the output is 201. I have no idea how this is possible. Please explain this. ``` #include <stdio.h> int main() { int number = 288; char * ptr; p...
The 201 is perfectly reasonable (on little-endian systems): The variablenumberstarts with these two bytes (on little-endian systems): 0x20, 0x01.
I tried to compile a.cfile but it returns the error: ``` yay.c:6:19: fatal error: netdb.h: No such file or directory #include <netdb.h> ^ compilation terminated. ``` I did some research and apparently.his a header file for C... I am new to C so I don't know what to do.
Dolocate netdb.hunderunixto find out (the filepath). Underopenbsdit is in located at/usr/include/netdb.h(installed with thecompXXfile set, and not being packaged asglibc) cheaders are usually placed in/usr/includeand/usr/local/includedirectories depending on if they are system or local (third-party, custom), respect...
---EDIT--- The array was previously initialized as a pointer (*arr). For a problem I´m trying to solve, I need to go through an array of variable size and started using this loop: ``` int arr[] = {3, 5, 10, -2, -1, -3}; // Just an example int i = 0; while(arr[i]) { //do something i++; } ``` It seems that...
int *arris not the array. intis not the type which should be used as the index. Usesize_tinstead Array int arr[50];<- this the array you can get the size of the array dividing its size by the size of the element. pointer int *ptr;it only references the int object. Youcantget the size of the allocated memory by ...
This question already has answers here:Resize an Array while keeping current elements in Java?(12 answers)Closed4 years ago. I don't know how should I type the new resized array. I create this in C... ``` void main() { int=1; int h[a]; a++; h[a]; h[1]=2; printf("%d",h[1]); } ```
You can't do it like that. If you want to dynamically change the size of the array, you would have to usenewoperator. You have allocate a new array with higher size and then copy all the old elements. Something like below. ``` int sz = 1; int[] h = new int[sz]; sz++; int h1 = new int[sz]; for (int i = 0; i < h.length...
This question already has answers here:What can happen if printf is called with a wrong format string?(5 answers)Closed4 years ago. Below is the C program and the output is 201. I have no idea how this is possible. Please explain this. ``` #include <stdio.h> int main() { int number = 288; char * ptr; p...
The 201 is perfectly reasonable (on little-endian systems): The variablenumberstarts with these two bytes (on little-endian systems): 0x20, 0x01.
I tried to compile a.cfile but it returns the error: ``` yay.c:6:19: fatal error: netdb.h: No such file or directory #include <netdb.h> ^ compilation terminated. ``` I did some research and apparently.his a header file for C... I am new to C so I don't know what to do.
Dolocate netdb.hunderunixto find out (the filepath). Underopenbsdit is in located at/usr/include/netdb.h(installed with thecompXXfile set, and not being packaged asglibc) cheaders are usually placed in/usr/includeand/usr/local/includedirectories depending on if they are system or local (third-party, custom), respect...
I have following struct defined which I can not change: ``` typedef struct _content { int length; char **lines; } content_t; ``` I initialized it in the main function like that: ``` struct _content cont; cont.length = 6; cont.lines[cont.length-1][255]; ``` I try to assign a value to a certain element o...
``` int main(){ content_t cont; cont.length = 6; cont.lines=malloc(sizeof(char*)*cont.length); for(int i=0;i<cont.length;i++) cont.lines[i]=malloc(255); printf("\n\n%c", cont.lines[1][1]); for(int i=0;i<cont.length;i++) free(cont.lines[i]); free(cont.lines); } ``` that's the right way to do it
I have a MIDI controller with several knobs. Is it possible to query state of all values, which these knobs have, when I connect to the device usingmidiInOpenfunction without physically moving each of them?
There is no standard MIDI message to inquire about the current state of a controller; messages are sent only when something changes. Unless your controller has a vendor-specific extension that does exactly what you want, this is not possible.
I want to print function names (imported, exported, normal/local functions) but not variable names and so on. SymEnumSymbolsExenumerates all symbols, but I only want functions. Also can not find how to distinguish functions and variables insidecallbackfunction. Is there a way to enumerate only functions?
SYMBOL_INFOpassed to your callback hasFlags, and there isSYMFLAG_FUNCTIONfor functions
I have to create a function void destroy(int ***matrix); use to deallocate the matrix And i dont know how can i deallocate it without knowing its sizes I'd some ideas or an example of a code.
You have to have a convention that only pointers before a sentinel value (e.g.NULL) need to be freed. ``` void destroy (int ***matrix) { if (matrix == NULL) return; for (int i = 0; matrix[i]; ++i) { for (int j = 0; matrix[i][j]; ++j) { free(matrix[i][j]); } free(matrix[i])...
While i was creating my own malloc, I used write to print some value. I don't have any problems to print value, I just create a char variable to stock my number and print it, but I don't understand why the cast doesn't work. The prototype of write is: ssize_t write(int fd, const void *buf, size_t count) So i cast m...
Yes, but it's not acast, it's acompound literal: ``` write(1, (char[]){nb + '0'}, 1); ``` or: ``` write(1, &(char){nb + '0'}, 1); ```
I am looking for a simple answer to a simple question but I have yet to find a straight forward answer. For the Hamming code sequence (7 4), it can either do 1-bit detection and correction or 2-bit error detection. I would like to know the same thing for the (255 247) Hamming sequence. If there is an algorithm to wo...
Theminimum hamming distancedetermines the error detection/correction capabilities of a code. Hamming codes(eg.Hamming(7,4)or Hamming(255,247)) have a hamming distance of 3 (d = 3), so can detect 2-bit errors (d - 1 = 2) or correct 1-bit errors ((d - 1) / 2 = 1).
by checking the serial folder @: \drivers\tty\serial There are many different serial port drivers there, which one is for x86?
There is no single UART chip for x86.The IBM PC originally used the8250, later it began customary to replace it with the16550and later with the 16750.With the advent ofSuperIO chipseach manufacturer had their implementation of the UART but all were more or less compatible with the 16550/750 and the 8250.Today chipsets...
I have two numbers of char type say ``` char* N1; char* N2; N1 = "92345610172222"; N2 = "12351097654671"; ``` I need to add MSD's of two numbers i.e 9 + 1 = 10 I solved by typecasting and dividing the number until it encounters a single digit using two loops.Sum it and return the result. ``` int sumMsd(char *N1,...
This should work. ``` int sumMsd(char *N1, char *N2) { return (N1[0] - '0') + (N2[0] - '0'); } ``` Let the first digit of N1 be '3'. Then '3' - '0' is 3, the difference between their ASCII values.
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.Closed4 years ago.Improve this question I want to assign integer value to character.Where 'C' has the least and 'B' largest valu...
You can use designated array initializers: ``` // UCHAR_MAX is from header <limits.h> int const map[UCHAR_MAX] = { ['C'] = 100, ['D'] = 101, ['B'] = 126, }; ``` Unassigned characters will have zero value. You would then get single value with expression: ``` int value = map[(unsigned char)character]; ``...
``` short int cipher[50],len; while(cipher != 0) { cipher=cipher/10; ++len; } ``` Need to count number of digits provided by user. ``` error: invalid operands to binary / (have ‘short int *’ and ‘int’) cipher=cipher/10; ```
As gsamaras noted, you definedcipheras an array of 50short ints. Presumably you want only one number, so you'd define it e. g. aslong long cipher;(C is not COBOL or something where one has to specify the number of digits). And don't forget to initializelen.
I have a question i came across embedded software development. I can programme gui and flash Arm Cortex m3/m4 proceesors with spi I2c uart bus interfaces. I can make decent gui on it using libraries like qt or emwin. My question is can i flash android tablet with my own gui on it. I mean i dont want android os on my...
The closest you can get is runningPostmarketOS, which is Linux Distribution with GNU userland for Android Devices. Developing a custom firmware is hardwork. Checkout the PostmarketOS website for the list of devices Compatible.
I am using a tool that has been written in C or C++. https://github.com/kern-lab/discoal I've never used C myself. In one of the files in discoal.h, I want to change:#define MAXSITES 220020to#define MAXSITES 1100000. The tool manual says that I would have change the MAXSITES define in discoal.h and then recompile. ...
Open a terminal, cd to the directory where the Makefile is, and typemake, then hit Enter. Prerequisites: A C compiler, which comes with Xcode on a Mac, as @Shawn commented.
I made the core dumped error with the two pieces of codes below: ``` //test.cpp int main() { int *p = new int; *p = 100; delete p; delete p; return 0; } //test2.cpp int main() { int *p = new int; *p = 100; delete p; *p = 111; std::cout<<*p<<std::endl; return 0; } ``` Gdb ...
The SIGABRT isexplicitly detected and signaledby the implementation ofdeletewhose detected the invalidity of the second delete. It is launch by calling theabortfunction The SIGSEGV is different, it isundergoingrather than detected by a check in a library like the previous, it is launch through the memory management o...
I'm trying to build libjpeg-turbo from source to include 12 bit support. I downloaded the source code fromhere(2.0.1) then followed instruction given in Building.md ``` cd libjpeg-turbo-2.0.1 mkdir build && cd build cmake -G"Unix Makefiles" -D WITH_12BIT=1 -D WITH_TURBOJPEG=1 .. make -j8 sudo make ins...
Line 201 ofCMakeLists.txtturnsWITH_TURBOJPEGoff when building withWITH_12BITenabled. Don't enableWITH_12BITand thenWITH_TURBOJPEGwill be default enabled and should build those libraries.
Today I had troubles with corrupted heap on ESP32. As it turned out, bug was caused by this line: ``` u8x8_i2c_cmdinfo* cmdinfo = malloc(sizeof(cmdinfo)); ``` When I meant ``` u8x8_i2c_cmdinfo* cmdinfo = malloc(sizeof(u8x8_i2c_cmdinfo)); ``` It actually surpriszed me a lot that wrong version compiled at all. Why ...
The code compiles because variable exists after its declaration. And this part just declared it:u8x8_i2c_cmdinfo* cmdinfo. You wouldn't be surprised if that worked, right? ``` u8x8_i2c_cmdinfo* cmdinfo; cmdinfo = malloc(sizeof(cmdinfo)); ``` Keep in mind, that while your code compiles fine, it has a nasty bug. You ...
I have a question i came across embedded software development. I can programme gui and flash Arm Cortex m3/m4 proceesors with spi I2c uart bus interfaces. I can make decent gui on it using libraries like qt or emwin. My question is can i flash android tablet with my own gui on it. I mean i dont want android os on my...
The closest you can get is runningPostmarketOS, which is Linux Distribution with GNU userland for Android Devices. Developing a custom firmware is hardwork. Checkout the PostmarketOS website for the list of devices Compatible.
I am using a tool that has been written in C or C++. https://github.com/kern-lab/discoal I've never used C myself. In one of the files in discoal.h, I want to change:#define MAXSITES 220020to#define MAXSITES 1100000. The tool manual says that I would have change the MAXSITES define in discoal.h and then recompile. ...
Open a terminal, cd to the directory where the Makefile is, and typemake, then hit Enter. Prerequisites: A C compiler, which comes with Xcode on a Mac, as @Shawn commented.
Somewhat of a beginner here. Ex: 12cx7,14:53:00,0.968900025,0,0,,0, The end has no value in this case (for this problem the value can be 1-4 but I think the way I read it should be fine) The way I was thinking of handling it was to handle it the same way I would a double comma (an empty mid value) using strstr to f...
you can just add an extra ',' at the end of the string to parse, so you will get the last field between the last two ',' if the last field is present you will get it, if it is absent you will get an empty string
I would like to use Windows SDK 7.1 to compile some C functions in Matlab r2014b. Now I wonder which C standard the compiler follows? My previous research in google (no study of manuals) did not yield a result yet. Furthermore I would like to know if it is possible to change the used standard.
When I run the commandcl.exe /?on the Windows SDK 7.1 Command Prompt, it reports version number16.00.30319.01, which, according to the accepted answer onthis questionis the version of the compiler that ships with Visual Studio 2010. According toWikipedia, Microsoft did not begin to add support for C99 until Visual St...
This question already has answers here:What is E in floating point?(4 answers)Scanf/Printf double variable C(3 answers)Closed4 years ago. When I run the code below ``` int main(int argc,char *argv[]) { double n = 2E-1; printf("%d",n); } ``` When I run the code it prints a weird number instead of 0.2(2E-1).
What does the constant E do in the c language The documentation for floating-point constants ishere. The form1e2or1E2means1times ten to the power of2, and you're perfectly correct that2E-1means2times ten to the power of-1, or0.2. It's based on the scientific E notation linked by Eugene. When I run the code it prin...
I get an error when the scanf tries to access titolo[i]->nome and I don't get why ``` typedef struct tit *TITOLO; struct tit { char nome[20]; }; int main() { TITOLO *titolo; titolo =(TITOLO *) malloc(4*sizeof (TITOLO)); if (titolo == NULL) exit(1); int i; for (i=0;i<4;i++) { printf("...
typedef struct tit *TITOLO;defines TITOLO as a pointer type, not a struct type. Get rid of this and typedef the struct instead: ``` typedef struct { char nome[20]; } TITOLO; TITOLO* titolo = malloc(4*sizeof(*titolo)); ```
If I run this code: ``` float a=1.123456789; printf("The float value is %f\n",a); double b=1.123456789876543 printf("The double value is %lf",b); ``` It prints: The float value is 1.123457The double value is 1.123457 The first line is understandable since the precision of float is ~6 decimal digits. But shouldn't ...
The%fformat specifier prints 6 digits of precision by default. If you want to print more digits, you need to add a precision to the format specifier: ``` float a=1.123456789; printf("The float value is %.15f\n",a); double b=1.123456789876543; printf("The double value is %.15lf",b); ``` Output: ``` The float value ...
I have multiple files in a directory, ending with the same name *.html.html, I'm looking for a way to get their names and change them to just *.html using therename()function in c or c++ or any other way to solve this problem
In command line, simply use: ``` ren *.html.html *.html ``` Or, in PowerShell: ``` Dir *.html.html | rename-item -newname { [io.path]::ChangeExtension($_.name, "html") } ``` Shell would be the simplest option and the most sensate to use. Using C would be overkilling it. Any scripting language (python, php) would b...
This question already has answers here:What is E in floating point?(4 answers)Scanf/Printf double variable C(3 answers)Closed4 years ago. When I run the code below ``` int main(int argc,char *argv[]) { double n = 2E-1; printf("%d",n); } ``` When I run the code it prints a weird number instead of 0.2(2E-1).
What does the constant E do in the c language The documentation for floating-point constants ishere. The form1e2or1E2means1times ten to the power of2, and you're perfectly correct that2E-1means2times ten to the power of-1, or0.2. It's based on the scientific E notation linked by Eugene. When I run the code it prin...
I get an error when the scanf tries to access titolo[i]->nome and I don't get why ``` typedef struct tit *TITOLO; struct tit { char nome[20]; }; int main() { TITOLO *titolo; titolo =(TITOLO *) malloc(4*sizeof (TITOLO)); if (titolo == NULL) exit(1); int i; for (i=0;i<4;i++) { printf("...
typedef struct tit *TITOLO;defines TITOLO as a pointer type, not a struct type. Get rid of this and typedef the struct instead: ``` typedef struct { char nome[20]; } TITOLO; TITOLO* titolo = malloc(4*sizeof(*titolo)); ```
If I run this code: ``` float a=1.123456789; printf("The float value is %f\n",a); double b=1.123456789876543 printf("The double value is %lf",b); ``` It prints: The float value is 1.123457The double value is 1.123457 The first line is understandable since the precision of float is ~6 decimal digits. But shouldn't ...
The%fformat specifier prints 6 digits of precision by default. If you want to print more digits, you need to add a precision to the format specifier: ``` float a=1.123456789; printf("The float value is %.15f\n",a); double b=1.123456789876543; printf("The double value is %.15lf",b); ``` Output: ``` The float value ...
I have multiple files in a directory, ending with the same name *.html.html, I'm looking for a way to get their names and change them to just *.html using therename()function in c or c++ or any other way to solve this problem
In command line, simply use: ``` ren *.html.html *.html ``` Or, in PowerShell: ``` Dir *.html.html | rename-item -newname { [io.path]::ChangeExtension($_.name, "html") } ``` Shell would be the simplest option and the most sensate to use. Using C would be overkilling it. Any scripting language (python, php) would b...
This question already has answers here:How to store a variable at a specific memory location?(8 answers)Closed4 years ago. For my embedded systems application, I want to allocate memory from a particular address. I know it can be dangerous but I just want to do it for testing purpose. So If I could point array global...
It's exactly the same.fsp_new_addr[1]is the first element after that address. Of course, as you stated, this can be dangerous, as you are not programmatically allocating memory, but deciding that this bit of memory is going to be a dedicated array for some purpose.
I have to input an array of integers. The length of this array is determined at runtime when the user hits some sentinal key (likely I'll use return) EXAMPLE ``` //input path to be analyzed int n = 0; while(scanf("%d",&input[n])==1){ //?? } } ``` Input: 3 2 1 3 4 5 (return) Then these values are stored ...
You can do it as follows: ``` int main() { char ch; int i=0; int input[100000]; //Or dynamically allocate while(scanf("%c",&ch) && (ch!='\n')){ if(ch==' ') continue; input[i++]=ch - '0'; printf("%d ",input[(i-1)]); } } ```
Consider the following code: ``` #include <stdio.h> #include <inttypes.h> void main(void) { int32_t a = 44; fprintf(stdout, "%d\n", a); fprintf(stdout, "%"PRId32"\n", a); } ``` When is it better to use%dand when would it be better to use"%"PRId32? How do both of those format characters differ? Does thi...
Use%dforintandPRId32forint32_t. Maybe on your platformint32_tis just a typedef forintbut this is not true in general. Using a wrong specifier invokes undefined behavior and should be avoided. As pointed out by @EricPostpischil note that%dis used inside a quoted format string whilePRId32is used outside. The reason fo...
DNM_Manager.c ``` struct DNM_s { uint32_t Addr; uint32_t SerialNum; uint32_t SubnetMask; uint16_t Tick; uint8_t Name[NAME_SIZE]; }DNMTemp; pDNM DNMManager_New(void) //reentrant? { return &DNMTemp; } ``` GeeksForGeekssays: To be reentrant, the function may not use global and static data. ...
Yes. From the tag excerpt ofreentrancy: A subroutine is considered reentrant if it can be safely called before a previous call has completed. In your case, since the function only returns the address of a global (static) variable, which should remain constant after the program starts, the function is well re-entran...
I have astructwith one of its fields annotated withgcc type attribute. ``` struct str { size_t size; /**< Size of string. */ char string[1] __attribute__ ((aligned(__BIGGEST_ALIGNMENT__))); /**< String. */ }; ``` When I run doxygen on this code, struct memberstringis referenced not asData Field, but as aPubl...
In case it is correct that for the documentation the line char string[1] __attribute__ ((aligned(__BIGGEST_ALIGNMENT__))); can be char string[1]; It would be sufficient to define in the doxygen configuration file: PREDEFINED = __attribute__((x))=
I'm currently getting into binary exploitation, so far so good. The only thing that I don't really understand is the difference between %4$d and %4d, for example. I was looking at this guide: http://www.kroosec.com/2012/12/protostar-format2.html and, on the last line, 'minimum field width' is mentioned while %60d i...
The dollar sign inside a format string indicates a position of the variable used in printf. In this way, you may for example have only 1 parameter to the function, but use it 10 times in your format string, or with more parameters, in a different order. Depending on the programming language, you may or may not use mix...
``` result.author = (char *)malloc(sizeof(char)*strlen(temp->author)); strcpy(result.author, temp->author); ``` I'm doing an RPC thing, but that is not the question about. Here i want to allocate and copy string "UNKNOWN" if temp is NULL like the below code. ``` result.author = (char *)malloc(sizeof(char)*strlen(te...
``` result.author = malloc(strlen(temp->author ? temp.author : "UNKNOWN") + 1); strcpy(result.author, temp->author ? temp.author : "UNKNOWN"); ``` it is a shorthand of : ``` if(temp->author) { result.author = malloc(strlen(temp->author) + 1); strcpy(result.author, temp->author); } else { result.autho...
I am trying to create a macro in c, that will take a variable name, and declare it. I could call it like this: ``` MY_MACRO(test); ``` Would produce: ``` int test; ``` In order to achieve this I went this way: ``` #define MY_MACRO(var) / int ##var; / ``` But the compiler doesn't understand this. D...
I wouldn't recommend doing such a thing. Anyway, there are two problems. First of all, to skip a newline, you need\, not/. Second, the##is wrong. What it does is concatenating thevarto theint. So withMY_MACRO(foo)you would getintfoo;, but you wantint foo; The macro needs to be like this: ``` #define MY_MACRO(var) ...
I have structure like below. ``` struct result{ int a; int b; int c; int d; } ``` and union like below. ``` union convert{ int arr[4]; struct result res; } ``` and I type pun as below. ``` int arr1[4] = {1,2,3,5}; union convert *pointer = (union convert *) arr1; // Here is my question, is ...
pointer->res.ais fine but the behaviour ofpointer->res.bis undefined. There could be an arbitrary amount of padding between theaandbmembers. Some compilers allow you to specify that there is no padding between members but of course then you are giving up portability.
Given that ``` void func(void **structs) { UI_Remote_s* a1 = (UI_Remote_s*)structs->Method; //expression UI_Remote_s* a2 = ((UI_Remote_s*)structs)->Method; //correct } ``` The first attempt is wrong. Why?
I would not use this type of casting as it makes code much harder to read. Instead use a temporary variable to store the pointer. It will make the code easier to read and understand. The compiler is very likely to optimize it oout in the generated code. ``` UI_Remote_s **ptr = (UI_Remote_s **)structs; a2 = (*ptr) -> ...
This is in Visual Studio 2015. I have a native C library that I'm using from my .NET Visual C++ code. I'm aware that I have to change the "Common Language Runtime Support" option to "No Common Language Runtime Support" on the property page for each .c file, perthis question. However, even after I have turned that o...
It cleared up on its own eventually. I had restarted Visual Studio a few times and it kept happening, which is why I asked this question. I guess some cache somewhere wasn't being updated or got corrupt or something.
This is in Visual Studio 2015. I have a native C library that I'm using from my .NET Visual C++ code. I'm aware that I have to change the "Common Language Runtime Support" option to "No Common Language Runtime Support" on the property page for each .c file, perthis question. However, even after I have turned that o...
It cleared up on its own eventually. I had restarted Visual Studio a few times and it kept happening, which is why I asked this question. I guess some cache somewhere wasn't being updated or got corrupt or something.
``` void rev(int n){ int rem; printf("reverse of that number is:"); while(n>0) { rem=n%10; n=n/10; printf("%d",rem); } } int main() { int n; printf("enter a number of more than two digits"); scanf("%d",&n); ...
Because you actually didn't reverse number, you are just printing it. If you want to store reversed number and use it later, you have to to doreverse = reverse * 10 + remainder;
i don't understand why when i try to cast my double to int the values ​​after the commas are rounded.. ``` void print_float(double nb) { int negative; int intpart; double decpart = -10.754; int v; negative = (nb < 0.0f); intpart = (int)nb; decpart = nb - intpart; v = (int)(decpart * 1...
Adoublecannot exactly encoded all numbers. It can exactly encoded about 264different values.-10.754is not one of them. Instead a nearby value is used just less than expected. ``` printf("%.24f", -10.754); // -10.753999999999999559463504 ``` Thedecpart * 1000part introduces some imprecision yet the product is still...
I obtain a segmentation fault after the second cudaMalloc. ``` #include <cuda.h> #include <cuda_runtime.h> int main(){ int n=16; float2* a; cudaMalloc((void **) a, n*sizeof(float2)); float2* b; cudaMalloc((void **) b, n*sizeof(float2)); return 0; } ``` However, if I comment out any of the 2 cudaMallo...
You have to pass a pointer to the pointer like this: ``` float2* a; cudaMalloc(&a, n*sizeof(float2)); float2* b; cudaMalloc(&b, n*sizeof(float2)); ``` otherwise, you just cast a dangling pointer to a "pointer to pointer" and the library dereferences a garbage address leading to a segfault.
I am implementing my own C/C++ app using the Qt framework. I want to retrieve the last crash log of my app at the time it crashes and send it to my API. Is there a Apple native or terminal way to retrieve the log or do I have to retrieve it the hard way? Thank you in advance.
Yes, but only if you publish your software via App Store. Crash reports are then gathered by the OS and can be retrieved on the App-Store-developer site. The user has the last say in whether the reports are delivered to Apple/you however.
I am a student, a couple of years messing about with C but no solid period of practising the language. I am trying to perform a walking one and walking zero test on a byte and pretty stuck, any tips would be appreciated. I have two questions. 1) How do I perform a walking Zero? 2) How do I perform a rotate right th...
C does not provide any rotate operation. However, you do not need one for this. To prepare the walking-one value for stepi, simply shift a one bit byi % 8bits: ``` uint8_t walkOne = 1u << i%8; ``` i%8is the remainder wheniis divided by eight. For walking zeroes, complement the pattern: ``` uint8_t walkZero = ~(1u ...
I want to check the content of a file from Linux Kernel v3.0.8 knowing onlystruct inode *. I only need to read the beginning of a file pointed by this inode, then close and return. I don't care about additional information like filename/mountpoint etc.. In fact, the file may not have the name (like deleted but still o...
I finally did it like this: This is needed. ``` struct path root; struct file *filerd; ``` Get the init task fs root. ``` task_lock(&init_task); get_fs_root(init_task.fs, &root); task_unlock(&init_task); ``` Change dentry to this file: ``` root.dentry = d_find_alias(inode); ``` Open file: ``` filerd = file_ope...
I have an fmp4 file (using h264 and aac frame codes). When playing with VLC, only video has no audio, but the audio can be parsed with PotPlayer. The AAC format is ADTS.The screenshot of my fmp4 audio-related box is as follows
Mp4 should not have ADTS headers in the data. Just raw aac frames plus a configuration record in esds.
This code is supposed to find the smallest odd number in given array and store it inminbut when I try to printminit always prints0. ``` int smallestodd(int x[5]){ int j; int k[5]; int p = 0; int r = 0; for(int h =0; h<5;h++){ j = x[h] % 2; if(j == 1){ int temp =x[h]; k[p] =temp; ...
Assuming there is an odd number in the array --let's say trying to find the minimum odd number in an array with just even numbers (or no numbers) is UB:) ``` index = 0; while (arr[index] % 2 == 0) index++; // skip even numbers min = arr[index++]; // first odd number while (index < length) { if (arr[index] % 2) { ...
I am using IAR embedded workbench software for ARM CORTEX M7 controller. I have already included stdio.h library and it have fopen function like this but when i am declaring my file pointer like this FILE *fpointer; Its giving me these two errors. Please share your experience how can i fix it?
File I/O is not present in the default library. To enable it you need to tell the compiler to use full libraries. This is done by opening the project options and choosing "Full" in the "Library Options" tab if you are using the IDE or by using the command line option--dlib_config fullif you are using the command line ...
RC6wikiuses variable left rotation value that depends on logarithmic value. Iam interested in finding a way to implement constant time c code of RC6. Is there open-source or an idea of how to implement the variable left rotation in constant-time code.
This point is addressed in section 4.1 ofhttps://pdfs.semanticscholar.org/bf3e/23be81385817319524ee6bb1d62e9054d153.pdf. The short summary is: Most processors take constant time for rotations including data dependent rotations (that was the case when rc6 was proposed anyway)Even if the run time to shift k bits is pr...
I'm compiling this code with C99 (with some different type definitions like uint32 instead of uint32_t) for an old arm architecture. ``` uint32 x2 = *((uint32 *) &data[t]); uint32 x3; memcpy(&x3, &data[t], 4); printf("%d %d %d %d %d %d", x2, x3, data[t], data[t + 1], data[t + 2], data[t + 3]); ``` (data ...
Thex2line causes undefined behavior. Firstlydata[t]might not have 32-bit alignment, and secondly, it's probably a strict aliasing violation to read a 32-bit value from that location. Just remove that line and use thex3version.
I'm rouhgly new to Atom Editor, and I wanted to program my media player, based onvlc/libvlc, with it, but I can't include any files fromlibvlc. I downloaded it through the terminal withsudo apt-get install libvlc-dev, but now I can't find the files to include it.
Since you installed usingapt-get, you should be able to locate the location of all the files from a particular package usingapt-file. ``` $ apt-file list libvlc-dev ``` Ifapt-fileisn't already on your system, install it. ``` $ sudo apt-get install apt-file ```
I want to check the content of a file from Linux Kernel v3.0.8 knowing onlystruct inode *. I only need to read the beginning of a file pointed by this inode, then close and return. I don't care about additional information like filename/mountpoint etc.. In fact, the file may not have the name (like deleted but still o...
I finally did it like this: This is needed. ``` struct path root; struct file *filerd; ``` Get the init task fs root. ``` task_lock(&init_task); get_fs_root(init_task.fs, &root); task_unlock(&init_task); ``` Change dentry to this file: ``` root.dentry = d_find_alias(inode); ``` Open file: ``` filerd = file_ope...
I have an fmp4 file (using h264 and aac frame codes). When playing with VLC, only video has no audio, but the audio can be parsed with PotPlayer. The AAC format is ADTS.The screenshot of my fmp4 audio-related box is as follows
Mp4 should not have ADTS headers in the data. Just raw aac frames plus a configuration record in esds.
This code is supposed to find the smallest odd number in given array and store it inminbut when I try to printminit always prints0. ``` int smallestodd(int x[5]){ int j; int k[5]; int p = 0; int r = 0; for(int h =0; h<5;h++){ j = x[h] % 2; if(j == 1){ int temp =x[h]; k[p] =temp; ...
Assuming there is an odd number in the array --let's say trying to find the minimum odd number in an array with just even numbers (or no numbers) is UB:) ``` index = 0; while (arr[index] % 2 == 0) index++; // skip even numbers min = arr[index++]; // first odd number while (index < length) { if (arr[index] % 2) { ...
I am using IAR embedded workbench software for ARM CORTEX M7 controller. I have already included stdio.h library and it have fopen function like this but when i am declaring my file pointer like this FILE *fpointer; Its giving me these two errors. Please share your experience how can i fix it?
File I/O is not present in the default library. To enable it you need to tell the compiler to use full libraries. This is done by opening the project options and choosing "Full" in the "Library Options" tab if you are using the IDE or by using the command line option--dlib_config fullif you are using the command line ...
RC6wikiuses variable left rotation value that depends on logarithmic value. Iam interested in finding a way to implement constant time c code of RC6. Is there open-source or an idea of how to implement the variable left rotation in constant-time code.
This point is addressed in section 4.1 ofhttps://pdfs.semanticscholar.org/bf3e/23be81385817319524ee6bb1d62e9054d153.pdf. The short summary is: Most processors take constant time for rotations including data dependent rotations (that was the case when rc6 was proposed anyway)Even if the run time to shift k bits is pr...
I'm compiling this code with C99 (with some different type definitions like uint32 instead of uint32_t) for an old arm architecture. ``` uint32 x2 = *((uint32 *) &data[t]); uint32 x3; memcpy(&x3, &data[t], 4); printf("%d %d %d %d %d %d", x2, x3, data[t], data[t + 1], data[t + 2], data[t + 3]); ``` (data ...
Thex2line causes undefined behavior. Firstlydata[t]might not have 32-bit alignment, and secondly, it's probably a strict aliasing violation to read a 32-bit value from that location. Just remove that line and use thex3version.
I'm rouhgly new to Atom Editor, and I wanted to program my media player, based onvlc/libvlc, with it, but I can't include any files fromlibvlc. I downloaded it through the terminal withsudo apt-get install libvlc-dev, but now I can't find the files to include it.
Since you installed usingapt-get, you should be able to locate the location of all the files from a particular package usingapt-file. ``` $ apt-file list libvlc-dev ``` Ifapt-fileisn't already on your system, install it. ``` $ sudo apt-get install apt-file ```
I tried to compute the inner product using function but the returned value is not correct. ``` /* Inner product x[n]*y[n] */ #include <stdio.h> #define n 5 void main() { int i,sum; int x[n]={1,2,-1,3,5}; int y[n]={0,6,-2,4,1}; sum=inner_prod(x[n],y[n]); printf("\nThe inner product = %d",sum); ...
The dot product of the two vectors x,y in your case should result in 31 and would do so with your inner_prod function, but you calculated the dot product for x * x which in your case results in 40.. In short, isn't the problem that you just made a typo? ``` sum=inner_prod(x[n],x[n]); ``` I believe you wanted for th...
``` char *a = malloc(10); memset(a, 10, 0); a[0]= 'a'; a[1]= 6; a[2]= 'b'; printf("%s\n", a); // prints ab a[0]= 'a'; a[1]= 27; a[2]= 'b'; printf("%s\n", a); // print a return 1; ``` Is it safe to put control char in string? like in strcpy, etc..
C strings are NUL-terminated sequences ofchars (bytes). Nothing more. Therefore, the control characters have no special meaning to the language or tostrcpy. Functions that care about the contents of strings will define which characters have special meanings.
Recently bought a new USB oscilloscope and tried to measure the frequency of avr timer0. There is 12 MHz crystal oscillator connected to atmega and timer0 set up to fast PWM mode without prescaler. Here is the code: ``` #include <avr/io.h> int main(void) { DDRB = 0x08; TCCR0 |= (1<<WGM00)|(1<<WGM01)|(1<<COM0...
The frequency seems correct to me. If your clock is12MHzand you have an 8 bit PWM your PWM frequency is actually12MHz/256 = 46.875kHz.
I was going through an online lecture and I saw this function to sum an array ``` int arraySum(int array[], const int n) { int sum = 0, *ptr; int *const arrayEnd = array + n; ... } ``` I've not seen an array added to an integer before. If n is the size of the array, does array + n mea...
What you're seeing is pointer arithmetic. arrayis a pointer to the start of your array. Assuming the array hasnelements, thenarray + n(or equivalently&array[n]) points to one element past the end of the array. It is legal to have a pointer to one element past the end of an array, however you can't dereference that ...
Is there a way to start a child process withoutfork(), usingexecvp()exclusively?
The pedantic answer to your question is no. Theonlysystem call that creates a new process isfork. The system call underlyingexecvp(calledexecve) loads a newprograminto an existing process, which is a different thing. Some species of Unix have additional system calls besidesfork(e.g.vfork,rfork,clone) that create a ...
I am trying to create a socket as follow but it is failing with error address family not supported. Can any one please help me out as i am beginner to socket. ``` socket(AF_ATMPVC, SOCK_STREAM, 0); ``` If any other information is required please let me know in comments.
Apparently, I managed to find an answer for my question. This problem can be fixed by passing--network=hostoption while creating the docker container.If you use the host network driver for a container, that container’s network stack is not isolated from the Docker host.
I was going through an online lecture and I saw this function to sum an array ``` int arraySum(int array[], const int n) { int sum = 0, *ptr; int *const arrayEnd = array + n; ... } ``` I've not seen an array added to an integer before. If n is the size of the array, does array + n mea...
What you're seeing is pointer arithmetic. arrayis a pointer to the start of your array. Assuming the array hasnelements, thenarray + n(or equivalently&array[n]) points to one element past the end of the array. It is legal to have a pointer to one element past the end of an array, however you can't dereference that ...
Is there a way to start a child process withoutfork(), usingexecvp()exclusively?
The pedantic answer to your question is no. Theonlysystem call that creates a new process isfork. The system call underlyingexecvp(calledexecve) loads a newprograminto an existing process, which is a different thing. Some species of Unix have additional system calls besidesfork(e.g.vfork,rfork,clone) that create a ...
I am trying to create a socket as follow but it is failing with error address family not supported. Can any one please help me out as i am beginner to socket. ``` socket(AF_ATMPVC, SOCK_STREAM, 0); ``` If any other information is required please let me know in comments.
Apparently, I managed to find an answer for my question. This problem can be fixed by passing--network=hostoption while creating the docker container.If you use the host network driver for a container, that container’s network stack is not isolated from the Docker host.
This question already has answers here:typedef struct vs struct definitions [duplicate](12 answers)Closed4 years ago. Let's say I have this definition: ``` typedef struct tnode *Tnodep; typedef struct tnode { int contents; /* contents of the node */ Tnodep left, right; /* left and right children */ }Tnode; `...
The first definition defines a struct tnode, and two type names Tnodep and Tnode. The second one doesn't define the type name Tnode. With the first definition, you can then define either of the following two: ``` Tnode x; tnode y; ``` With the second definition, you can't. You can only write ``` struct tnode x; ``...
I have two libraries and unfortunately they define two identical preprocessor definitions (which I need to use): lib1.h ``` #define MYINT 1 ``` lib2.h ``` #define MYINT 2 ``` In my program I need to use both of them: ``` #include <Lib1.h> #include <lib2.h> ... int myint = MYINT; ``` And here I have error that M...
You might#undef MYINTbefore to include the header as workaround. ``` #undef MYINT #include <Lib1.h> const int myint_lib1 = MYINT; // 1 #undef MYINT #include <lib2.h> const int myint_lib2 = MYINT; // 2 ```
I am writing a C program that does many comparisons and I was wondering if this actually saves memory. Any help appreciated
No, it does not. Using a tricky syntax to do something that there's a well-known syntax for is never the right answer. You should use x==a.
I have a program that should be CPU bound, but it is using well less than 100% CPU, and is not consuming input as fast as it can. It means my process is blocking or sleeping somewhere. How to find what calls are blocking my process for the most time? Is there a tool or debugging procedure that measures the time how m...
straceis an option: ``` $ strace -wc sleep 1 % time seconds usecs/call calls errors syscall ------ ----------- ----------- --------- --------- ---------------- 99.96 1.000146 1000146 1 nanosleep 0.01 0.000131 131 1 execve 0.01 0.000082 ...
I get the frame at0xffffd3d0and saveedeip = 0xf7e04e7ein stack level 0 while doing gdb debug. ``` (gdb) info frame Stack level 0, frame at 0xffffd3d0: eip = 0x8048452 in main (test.c:13); saved eip = 0xf7e04e7e source language c. Arglist at 0xffffd3b8, args: Locals at 0xffffd3b8, Previous frame's sp is 0xffffd3d0...
3GB limit does not apply to 64-bit processes