question
stringlengths
25
894
answer
stringlengths
4
863
I have this code and I intend to create a set of 4 decks, the problem is that in the suits, after the card 51 the result of the division gives 4 and the arrays of the suits do not return the initial position, how can I solve this situation? Thank you ``` #include <stdio.h> #define NCARTAS 52 int main() { const c...
``` posNaipe = i % NCARTAS / 13; ``` would do it. This is also a touchstone for your knowledge of operator precedence and associativity.
How can I exit the while loop when stdin line is empty? ``` #include <unistd.h> #include <stdio.h> int main(){ FILE* stream = popen("sort", "w"); char *line = NULL; size_t size; while (getline(&line, &size, stdin)) { fprintf(stream,"%s\n", line); } pclose(stream); return 0; } `...
The problem you have is the newline you read. if you add ``` if (*line == '\n') break; ``` to your loop, it will probably work as intended. Testing getline() for a -1 return value is a good idea; you might encounter an End Of File instead of an empty line
I'm imagining readingbyte by bytewould be very inefficient, but reading in bulks would almost always read more than needed, requiring to store the rest of the read input in a global context for all subsequent read operations to find. What am I missing?
The prototype is: ``` ssize_t getline(char **lineptr, size_t *n, FILE *stream); ``` So it's clearly usingFILE, which is already buffered. So reading character-by-character is not inefficient at all.
I have this code and I intend to create a set of 4 decks, the problem is that in the suits, after the card 51 the result of the division gives 4 and the arrays of the suits do not return the initial position, how can I solve this situation? Thank you ``` #include <stdio.h> #define NCARTAS 52 int main() { const c...
``` posNaipe = i % NCARTAS / 13; ``` would do it. This is also a touchstone for your knowledge of operator precedence and associativity.
I'm imagining readingbyte by bytewould be very inefficient, but reading in bulks would almost always read more than needed, requiring to store the rest of the read input in a global context for all subsequent read operations to find. What am I missing?
The prototype is: ``` ssize_t getline(char **lineptr, size_t *n, FILE *stream); ``` So it's clearly usingFILE, which is already buffered. So reading character-by-character is not inefficient at all.
I have this code and I intend to create a set of 4 decks, the problem is that in the suits, after the card 51 the result of the division gives 4 and the arrays of the suits do not return the initial position, how can I solve this situation? Thank you ``` #include <stdio.h> #define NCARTAS 52 int main() { const c...
``` posNaipe = i % NCARTAS / 13; ``` would do it. This is also a touchstone for your knowledge of operator precedence and associativity.
Sanitization keeps code clean, removing the "dirty" injections. In HTML and JavaScript, this is accomplished by removing unsafe tags or escaping user input. What does "sanitization" mean to C?
It's a compiler feature (at least in Clang) that tries to detect memory addresses that are invalid, such as those that are out-of-bounds, or that are still being used after they are freed. You can enable it with the-fsanitize=addresscompiler flag. Seeherefor more info.
I have simple bash script ``` #!/bin/bash make ./code1_test/test_syn1 ./code2_test/test_syn2 ./code3_test/test_syn3 ``` test_syn are my program tests. In every of these programs, I'm using fopen command to open .txt file. If I run programs from command line, I have a correct test output, but when I'm using this bas...
If you’re usingfopen()with a relative path, you should execute the script from its directory. Try this: ``` #!/bin/bash make (cd code1_test/ && exec ./test_syn1) (cd code2_test/ && exec ./test_syn2) (cd code3_test/ && exec ./test_syn3) ``` Otherwise your program tries to open your.txtin the directory from where your...
Given a path ``` /level1/level2/level3/level4 ``` I want to be able to split this string such that I can retrieve each individual entry,i.e "level1", "level2", "level3", "level4". Now my first idea was usingstrtok, but apparently most people recommendagainstusing this function. What is another approach so that I c...
strtokis actually the preferred way to tokenize a string such as this. You just need to be aware that: The original string is modifiedThe function uses static data during its parsing, so it's not thread safe and you can't interleave parsing of two separate strings. If you don't want the original string modified, ma...
How do I print character 128 from extended ascii with write function in c language? ``` #include <unistd.h> int main(void) { int c; c = 128; write(1, &c, 1); return(0); } ``` Output:� Ascii extended 128: Ç
Using awchar_t: ``` #include <stdio.h> #include <wchar.h> #include <locale.h> int main(void) { wchar_t c; setlocale(LC_ALL, ""); for (c = 128; c < 256; c++) { wprintf(L"%lc\n", c); } return 0; } ```
I can determine if my application last terminated due to a call toexit()by usingatexitor a destructor function. Is there any way to determine if my application last terminated due to_exit()?
From theman page The function _exit() terminates the calling process "immediately". Any open file descriptors belonging to the process are closed; any children of the process are inherited by process 1, init, and the process's parent is sent a SIGCHLD signal.The value status is returned to the parent process as...
I am getting error when i am running this code ``` int row1=2,col1=2; int mat1[row1][col1]= { {1,5}, {4,6} }; ``` What is wrong with this code?? IDE: CodeBlocks error: variable-sized object may not be initialized|
What you have here is a variable length array. Such an array cannot be initialized. You can only initialize an array if the dimensions are constants (i.e. numeric constants, not variables declared asconst): ``` int mat1[2][2]= { {1,5}, {4,6} }; ```
How can you format an double like 12345.0 to be printed as 1.234E+04? I want to print something like this: ``` int N = 1024; int time = 3476; printf("%f", (N/time)); ``` Where the output would be:3.394531E+00
You could either usefloatfor your variables or cast some of the variables to floating-point type like this: ``` printf("%f", ((float)N/time)); ``` If you want to have your numbers always inScientific notationhttp://www.cplusplus.com/reference/cstdio/printf/you can replace the format with "%e". It's worth noting tha...
I am getting error when i am running this code ``` int row1=2,col1=2; int mat1[row1][col1]= { {1,5}, {4,6} }; ``` What is wrong with this code?? IDE: CodeBlocks error: variable-sized object may not be initialized|
What you have here is a variable length array. Such an array cannot be initialized. You can only initialize an array if the dimensions are constants (i.e. numeric constants, not variables declared asconst): ``` int mat1[2][2]= { {1,5}, {4,6} }; ```
How can you format an double like 12345.0 to be printed as 1.234E+04? I want to print something like this: ``` int N = 1024; int time = 3476; printf("%f", (N/time)); ``` Where the output would be:3.394531E+00
You could either usefloatfor your variables or cast some of the variables to floating-point type like this: ``` printf("%f", ((float)N/time)); ``` If you want to have your numbers always inScientific notationhttp://www.cplusplus.com/reference/cstdio/printf/you can replace the format with "%e". It's worth noting tha...
How do I handle more than one condition (with different boolean expressions) in a UML state machine transition (as guard)? Example: In this example I would like to add more than only one condition (Tries < 3) in the transition from "logging in" to "Logged In" like discribed in the note. How to handle this UML compl...
Simply spoken (and to focus on the needed step) put a boolean condition like above in theGuard. This can be any text. You can write C-style or plain text. I'm not sure about OCL here, but that's for academic purpose anyway (my opinion). N.B. Your diagram showsTries = 3which should be aGuardalso (i.e.[Tries = 3]) r...
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 I wanted to create a cryptographic secure octet in c. I've heard, that therand()function is not secure enou...
Under Linux, read /dev/urandom to get some random seed, then srandom(seed). On bare metal, reading ADC values + some mathematics helped me in past.
I am coding a program that will take an array, heapify it, then find the kth smallest element. From my textbook I was able to get a lot of the algorithms needed down, but I am stuck now, because I am receiving a segmentation fault whenever I attempt to test the program. In the textbook in the struct it has PQ_SIZE as ...
inmain()you passed*heapwhich is uninitialized pointer topq_init()where you are assigning value to its member ``` priority_queue* heap; pq_init(heap); ``` This is going to lead undefined behaviour, you need to allocate memory toheapprior to using it
I'm a noob at shellcodes and I'm trying to understand all scenarios. I have found many codes to test my shellcodes in C, but to my surprise they are very unreadeable and I can't understand neither this code: ``` int (*func)(); func = (int (*)()) code; (int)(*func)(); ``` Or this one: ``` int (*ret)() = (int(*)())co...
int (*func)();is a pointer to a function (taking no parameters in C++) that returns anint. (*func)();or justfunc();calls the function pointed to. (int (*)()) code;is a nasty type cast telling the compiler thatcodeis pointing to such a function. If it is not, but you still try to call the function, the program is inv...
I am attempting to debug the following line of code in GDB: ``` p=((uint32 *) tiff_pixels)+image->columns*i; ``` p iyeilds8 p columnsyeilds32 p image->columns*icorrectly yields256 p ((uint32 *) tiff_pixels)yields0x619000008780 so I expect((uint32 *) tiff_pixels)+image->columns*ito yield0x619000008880but I get0x6...
You forgot to multiply by the size of each pixel, which is 4 bytes. ``` p=((uint32 *) tiff_pixels)+image->columns*i; ``` You've casttiff_pixelsto be a pointer to auint32. Eachuint32is four bytes. So if you add one to the pointer, it will point to thenextuint32, which is four bytes after the first one.
I want to know whether threads created usingpthread.hlibrary are using one core, or they are running in multiple cores.
A newly created thread has no affinity, and will be shuffled around the process as deemed best by the system. If you need to pin it to a specific core,this answer provides detailsfor setting affinity to a specific pthread.
Hi this is my code for calculating pascal triangle but it runs error : has stopped working... why ? i think its error is in paskal function ``` #include <stdio.h> long paskal(int,int); int main (void) { int n = 0 ; int m = 0 ; int k = 0 ; scanf("%d" , &n); for(k = 1 ; n >= k ; ) { ...
The limit-conditions are not correct. The correct way to put the limit conditions is ``` if(n == 1 || i == 1 ) return 1 ; else .... ```
Is there any macro in GCC that contain compilation flags used to compile the program? I want something like this: ``` printf("Compilation flags: %s", __FLAGS__); ``` To output for example: ``` Compilation flags: -02 -g ```
Short answer: No. Slightly longer answer: Even if there was, your code would become non-portable. Projects needing this sort of functionality let the build system do it, e.g. by having all the flags in aCFLAGSvariable inmakeand have a rule create aconfig.hputting all these flags in a#definethere.
I am really confused, but cannot to do simple task as it seems: I simply need to set number of bits in byte. For example: I need 5 bits set. So I need0xb00011111. Is it possible to do this without loop? Also I'd not like to write lot of#definestoo.
For any integernless than the number of bits in the word, the mask you need is: ``` const unsigned int mask = (1u << n) - 1; ``` No loop required. A simple function using this: ``` unsigned int set_lsbs(unsigned int n) { return (1u << n) - 1; } ``` The ten first results are: ``` 0: 0x0 1: 0x1 2: 0x3 3: 0x7 4: ...
I was given this code to look into, and this code is filled with these arrow type symbols: Those symbols are seen around variable declarations like in the image, and they disappear if I copy them and try to paste them into web browser. Are they like some sort of custom symbol from different keyboard? What could pos...
Those arrow symbols are actually visualizations of the tab character. What you actually have is this: ``` void *ptr; int len = strlen( string ) + 1; ``` The arrows are there just to show you that there are tabs in the code.
While I was browsing cppreference, I saw a strange type array in function parameters like this: ``` void f(double x[volatile], const double y[volatile]); ``` So, What is the purpose of thevolatilekeyword appearing inside an array subscript? What does it do?
Thevolatilekeyword is used to declare an array type of a function parameter. Here,double x[volatile]is equivalent todouble * volatile x. Thecppreferencesays : In a function declaration,the keywordvolatilemay appear inside the square brackets that are used to declare an array type of a function parameter.It qual...
I would like to create a 2D string array so i try that: ``` char **value[] = {"integer", "char", "string", "octal", "hexa_min", "hexa_maj", "pointer", "integer", "bin_int", "non_printable", "unsigned_int", NULL}; ``` but i have a warning for each str of my array. https://pastebin.com/bwJtB1CR Thanks for your help ...
``` char value[12][30] = { "integer", "char", "string", "octal", "hexa_min", "hexa_maj", "pointer", "integer", "bin_int", "non_printable", "unsigned_int", "NULL"}; ``` Always remember when you declare 2D array as follows: array2D[No_Of_Rows][No_Of_Coloums];
Any time I had the need of a Boolean type I was told to either create one, or better yet, usestdbool.h. Sincestdbool.husestypedef bool _Bool, is there a reason to use the header instead just using type_Bool? Is it just for the additional macros (/* #define true 1 #define false 0 */)?
The obvious type to add into the language wasbool. But unfortunately, plenty of code was written that includedboolin other shapes and forms. Recall that support for a boolean type was added only in C99. So the C language committee had no choice but to pull out a reserved identifier for it (_Bool). But, since the obvi...
How doeswhileterminate when count becomes 0 without a condition likecount!=0? ``` #include<stdio.h> static int count=5; void func(void); void main() { while(count--) { func(); } } void func(void) { static int i=5; i++; printf("%d\t%d\n",i,count); } ```
In C Language0( Zero ) is considered as being false. When you use0in any conditional statement, it will evaluate as false. Ex:if( 0 )evaluates as false and the else code (if any) is triggered. In your code, whencount--equals0, the while condition evaluates towhile (0). Since an iteration of thewhileloop will only b...
Is there any way to print multiple strings in C based on only one condition for example ``` int main(int argc, char const *argv[]) { printf("%s %s\n", condition ? "string1","string2" : "string3","string4"); return 0; } ``` if the condition is true then I would like to have ``` string1 string2 ``` as the outp...
I think you need: ``` printf("%s %s\n", condition ? "string1" : "string3", condition ? "string2" : "string4"); ```
The C standard states (emphasis mine): If an identifier designates two different entities in the same name space, the scopesmightoverlap. [...] (section 6.2.1.4 fromhttp://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf) When can an identifier refer to two different entities but their scopes do not overlap? Or,...
These scopes fornameoverlap: ``` int f(void) { int name = 4; { int name = 6; } } ``` These ones do not overlap: ``` int f(void) { { int name = 4; } { int name = 6; } } ```
I looked through several sites ,but, I am not able to find a suitable answer. It seems really hard to convert my c programme to assembly code...
if you use keil uvision ,than 1. goto Debug >> click "start/stop Debug Session" it'll start simulator if ide 2. 2. view >> click Disassembly Window and you can see the assembly. if not then go to below link and download it DIS8051 Cross-Disassembler V2.1 (you need hex file to convert your program to assembly of 8051...
I would like to analyze an ELF binary file and figure out how many calls to dlopen() it makes in C, are there any libraries that can do this? Or how would I go about finding the count?
You could simply useltrace: Example: ``` #include <dlfcn.h> #include <stdio.h> int main(int C, char **V) { char **a = V+1; while(*a){ void *h; if(0==(h=dlopen(*a++, RTLD_LAZY))) fprintf(stderr, "%s\n", dlerror()); } } ``` Compile it: ``` $ gcc example.c -fpic -pie ``` Invo...
This question already has an answer here:How to change console window style at runtime?(1 answer)Closed5 years ago. So I was searching (a lot) and haven't find anything on how to prevent user from resizing my program's console window. I had found information for languageC++andC#but not forC. I already managed to set ...
Okay so I managed to do the magic with combining codes. First of all you need a ``` #define _WIN32_WINNT 0x0500 ``` and after that (the order is important) ``` #include <windows.h> ``` and after all this you need this code in your main: ``` HWND consoleWindow = GetConsoleWindow(); SetWindowLong(consoleWindow, GWL...
I have a GTK application where I need to allow the user to open a file manager to delete older data files. I have successfully incorporated this using this bit of code: ``` GError *error = NULL; if (!g_app_info_launch_default_for_uri ("file:///", NULL, &error)) { g_warning ("Failed to open uri: %s", error->messag...
Maybe as alternative consider GtkFileChooserDialog in your app? It should allow deleting files through that one and you have full control over the window.
When I useIF_NAMESIZE(fromnet/if.hin libc implementations) as array size, should I use it as it is or with+ 1for\0(null byte)? ``` char iface[IF_NAMESIZE]; ``` or ``` char iface[IF_NAMESIZE + 1]; ``` I see it using both ways across various open source projects.
The header shall define the following symbolic constant for the length of a buffer containing an interface name (including the terminating NULL character):IF_NAMESIZE Interface name length. http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/net_if.h.html So: ``` char iface[IF_NAMESIZE]; ``` is enough
schot's answeris a good one. He claimed that Tags (names of structures, unions and enumerations). I think that the tags for structures, unions and enumerations have different namespaces, so that this code is completely fine: ``` // In the same scope struct T {}; union T {}; enum T {}; ``` But inferring from the qu...
No. All the tags share the same namespace. So you are not allowed to have: ``` struct T {...}; union T {...}; enum T {...}; ``` C11 draft N1570, 6.2.3 Name spaces of identifiersexplicitly add s footnote. 32) There isonly one name space for tagseven though three are possible.
I'm using this function to read the input matrix: ``` void leMatInt(int **M,int linhas,int colunas){ int i, j; for (i = 0; i < linhas; i++){ for (j = 0; j < colunas; j++){ scanf("%d", &M[i][j]); //printf("Leu [%d, %d]\n", i, j); } } } ``` And I'm creating the matrix like this:...
matriz1is a double pointer so while allocating memory you should writesizeof(int*). because** pointerwill holds/contains* singlepointers. ``` int **matriz1 = malloc(v1 * sizeof(int*)); for(i = 0;i < v1; i++){ matriz1[i] = malloc(v1 * sizeof(int)); } ``` typecastingmalloc()is discouraged.
This question already has answers here:Is CHAR_BIT ever > 8?(3 answers)Closed5 years ago. As far as I know the standard says that the size of theshorttype must be at least 16 bits. Now I'm wondering if there are actually platforms whereshorts are 32 bit or even larger. I'm aware ofstddef.hand that the types defined...
Yes. You can findan example here(well, not 32 bit, but "larger than 16"). The example given there is theUNICOSoperating system for "Cray" supercomputers, which has 64bitshort.
I'm using this function to read the input matrix: ``` void leMatInt(int **M,int linhas,int colunas){ int i, j; for (i = 0; i < linhas; i++){ for (j = 0; j < colunas; j++){ scanf("%d", &M[i][j]); //printf("Leu [%d, %d]\n", i, j); } } } ``` And I'm creating the matrix like this:...
matriz1is a double pointer so while allocating memory you should writesizeof(int*). because** pointerwill holds/contains* singlepointers. ``` int **matriz1 = malloc(v1 * sizeof(int*)); for(i = 0;i < v1; i++){ matriz1[i] = malloc(v1 * sizeof(int)); } ``` typecastingmalloc()is discouraged.
This question already has answers here:Is CHAR_BIT ever > 8?(3 answers)Closed5 years ago. As far as I know the standard says that the size of theshorttype must be at least 16 bits. Now I'm wondering if there are actually platforms whereshorts are 32 bit or even larger. I'm aware ofstddef.hand that the types defined...
Yes. You can findan example here(well, not 32 bit, but "larger than 16"). The example given there is theUNICOSoperating system for "Cray" supercomputers, which has 64bitshort.
So I create a new file: ``` fd = open("tester.txt", O_CREAT | O_RDWR); ``` then using the system call write I add some info to it. But when I try to read the info from the file, it can't be made. Using theterminalI found out, that the only way to open the file is to usesudoand thecontent is successfully written. How...
You are missing to specify the file mode as third argument to the creating open call; try the following: ``` fd = open("tester.txt", O_CREAT | O_RDWR, 0644); ``` Then, the file should be created with mode-rw-r--r--, so your own user can open it for reading and writing. Otherwise, it might end up with some random per...
MSDN link for TTM_GETBUBBLESIZEdoesn't have an example, how the lower word and higher word get returned. Didn't get much from Google. Please care to provide an example of it. Thanks!
FromMSDN: Returns the width of the tooltip in the low word and the height in the high word if successful. A "word" in the context of the Win API usually has a size of 16-bit. You have to use somebitwise arithmeticto extractwidthandheightfrom theresultof the message: ``` width = result & 0xFFFF; // extract the...
I have declared onlychartype members in the structure. ``` #include <stdio.h> struct st { char c1; char c2; char c3; char c4; char c5; }; int main() { struct st s; printf("%zu\n", sizeof(s)); return 0; } ``` Output:[Live Demo] ``` 5 ``` So, why is there no padding in the structure...
Padding is to enforcealignmentrequeriments. A member is said to bealigned(to its size) if it is located at an address that is divisible by its size. There is no need for padding in your example, since all members of theststructure are already aligned to their size, i.e.: the address of each member ofstis already di...
I have a problem assigning values to variable in struct. My code is shown below. ``` typedef struct _neuron { double value[100]; int id; }NEURON; int main() { NEURON node; int i; for(i = 0; i < 100; i++){ node.value[i] = 10; printf("the value is %d\n",node.value[i]); } } ``` The values I ass...
You're using the wrong format specifier toprintf. The%dformat specifier expects anintargument, but you're passing in adouble. Using the wrong format specifier invokes undefined behavior. For adouble, use the%fformat specifier. ``` printf("the value is %f\n",node.value[i]); ```
Some C/C++ headers like<sys/ioctl.h>have asys/prefix in front of them. (There are also some with anet/prefix.) Why is this?
Practically, this shows those file are under a sub-folder named "sys" in one of the standard list of system directories (e.g compiler default search path, or folder given as a parameter during the build). The reason they are in a sub-folder is to indicate they are not a part of the c or c++ standard libraries, but r...
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 Is this possible to get lines from file one by one and save them to the char array which size is determined...
fromhttps://linux.die.net/man/3/getline ``` ssize_t getline(char **lineptr, size_t *n, FILE *stream); ``` getline automatically allocates lineptr if it is NULL or not large enough to contain the string
This question already has answers here:What is 'forward declaration' and the difference between 'typedef struct X' and 'struct X'?(5 answers)Closed5 years ago. Why does ``` //The type anything_at_all exists nowhere. typedef struct anything_at_all lol; ``` compile without errors, whereas ``` //The type anything_at_...
You can declare astructwithout defining it. This is called aforward declaration. It allows you to do things like this: ``` struct s1; struct s2 { int x; struct s1 *p; }; struct s1 { int y; struct s2 *p; }; ```
For example, I have a 64 bit vara, and a 8 bit charb ``` unsigned long long a = 0x1234567890123456; unsigned char b = 0x78; ``` I wantato become 0x1234567890123478 I want rightmost 8 bit ofato set tob, and remain left 56 bits untouched, how can i do this? ``` a = a & (0xFFffFFffFFffFFff | b); //is this correct? ``...
There's a useful macro defined inlimits.hthat can help make it portable. It'sCHAR_BIT. ``` a = ((a >> CHAR_BIT) << CHAR_BIT) | b; ``` And that's it. The piece in parentheses clears the least significantCHAR_BITs ofa, and then that can be bitwise-ored withb.
I followed the solution here:How to Calculate Double + Float Precisionand have been unable to calculate the maximum value for variables of type double. I run: ``` double dbl_max = pow(2, pow(2, 10)) * (1-pow(2, -53)); printf("%.2e", dbl_max); Result: inf ``` Or: ``` double dbl_max = (pow(2, pow(2, 10))); printf(...
The intermediate exponent is one too high. Changepow(2, 10)to(pow(2, 10) - 1)and it should work. You can compensate by multiplying the final result by 2. – Tom Karzes ``` double dbl_max = pow(2, pow(2, 10)-1) * (1-pow(2, -53)) * 2; printf("%.2e", dbl_max); ```
Is there a better way than: ``` #define BOUND 7 int r; int e = 1; r = rand() % BOUND; while (r == e){ r = rand() % BOUND; } ``` for generating numbers in a range except for a valuee?
What you're asking for is generating a random number in the range[0, BOUND)excluding the valuee Thealgorithm explained hereseems to be the best way to do it without using a loop. Here is the C code: ``` #define BOUND 7 int r; int e = 1; r = rand() % (BOUND-1); if (r >= e){ r = r+1; } ``` So, you basically g...
I want to read the values of the register starting from 0x20000000 to 0x20000FFC. Architecture: ARMRegister width: 32 bit I did following: ``` #define REG 0x20000000 unsigned int volatile * const port = (unsigned int *) REG; for(int i=0; i<4093; i++) { printf("%d", *(port+i)); } ``` Is this the right wa...
``` #define REG 0x20000000 unsigned int volatile const* port = (unsigned int *) REG; for(; port < (unsigned int *) REG+0x1000; port++) printf("%u", *port); ```
So i'm debugging a very rare case that SEGSEV occurs, I do not know when it will happen, but i know that when it happens, one local var is-1, so I did this in gdb ``` break file.c:100 if t1 == -1 ``` the problem is i have to go back many steps to find out what happened, is it possible to record all execution informa...
there is currently therr projectfor linux which record the execution of your program and help you replay the execution in GDB. Windows also seem to have somereplay debugging capabilities with winDbg preview
How do you allocate an array comprised of fixed size array of floats ? I tried this: ``` float **sub_uvs = malloc(sizeof(float [2]) * size * size); /* Seg. fault */ sub_uvs[0][0] = 0.3; sub_uvs[0][1] = 0.4; ```
Multidimensional arrays of variable size are still tricky. Several options: Use an array of pointers to arrays. Use onemallocfor the array of pointers, then loop overmallocto make each row-array. But, this is a whole different data structure.Find a class providing memory management and multidimensional indexing metho...
Currently, I'm taking C language certification course at cppinstitute.org. In one of it's quizzes there is a question as below to recognize output. ``` int i = 1,j= 1; int w1,w2; w1 = (i>0) && (j<0) || (i<0) &&(j>0); w2 = (i<=0) || (j>=0) && (i>=0) || (j<=0); printf("%d",w1 == w2); ``` I think the program should pri...
Here,&&higher precedence than||operator. So, ``` w1 = (i>0) && (j<0) || (i<0) &&(j>0); = 1 && 0 || 0 && 1; = 0 || 0 = 0 ``` And ``` w2 = (i<=0) || (j>=0) && (i>=0) || (j<=0); = 0 || 1 && 1 || 0 = 0 || 1 || 0 = 1 || 0 = 1 ``` So,w1 == w2become false. So, correct output is 0.
Is there difference in code for writing to a serial port in C usingcanonicalornon-canonicalmethod?
yes, there is a major difference. The parameters of the communication port need to be modified to be transferring 'raw' or 'cooked' characters. 'raw' transfers every char, exactly as it is received. 'cooked' makes the I/O module handle control characters, back space, etc Suggest starting by reading the MAN page fo...
I have a struct defined by: ``` typedef struct { char name[CANDY_NAME_LEN]; bool vegan; } candy; ``` I define an array of size 10 of these structs: ``` const candy candy_db[NUM_OF_CANDIES]; ``` and try to fill the array: ``` strcpy_s(candy_db[0].name, sizeof(candy_db[0].name), "Apple"); candy_db[0].vegan ...
const candy candy_db[NUM_OF_CANDIES]; You've defined your array asconst, so none of its elements can be modified.
I know I can print an address using: ``` printf("%p\n",(void*)&a); ``` Is there a way to just access the address (=int representing place in memory) of a variable? A possible workaround is atoi of sprintf %p but common, is there a cleaner way? I need that for a Nachos project.What I am trying to do is writing into...
You can cast avoid *to auintptr_t, which is an integer type large enough to represent a pointer. ``` uintptr_t p = (uintptr_t)(void *)&a; ``` Note that the double cast is needed, as the standard states the conversion is only valid between auintptr_tand avoid *.
I know I can print an address using: ``` printf("%p\n",(void*)&a); ``` Is there a way to just access the address (=int representing place in memory) of a variable? A possible workaround is atoi of sprintf %p but common, is there a cleaner way? I need that for a Nachos project.What I am trying to do is writing into...
You can cast avoid *to auintptr_t, which is an integer type large enough to represent a pointer. ``` uintptr_t p = (uintptr_t)(void *)&a; ``` Note that the double cast is needed, as the standard states the conversion is only valid between auintptr_tand avoid *.
I want to pack the following numbers into a 64 bit int64_t field in the following order: int8_t num1int8_t num2int32_t num3int16_t num4 So, the 64 bits should be in the following layout: ``` [ num1(8) | num2(8) | num3(32) | num4(16) ] ``` I'm not able to wrap my head around the bit packing log...
You probably want this: ``` int8_t num1; int8_t num2; int32_t num3; int16_t num4; ... uint64_t number = ((uint64_t)num1 << (16 + 32 + 8)) | ((uint64_t)num2 << (16 + 32)) | ((uint64_t)num3 << 16) | (uint64_t)num4; ``` From this you should be able to figure out how to do the inverse conversion. If not, post ...
I am new to messaging world and started usingNanomsglibrary in my application. I want to know whether the messages are encrypted by default between the server and the client by theNanomsglibrary. If not, how can I add encryption to secure the messages between the communicating nodes?
The payload of the message is not encrypted. You can add encryption and decryption for payload into the client and server. A very simple encryption is described hereSimply encrypt a string in C
I've found out where caused SEGSEV, but only happens when that function be called hundreds of thousands times to trigger some rare case, is it possible to set breakpoint there when something is true? either on the gdb command line or c source file
Try like this: ``` (gdb) break file.c:15 if some_variable == some_value ```
I saw following macrohere. ``` static const char LogTable256[256] = { #define LT(n) n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n -1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, LT(4), LT(5), LT(5), LT(6), LT(6), LT(6), LT(6), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7) }; ``` What does#def...
If simply repeats its argument 16 times. See how it is used in the code at your link, immediately after its definition, to produce sequential repetitive values in the initializer ofLogTable256array: ``` static const char LogTable256[256] = { -1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, LT(4), LT(5), LT(5...
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 can I increase accuracy in double. for example in this code: ``` #include <stdio.h> int main() { ...
Floating Point Numbers have a limited precision.Mandatory Reading Here. Theboost.multiprecisionlibrary can give you access to higher precision floating point numbers, whether in the form ofquadtypes which simply double the precision ofdouble, or in the form of arbitrary precisionrationalnumbers. If you're willing to ...
I've trying to do this but I can't find the right way. I have this : ``` #include <string.h> #include <stdio.h> int main(){ char a = 'a'; char b[1] = " "; strcat(b,a); printf ("%s",b); return 0; } ``` I know it's wrong. How can I fix this code in order to turn'a'into"a"?
``` #include <string.h> #include <stdio.h> int main(){ char a = 'a'; char b[2] = " "; b[0] = a; printf ("%s",b); return 0; } ``` A c string is just an array of characters - if you want to set individual characters in that string, you can do so exactly as you would any other array. One thing you ...
the following error shows ,when i try to compile the source code ``` C:/Program Files (x86)/mingw-w64/i686-7.1.0-posix-dwarf-rt_v5-rev2/mingw32/bin/. ./lib/gcc/i686-w64-mingw32/7.1.0/../../../../i686-w64-mingw32/bin/ld.exe: cannot open output file print.exe: Permission denied collect2.exe: error: ld returned 1 exit ...
You have to kill the existing process that is running. kill theprint.exeprocess an it will be accessible or simply close thecommand prompt windowwhich opened the execution instance.
Hello! I want to make Makefile.win which will make a tar.gz with 2 other files(dodaj.c and another Makefile, both are in the same directory where i want use commend make ).My problem is ``` make dodaj.tar.gz make: *** No rule to make target 'dodaj.tar.gz'. Stop ``` Here is my code: ``` dodaj.tar.gz: dodaj.c Make...
Make will look for files named 'makefile' and 'Makefile'. If you are using Gnu make, it will also look for 'GNUmakefile'. It does not look for 'Makefile.win'. To use that file, you must domake -f Makefile.win dodaj.tar.gz
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 can I increase accuracy in double. for example in this code: ``` #include <stdio.h> int main() { ...
Floating Point Numbers have a limited precision.Mandatory Reading Here. Theboost.multiprecisionlibrary can give you access to higher precision floating point numbers, whether in the form ofquadtypes which simply double the precision ofdouble, or in the form of arbitrary precisionrationalnumbers. If you're willing to ...
I've trying to do this but I can't find the right way. I have this : ``` #include <string.h> #include <stdio.h> int main(){ char a = 'a'; char b[1] = " "; strcat(b,a); printf ("%s",b); return 0; } ``` I know it's wrong. How can I fix this code in order to turn'a'into"a"?
``` #include <string.h> #include <stdio.h> int main(){ char a = 'a'; char b[2] = " "; b[0] = a; printf ("%s",b); return 0; } ``` A c string is just an array of characters - if you want to set individual characters in that string, you can do so exactly as you would any other array. One thing you ...
the following error shows ,when i try to compile the source code ``` C:/Program Files (x86)/mingw-w64/i686-7.1.0-posix-dwarf-rt_v5-rev2/mingw32/bin/. ./lib/gcc/i686-w64-mingw32/7.1.0/../../../../i686-w64-mingw32/bin/ld.exe: cannot open output file print.exe: Permission denied collect2.exe: error: ld returned 1 exit ...
You have to kill the existing process that is running. kill theprint.exeprocess an it will be accessible or simply close thecommand prompt windowwhich opened the execution instance.
Hello! I want to make Makefile.win which will make a tar.gz with 2 other files(dodaj.c and another Makefile, both are in the same directory where i want use commend make ).My problem is ``` make dodaj.tar.gz make: *** No rule to make target 'dodaj.tar.gz'. Stop ``` Here is my code: ``` dodaj.tar.gz: dodaj.c Make...
Make will look for files named 'makefile' and 'Makefile'. If you are using Gnu make, it will also look for 'GNUmakefile'. It does not look for 'Makefile.win'. To use that file, you must domake -f Makefile.win dodaj.tar.gz
This question already has answers here:Modify a string with pointer [duplicate](4 answers)Closed5 years ago. I am getting segmentation fault when running the below code. What could be the reason for this error? Please help ``` int main() { char *str2 = "Hello"; str2[3] = 'J'; printf("%s\n",str2); ret...
It is aundefined behaviourbecause you are trying to modify the content of astring literal. A string literal mainly stored in aread only location. so you do not modify it, otherwise it is invoked undefined behaviour. C11 §6.4.5 String literals(Paragraph 7): It is unspecified whether these arrays are distinct provided...
Let's say here is a char with unknown digit number in C: ``` char char_id[1000] = {'1', '2', '3', ..., '8', '9', '\0'}; ``` If I want the last two digit to form an integer i.e. '89'. What is the easiest way?
may be this ``` char char_id[1000] = {'1', '2', '3', /*..., */ '8', '9', '\0'}; int what_i_want = atoi( char_id + ( strlen(char_id) - 2 ) ); ``` by the way those dots are a bit of rubbish, comment them
This question already has answers here:How do I align a number like this in C?(11 answers)Closed5 years ago. So I want to align my outputs like so: ``` John Smith Age: 34 Gender: M Micheal Smith Age: 9 Gender: F ``` and so on I have an array that contains the information for this and I loop through...
If you look at the manual for printf(), and note that you can do things like %-18s and %2d - putting a field width and alignment in the format group. So I'd do something like ``` printf("%-20s Age:%3d Gender: %1s", person[i].name, person[i].age, person[i].gender); ``` which should align nicely for you.
In C, how can I declare and use/manipulate a an array of strings? For example, it could be ``` a[1]="Apples"; a[2]="Pineapples are red" ``` How can I access these elements and modify them?
In your code,amust be an array of pointers to char, e.g.char *a[5], to which you then assign pointers to string literals: ``` a[1]="Apples"; a[2]="Pineapples are red"; ``` You can modify an element in the sense to let it point to a different string, e.g.a[1]="another fruit";. You can access an entire string like, fo...
I know what the difference between these types of variables is, but I'm wondering if making a static variable local actually affects, or can affect the compiler's code-generation in any way.
Static variables declared at file scope have the same properties as static variables declared locally (aside from theirscope, i.e. visibility region of the identifier). Both kinds have the same storage duration. Both kinds are initialized before program's startup. There's no reason to expect them to behave differentl...
When I try to assign a big number to adoublevariable, I get this warning sqrt.c:8:11: warning: integer constant is too large for its typedouble x=28462391747582051264412870770688; ``` #include <stdio.h> #include <math.h> #include <limits.h> #include <float.h> int main() { printf("MAX_DBL=%.53f\n",DBL_MAX); ...
``` double x=28462391747582051264412870770688; ``` The type of the number literal is notdouble, butint. This number is too large for anint. If you use adoubleliteral: ``` double x=28462391747582051264412870770688.0; ``` The warning disappears, but the number will be rounded to the next representabledouble, if need...
I'm trying to make my charpWRtaking the value of the first 6 characters of charpWbut I am getting the following error: ``` incompatible types in assignment of 'char' to 'char [6]' pWR = pW[1,2,3,4,5,6]; ``` This is part of my code: ``` char pWR[6]; char pW[30]; pWR = pW[1,2,3,4,5,6]; ``` Any help would be great.
You can use the library functionstrncpyto achieve your objective: ``` char pWR[6]; char pW[30] = "abcdefghij"; strncpy(pWR, pW, 6); ``` However, if you are planning to treat pWR as a string, make sure you allow for the null terminator character to mark the end of the string. The other alternate as suggested by a f...
I'm currently learning the basics in C programming and was about to try out the switch-statement. My questions is: ``` switch (answer) { case ('Y' || 'y') : printf("\nYay! Me too. "); break; case ('N' || 'n') : printf("\nBoo! :("); break; default: printf("\nIn...
switch case doesn't support logical operations. In your case the solution is easy: ``` switch (answer) { case 'Y': case 'y': printf("\nYay! Me too. "); break; case 'N': case 'n': printf("\nBoo! :("); break; default: printf("\nInput error!"); break; } ```
Parentheses and pointer symbol have same priority, and they are dealed from left to right. Why does the following code try to get the membernfctfromskb, then do the type conversion? It's seems that the associativity is from right to left. ``` (struct nf_conn *) skb->nfct ```
I believe the point you're missing here is theOperator Precedence. The pointer member access operator (->) has higher precedence than the cast. To elaborate, (borrowed wordings) Operator precedence determines which operator is performed first in an expression with more than one operators with different precedence.A...
I'm using 32-bit variable for storing 4 8-bit values into one 32-bit value. ``` 32_bit_buf[0]= cmd[9]<<16 | cmd[10]<<8| cmd[11] <<0; ``` cmdis of unsigned char type with data ``` cmd [9]=AA cmd[10]=BB cmd[11]=CC ``` However when 32-bit variable is printed I'm getting0xFFFFBBCC. Architecture- 8-bit AVR Xmega Lang...
Your architecture uses 16bitint, so shifting by 16 places is undefined. Cast yourcmd[9]to a wider type, e.g.(uint32_t)cmd[9] << 16should work. You should also apply this cast to the other components: When you shiftcmd[10]by 8 places, you could shift into the sign-bit of the 16bitsignedintyour operands are automatical...
This question already has answers here:How do I properly compare strings in C?(11 answers)string comparison inside if condition malfunctioning [duplicate](2 answers)Closed5 years ago. ``` #include<stdio.h> int main(){ char name[20]; scanf(" %s", name); if (name == 'James'){ printf("Welcome James"); }else{ ...
Use ``` if (strcmp(name, "James") == 0) ``` instead of ``` if (name == 'James') ``` Man page ofstrcmp: Return Value Thestrcmp()andstrncmp()functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greate...
I know what the difference between these types of variables is, but I'm wondering if making a static variable local actually affects, or can affect the compiler's code-generation in any way.
Static variables declared at file scope have the same properties as static variables declared locally (aside from theirscope, i.e. visibility region of the identifier). Both kinds have the same storage duration. Both kinds are initialized before program's startup. There's no reason to expect them to behave differentl...
When I try to assign a big number to adoublevariable, I get this warning sqrt.c:8:11: warning: integer constant is too large for its typedouble x=28462391747582051264412870770688; ``` #include <stdio.h> #include <math.h> #include <limits.h> #include <float.h> int main() { printf("MAX_DBL=%.53f\n",DBL_MAX); ...
``` double x=28462391747582051264412870770688; ``` The type of the number literal is notdouble, butint. This number is too large for anint. If you use adoubleliteral: ``` double x=28462391747582051264412870770688.0; ``` The warning disappears, but the number will be rounded to the next representabledouble, if need...
I'm trying to make my charpWRtaking the value of the first 6 characters of charpWbut I am getting the following error: ``` incompatible types in assignment of 'char' to 'char [6]' pWR = pW[1,2,3,4,5,6]; ``` This is part of my code: ``` char pWR[6]; char pW[30]; pWR = pW[1,2,3,4,5,6]; ``` Any help would be great.
You can use the library functionstrncpyto achieve your objective: ``` char pWR[6]; char pW[30] = "abcdefghij"; strncpy(pWR, pW, 6); ``` However, if you are planning to treat pWR as a string, make sure you allow for the null terminator character to mark the end of the string. The other alternate as suggested by a f...
This may be a silly question, but I'm struggling to solve this problem. I know that to append a char to a string I can do something like this: ``` char c; char string[10] = ""; strcat(string, &c); ``` Now, this works well for char variables, but the problem is that when I try to append a char from an array: ``` cha...
You can use strncat().Here length is the number of characters you want to append to string ``` strncat(string, array, length); ``` For appending single character, use length = 1
May I know if there is anything like the easiest node to be removed or deleted from a LinkedList. I know that deleting a node from in between requires a change of the preceding nodes link, whereas deleting from beginning needs a change of pointer to the new head and deleting from the end needs a change of new end of ...
Sounds like you are on the right track with your thoughts on linked lists. Another thing to consider about removing theeasiestnode from a linked list is the following: How often will theseeasiestnodes be removed? If the node is removed from theheadof the list the removal will becomplete in O(1)time, but if theeasiest...
For example, if I had amakefilethat contains this: ``` dynArray.o: dynArray.c dynArray.h type.h gcc -Wall -ansi -c dynArray.c ``` How would I translate that into aCMakeLists.txtfile?
ProbablyCMake's object librarieswould do that, that mean compile objects but not archive them like normal library would. ``` add_library(<name> OBJECT <src>...) ```
If we open FIFO with O_NONBLOCK set, why opening with read-only or write-only set,open()behave differently?
There is asymmetry due to communication semantic. Opening for writing in non blocking mode should fail if there is no reader at that time because writing into a channel with no reader is of no usage (without any reader writing should fail). Opening for reading in non blocking can succeed (and does) because it declar...
This may be a silly question, but I'm struggling to solve this problem. I know that to append a char to a string I can do something like this: ``` char c; char string[10] = ""; strcat(string, &c); ``` Now, this works well for char variables, but the problem is that when I try to append a char from an array: ``` cha...
You can use strncat().Here length is the number of characters you want to append to string ``` strncat(string, array, length); ``` For appending single character, use length = 1
May I know if there is anything like the easiest node to be removed or deleted from a LinkedList. I know that deleting a node from in between requires a change of the preceding nodes link, whereas deleting from beginning needs a change of pointer to the new head and deleting from the end needs a change of new end of ...
Sounds like you are on the right track with your thoughts on linked lists. Another thing to consider about removing theeasiestnode from a linked list is the following: How often will theseeasiestnodes be removed? If the node is removed from theheadof the list the removal will becomplete in O(1)time, but if theeasiest...
For example, if I had amakefilethat contains this: ``` dynArray.o: dynArray.c dynArray.h type.h gcc -Wall -ansi -c dynArray.c ``` How would I translate that into aCMakeLists.txtfile?
ProbablyCMake's object librarieswould do that, that mean compile objects but not archive them like normal library would. ``` add_library(<name> OBJECT <src>...) ```
If we open FIFO with O_NONBLOCK set, why opening with read-only or write-only set,open()behave differently?
There is asymmetry due to communication semantic. Opening for writing in non blocking mode should fail if there is no reader at that time because writing into a channel with no reader is of no usage (without any reader writing should fail). Opening for reading in non blocking can succeed (and does) because it declar...
For example, if I had amakefilethat contains this: ``` dynArray.o: dynArray.c dynArray.h type.h gcc -Wall -ansi -c dynArray.c ``` How would I translate that into aCMakeLists.txtfile?
ProbablyCMake's object librarieswould do that, that mean compile objects but not archive them like normal library would. ``` add_library(<name> OBJECT <src>...) ```
If we open FIFO with O_NONBLOCK set, why opening with read-only or write-only set,open()behave differently?
There is asymmetry due to communication semantic. Opening for writing in non blocking mode should fail if there is no reader at that time because writing into a channel with no reader is of no usage (without any reader writing should fail). Opening for reading in non blocking can succeed (and does) because it declar...
I'm programming some functions to treat with strings without using<string.h>, and I'm getting the length of a string by doing this: ``` char *str= "Getting the length of this"; int c; for (c= 0; str[c]!='\0'; c++); ``` Nowcis the length of my string so it makes work with strings a lot easier, but i wonder if this is...
... i wonder if this is correct Yes, it is correct. For readability I would prefer: ``` char *str= "Getting the length of this"; int c = 0; while(str[c]) c++; ``` but that's just a matter of taste. Be aware that it is unusual to useintfor string length. Thestrlenfunction returnssize_tso to mimic the library func...
``` #include <stdio.h> void main() { char c = getchar(); while ( c != '.') { putchar(c); c = getchar(); } } ``` when you run above code and input any string like "Shubham jain". the whole string gets copied and gets printed whilegetchar()should have read only the first character from the string. can someone explain h...
When you input a string using your program, it will automatically provide input for every char in the string ongetcharfunction, calling it multiple times. The moment the loop detects a '.' the program stops reading any more characters.
What's the difference betweenchar str[10]andchar *str = (char *) malloc(10)? As I understand, don't both of them allocate 10 bytes for an array ofchars?
char str[10]; Global (static) scope - allocated in the.dataor.bsssegments (depending on the initialisation. Cannot be freed before program termination. Local (automatic) scope - usually (most implementations but C standard does not defie anything like the "stack") allocated on the stack. Automatically freed when pro...
I have the following code: ``` struct coord { float x; float y; }; struct coord vertices[4]; ``` But when I do the following, an error occurs: ``` void setVertices(float x, float y) { vertices[0] = (struct coord) { x, y }; } ``` Why isn't this allowed in C? Is there another way to do this? Thank you.
I can initialize structs that way, actually. The IDE just lagged on its error-checking for several minutes, for some reason.
``` #include <stdio.h> void main() { char c = getchar(); while ( c != '.') { putchar(c); c = getchar(); } } ``` when you run above code and input any string like "Shubham jain". the whole string gets copied and gets printed whilegetchar()should have read only the first character from the string. can someone explain h...
When you input a string using your program, it will automatically provide input for every char in the string ongetcharfunction, calling it multiple times. The moment the loop detects a '.' the program stops reading any more characters.