question
stringlengths
25
894
answer
stringlengths
4
863
I am trying to calculate factorial using recursion but my program is returning wrong value. I am unable to understand the recursion functionality. Please help me in understanding how recursion works. My code is as follows: ``` #include <stdio.h> #include <math.h> int main() { //code int T,N,sol; scanf(...
Replace your fact function with this one: ``` int fact(int n) { int value = 1; if(n>0) { value=n*fact(n-1); } return value; } ```
I am writing 3200 floats like so: ``` float fft[3200] = {0}; get_fft_frame(dev, fft, 3200); // rf sensor int written = write(sd, fft, sizeof(fft)); ``` and reading then like this: ``` float *fft = new float[3200]; int inRead = 0; while (inRead < (3200*4)) { //sleep(1); int bytesRead = read(sd, fft + inRead,...
You're mixing up your offsets.inReadis measured in bytes, but when you add it tofftit is multiplied bysizeof floatby the rules of pointer arithmetic. The offset expression in theread()call should be ``` ((char*)fft)+inRead ```
Does gcc addatributein signature of function, or not? Will these functions be compiled if it's in the same source file? ``` void*__attribute__ ((noinline)) GetCurrentIp(void) { some code... } void*GetCurrentIp(void); void*__attribute__ ((always_inline)) GetCurrentIp(void) ```
Even if the question is about C, we can let g++ answer it (seeFunction Names as Strings). f.C: ``` #include <stdio.h> extern "C" void *__attribute__((noinline)) GetCurrentIp(void) { printf("signature of %s: %s\n", __func__, __PRETTY_FUNCTION__); return __builtin_return_address(0); } int main() { GetCur...
I'm trying to understand the lock-less list in the Linux kernel. This is defined in llist.h. Why do they have two structs, to define a list: ``` struct llist_head { struct llist_node *first; }; struct llist_node { struct llist_node *next; }; ``` Why not have just one struct that has a pointer to the next ...
Why do they have two structs, to define a list? Because it ispossibleto usedifferentstruct (types) fordifferentthings (head and node correspondingly). Linux kernel tends to follow same convensions as for usual programming. In case of double linked lists, both head and node areforced to have the same type: by design,...
I want to compile several c files and I want to have executables whose names are same as the c file's names i.e if I have trial1.c, how can I have trial1.out?
Do you want something like this? ``` for i in *.c; do gcc ${i::1}.c -o ${i::1}.out; done ``` Or, if you are interested on just knowing if they compile successfully: ``` for i in *.c; do gcc $i 2>/dev/null && echo "$i : OK" || echo "$i : FAIL"; done ```
I know * indicates it is a pointer, but what's the difference betweenint (* a)[2]and(int (*)[2]) ainC?
int (* a)[2];declaresaasa pointer to an array of twointwhile(int (*)[2]) acastsatoa pointer to an array of twoint.
This question already has an answer here:How does Linux execute a file? [closed](1 answer)Closed7 years ago. might be a stupid question but I'll try anyway: when you turn a shell-script into an executable, it uses the shebang to knows which interpreter to use when you run it. Does a C code/script/program uses/has so...
Yes. C program executables (and all compiled languages) start with the "magic" characters0x7fELF. The Linux kernel recognises this in the same way as it recognises shebang scripts, except that it then triggers the ELF loader, not the script interpreter. It's notactuallyshebang, but it's analogous.
I have been following these instructions(http://jonisalonen.com/2012/calling-c-from-java-is-easy/) on how to create a shared library, but these instructions only show how to do it with one file. When I use this file, that I made into a shared library, the .so file can't call other .c files in the same place. How do i ...
1) Create your object files with-fPIC: ``` gcc -fPIC -c file1.c ``` This createsfile1.o. (same forfile2.c,file3.cand so on). 2) Link it in a shared library. ``` gcc -shared -o library.so file1.o file2.o file3.o ``` Adjust accordingly for additional compiler flags, include paths from other stuff you're using etc.
This question already has answers here:how does url within function body get compiled(2 answers)Closed7 years ago. I found I added some URL in source code but forgot to comment it, but still can compile, and I test it individually: ``` int main(){ http://localhost return 0; } gcc hello.c -o hello.exe ``` W...
Because it'll be treated as a label followed by a comment. So you could later: ``` goto http; ``` If you turn on warnings:-Wallit'll warn you gracefully: ``` In function ‘main’: :2:5: warning: label ‘http’ defined but not used [-Wunused-label] http://localhost ```
I come across an example of a function as below: ``` int someFunction(void) { int i; for(i = 0; i < 10; i++) { a_var[i] = 0xFFFF; //uninitialize a_var } return 0; } ``` What is the purpose of uninitialize a variable and why is it have to use 0XFFFF?
Code is notun-initializinga variable. Code is simply setting the variable to the value0XFFFFor65535.@user2357112 The author of the code may be using this value (16 one bits) to signify something special - but that is application specific. There is no general un-initializing a variable in C.@And
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.Closed7 years ago.Improve this question ``` char name [Number]; ``` [Number] is bytes or bits?
Number specifies the number of elements in the array. We can do: ``` char name[10]; ``` To allocate 10 bytes, or something like: ``` #define Number 10 char name[Number]; ``` This means you can store up to 10 characters, although the \0 sequence marks the end of a string - this tells other string handling functio...
This question already has answers here:Printing with "\t" (tabs) does not result in aligned columns(8 answers)Closed7 years ago. ``` #include "stdio.h" int main() { int toes = 10; printf("toes=%d\t2toes=%d\ttoes2=%d\n",toes,toes+toes,toes*toes); return 0; } ``` //This is an exercise from c primer plus. A...
It works fine for me. (example) Output: ``` toes=10 2toes=20 toes2=100 ``` Note that\tmeans "tabulate", or in other words to pad to the nearest multiple ofNposition, whereNis usually 8. toes=10takes up 7 characters, so to reach the next multiple of 8 would require printing 1 space.
I found some code that gets the size of struct like this: ``` sizeof(struct struct_type[1]); ``` I tested and it does return the size ofstruct_type. And ``` sizeof(struct struct_type[2]); ``` returns twice the struct size. Edit: struct_typeis a struct, not an array: ``` struct struct_type { int a; int ...
Remembersizeofsyntax: ``` sizeof ( typename ); ``` Here typename isstruct struct_type[N]or in more readable formstruct struct_type [N]which is an array of N objects of type struct struct_type. As you know array size is the size of one element multiplied by the total number of elements.
I was wondering, in the following code : ``` { int i = 42; goto end; } end: ``` What is the status of the symboliwhen we reachend:(what would we see in a debugger) ? Does it still exist, even if we're out of the scope ? Is there a standard behavior or is it compiler-dependent ? For the sake of the example, ...
A variable that has been declared in a block will "live" only in that block (it does not matter if you used goto or not). This behavior is the same in c++
I understand from the signature anddocumentationofDuplicateHandlethat I can duplicate a handle from an external (possibly unrelated) process, given that I have permission and know both the process ID and the handle value. Is that true? If so, which permissions must be granted to the processes and/or handles?
This is described in the documentation forDuplicateHandle(): hSourceProcessHandle [in]A handle to the process with the handle to be duplicated.The handle must have the PROCESS_DUP_HANDLE access right. So the ACL for the remote process must grant youPROCESS_DUP_HANDLEand you must request that right when callingOpenPr...
Both C and C++ standards do not specify the exact length of some data types, only their minimum lengths. I have a third party library:someLib.lib(compiled for my platform) and its correspondingsomeLib.h. Let's say it contains the following functions: ``` int getNumber(); void setNumber(int number); ``` When I compi...
You should not get compiler or linker errors, only undefined behavior at run-time. Possibly crashes, or if you're lucky just weird results.
I would like to have a pointer to client pixels of a windowed window in order to blit my own pixels. I do not want to use Gdi set pixel function. How shall I proceed ? I don't want to use directdraw. EDIT: If someone wants a ready code template, check out here :http://sol.gfxile.net/wintut/ch3.html
GDI always hides the screen display behind an HDC so you are always going to need to use BitBlt with a source, and destination HDC to get content onto it. However, as a compromise, I think you are looking for the methodCreateDIBSectionwhich will give you an area of memory you can directly manipulate, as well as an HB...
This is a theoretical question. To understand further how a return statement at the end of a function can be manipulated. Can we do like this: ``` int intialize1() { ...do smth; ...do smth; return initialize2(); } ``` in other c file ``` int initialize2() { ...do other thing; ...do other thing; ...
What you wrote is completely correct, frequently done, and functionally equivalent to: ``` int initialize1() { ...do smth; ...do smth; int x_value; // Create a place to store the return value x_value = initialize2(); // Get the result of the function, and store it. return x_value; ...
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
If you have Apple development tools installed, it should be found in the most possible unixoid place:/usr/include/ctype.h- At least that's where it is on my Macbook with Xcode installed.
``` #include<stdio.h> main(){ int a,b,c; scanf("%d-%d",&a,&b); c=a+b; printf("%d",c); } ``` What is the output we can expect from this code?
Yes, using not whitespace characters in ascanfformat string is legal. Those characters are expected to be read and skipped over. If those characters are not given in the input,scanfstops reading at that point. For example, if your input was3-4, the3would be stored ina, the-would match the pattern, and the4would be ...
I understand from the signature anddocumentationofDuplicateHandlethat I can duplicate a handle from an external (possibly unrelated) process, given that I have permission and know both the process ID and the handle value. Is that true? If so, which permissions must be granted to the processes and/or handles?
This is described in the documentation forDuplicateHandle(): hSourceProcessHandle [in]A handle to the process with the handle to be duplicated.The handle must have the PROCESS_DUP_HANDLE access right. So the ACL for the remote process must grant youPROCESS_DUP_HANDLEand you must request that right when callingOpenPr...
Both C and C++ standards do not specify the exact length of some data types, only their minimum lengths. I have a third party library:someLib.lib(compiled for my platform) and its correspondingsomeLib.h. Let's say it contains the following functions: ``` int getNumber(); void setNumber(int number); ``` When I compi...
You should not get compiler or linker errors, only undefined behavior at run-time. Possibly crashes, or if you're lucky just weird results.
I would like to have a pointer to client pixels of a windowed window in order to blit my own pixels. I do not want to use Gdi set pixel function. How shall I proceed ? I don't want to use directdraw. EDIT: If someone wants a ready code template, check out here :http://sol.gfxile.net/wintut/ch3.html
GDI always hides the screen display behind an HDC so you are always going to need to use BitBlt with a source, and destination HDC to get content onto it. However, as a compromise, I think you are looking for the methodCreateDIBSectionwhich will give you an area of memory you can directly manipulate, as well as an HB...
How can I useperf_event_open()to retrieve callchain? I do not want to use the callchains provided by oprofile and perf. I want to get them directly. It seems that I need tommap()the file descriptor returned byperf_event_open(). I do not know the size ofmmap()and how to read from it.
Chapter 8 ofthis bookdescribes, by example, how to useperf_event_open()for bothcountingandsamplingmodes.
I am trying to make sure I understand how %n is used, and I have the very simple code below ``` #include <stdio.h> int main (void) { int c1, c2; printf("This%n is fun%n\n", &c1, &c2); } ``` It should print "This is fun" and store the number of characters printed in c1 and c2. But all I get as an output is the st...
Your program is crashing after printingThis. MinGW uses Microsoft's Visual C++ runtime by default.MSDNsays following about "%n": Because the%nformat is inherently insecure, it is disabled by default. If%nis encountered in a format string, the invalid parameter handler is invoked, as described inParameter Validat...
If the signals that I want to mask and unmask are common between all threads, can I use one global variable for the signal set in POSIX C to pass to pthread_sigmask, or there should be different sigsets for each thread?
The second argument ofpthread_sigmask()is constant (const sigset_t *set) [meaning that the memory pointed bysetwill not be modified], so you can declare a single [possibly global, at your opinion] variable, without the need of implementing any thread locking mechanism while accessing it as it won't be modified. All th...
In C, if the array is initialised while declaration then the dimension is optional. Why?
Because if you tell it to create an array holding a1,2, and3, it can easily figure out the required size since you gave it 3 elements.
I am not sure if the question is framed correctly. But I am using code blocks on a windows machine. I want to usegcc -o myfile myfile.c -lpthread. But in my code blocks I don't have this -lpthread flag(is that called a flag?). So where do I need to add this in code blocks so that when I click build, it will simply cal...
-lpthread is a flag to the linker saying to include the library pthread (POSIX threads). I'm not particularly good with code blocks but in the main settings you should be able to find options for configuring the compiler or linker. You need to add the library "pthread" there. Take a look at this possible duplicate:Ho...
This question already has answers here:How does the ternary operator work?(12 answers)Closed7 years ago. I came across a different way of returning values and got excited. What does it mean exactly? If I had to guess, I would say it means something along the line of... if z < 0, then add z and y, else return z? `...
You're using theternary operatorand returning the result of that. It's basically an if statement on one line. It's saying: ``` if(z < 0) { return z + y; } else { return z; } ```
This question already has answers here:What does a double hash (##) in a macro mean?(2 answers)Closed7 years ago. I am familiar with std #defines and macro expansion for min max function but this one throws me. In particular the #'s in the definition. Your thoughts appreciated. ``` #define TAB_WIDGET_ROW(t) {t##...
You should read somedocumentationconcerning theC Preprocessor. The##is aboutConcatenation. So an invocation likeTAB_WIDGET_ROW(xy)of yourTAB_WIDGET_ROWmacro would probably be expanded to{xy_seq, xy_len, xy_rep}
``` #include <stdio.h> int main(void) { printf("%d", sizeof (getchar()) ); } ``` What I expect is,1. Type input.2. Read input and return input value.3. Evaluate sizeof value.4. Print the sizeof value. But the first step never happens. Why doesn't the first step happen?
Thesizeofoperator does not evaluate its operand unless its type is a variable length array type: It looks at the type and returns the size. This is perfectly safe: ``` char *ptr = NULL; // NULL ponter! printf("%zu", sizeof *ptr); ``` It will return1, since it does not have to evaluate the expression to know the answ...
I am not sure if the question is framed correctly. But I am using code blocks on a windows machine. I want to usegcc -o myfile myfile.c -lpthread. But in my code blocks I don't have this -lpthread flag(is that called a flag?). So where do I need to add this in code blocks so that when I click build, it will simply cal...
-lpthread is a flag to the linker saying to include the library pthread (POSIX threads). I'm not particularly good with code blocks but in the main settings you should be able to find options for configuring the compiler or linker. You need to add the library "pthread" there. Take a look at this possible duplicate:Ho...
This question already has answers here:How does the ternary operator work?(12 answers)Closed7 years ago. I came across a different way of returning values and got excited. What does it mean exactly? If I had to guess, I would say it means something along the line of... if z < 0, then add z and y, else return z? `...
You're using theternary operatorand returning the result of that. It's basically an if statement on one line. It's saying: ``` if(z < 0) { return z + y; } else { return z; } ```
This question already has answers here:What does a double hash (##) in a macro mean?(2 answers)Closed7 years ago. I am familiar with std #defines and macro expansion for min max function but this one throws me. In particular the #'s in the definition. Your thoughts appreciated. ``` #define TAB_WIDGET_ROW(t) {t##...
You should read somedocumentationconcerning theC Preprocessor. The##is aboutConcatenation. So an invocation likeTAB_WIDGET_ROW(xy)of yourTAB_WIDGET_ROWmacro would probably be expanded to{xy_seq, xy_len, xy_rep}
``` #include <stdio.h> int main(void) { printf("%d", sizeof (getchar()) ); } ``` What I expect is,1. Type input.2. Read input and return input value.3. Evaluate sizeof value.4. Print the sizeof value. But the first step never happens. Why doesn't the first step happen?
Thesizeofoperator does not evaluate its operand unless its type is a variable length array type: It looks at the type and returns the size. This is perfectly safe: ``` char *ptr = NULL; // NULL ponter! printf("%zu", sizeof *ptr); ``` It will return1, since it does not have to evaluate the expression to know the answ...
I am on 64-bit Linux x86. I need to executemmapsyscall usingsyscallfunction.mmapsyscall number is 9: ``` printf("mmap-1: %lli\n", syscall(9, 0, 10, 3, 2 | 32, -1, 0)); printf("mmap-2: %lli\n", mmap( 0, 10, 3, 2 | 32, -1, 0)); ``` However, when I run it, thesyscallfunction gives wrong results. ``` mmap-1:...
In yoursyscall(), instead of passing in0 (NULL)for the first parameter,addr, pass some pointer you have declared previously. This way you can access the memory mapped bymmap.mmapfunction declaration: ``` void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset); ```
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.Closed7 years ago.Improve this question I'm rather new to C and sometimes I come across strange notations, especially in relation with pointers. A...
First increment pointer and then adddelta_forceto the value pointed to by the pointer. ``` *(++ptr) += delta_force; ``` means same as ``` ptr = ptr + 1; *ptr = *ptr + delta_force; ```
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed7 years ago.Improve this question Quite simply, I want to delete a file that may or may not exist. Is it bad practice ...
Should I check whether a file exists before deleting it? There is no such requirement or need, and doing so is in no way useful. and ignore the return value? Usually, the user may want to know whether a file was deleted or not, so it is often a bad idea to ignore the return value. Further, the user probably also wa...
We all know that c doesn't support operator overloading.Can anyone tell me if that is so, then how are we able to use the less than sign in the#includedirective and incomparisonalso? Or the functionality provided is called something else and defined in language?
Many symbols in C have different meaning depending on context. Example: *can mean either multiplication or pointer dereference. Such dual meanings makes it a bit tricky to write a C parser and even trickier to provide helpful error messages when the code doesn't compile. Note that this dual meaning isnotoperator ...
I have achararray in which I would like to loop, where its divided by all math operations , for example, right now I am looking only for=sign , so ``` for (char *p = strtok(data,"="); p != NULL; p = strtok(NULL, " ")) { numberOfChars++; } ``` I would like to loop where not only"="is the token , but ...
You can symply loop through the string ``` for (size_t i=0; i < strlen(data); i++) { if ((data[i] == '+') || (data[i] == '-') || (data[i] == '*') || (data[i] == '\') || (data[i] == '=')) { numberOfChars++; } } ```
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.Closed7 years ago.Improve this question Why is the struct pointer repeated again inside this struct: ``` typedef struct node { int data; str...
Recursive structs are very useful for all kinds of node-based data structures, in this case a linked list: Note howbis linked toaandcis linked tobvia thenextmember.
For example: ``` 5*3 + 9*6 ``` As far as I know, according to types of compilers in some5*3is evaluated first while in other compilers9*6is evaluated first. Is there a function in C or technique that can check which is evaluated first?
Is there a function in C or technique that can check which is evaluated first? You can define a function to multiply the numbers and add code to produce some output. ``` int multiply(int n1, int n2) { printf("Computing %d*%d\n", n1, n2); return n1*n2; } ``` and use the function to do the multiplication instea...
I am compressing several long strings using ZLIB, which uses LZ77 representations of repeated substrings prior to encoding these representations using a Huffman tree. I am interested in studying the sequence of integer tuple representations themselves, and have been looking in the code to figure out where these are...
You can useinfgento disassemble a deflate stream. It will print the decoded symbols in a readable form, e.g.match 41 105indicating a string to copy of length 41, from a distance back of 105.
When using GCC to compile a simple hello world program, I get the following error: ``` c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: final link failed: No space left on device ``` There is plenty of disk space and memory left. I am calling GCC from within the Git Bash command line. What is ca...
I uninstalled GCC from the simple MinGW installer and installed the Codeblocks IDE. Codeblocks has an option to install the MinGW GCC. I do not understand what was wrong but this method works. The exact same command with the exact same C file compiles Here is a simple video that shows the process:https://www.youtube....
We all know that c doesn't support operator overloading.Can anyone tell me if that is so, then how are we able to use the less than sign in the#includedirective and incomparisonalso? Or the functionality provided is called something else and defined in language?
Many symbols in C have different meaning depending on context. Example: *can mean either multiplication or pointer dereference. Such dual meanings makes it a bit tricky to write a C parser and even trickier to provide helpful error messages when the code doesn't compile. Note that this dual meaning isnotoperator ...
I have achararray in which I would like to loop, where its divided by all math operations , for example, right now I am looking only for=sign , so ``` for (char *p = strtok(data,"="); p != NULL; p = strtok(NULL, " ")) { numberOfChars++; } ``` I would like to loop where not only"="is the token , but ...
You can symply loop through the string ``` for (size_t i=0; i < strlen(data); i++) { if ((data[i] == '+') || (data[i] == '-') || (data[i] == '*') || (data[i] == '\') || (data[i] == '=')) { numberOfChars++; } } ```
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.Closed7 years ago.Improve this question Why is the struct pointer repeated again inside this struct: ``` typedef struct node { int data; str...
Recursive structs are very useful for all kinds of node-based data structures, in this case a linked list: Note howbis linked toaandcis linked tobvia thenextmember.
For example: ``` 5*3 + 9*6 ``` As far as I know, according to types of compilers in some5*3is evaluated first while in other compilers9*6is evaluated first. Is there a function in C or technique that can check which is evaluated first?
Is there a function in C or technique that can check which is evaluated first? You can define a function to multiply the numbers and add code to produce some output. ``` int multiply(int n1, int n2) { printf("Computing %d*%d\n", n1, n2); return n1*n2; } ``` and use the function to do the multiplication instea...
I am compressing several long strings using ZLIB, which uses LZ77 representations of repeated substrings prior to encoding these representations using a Huffman tree. I am interested in studying the sequence of integer tuple representations themselves, and have been looking in the code to figure out where these are...
You can useinfgento disassemble a deflate stream. It will print the decoded symbols in a readable form, e.g.match 41 105indicating a string to copy of length 41, from a distance back of 105.
When using GCC to compile a simple hello world program, I get the following error: ``` c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: final link failed: No space left on device ``` There is plenty of disk space and memory left. I am calling GCC from within the Git Bash command line. What is ca...
I uninstalled GCC from the simple MinGW installer and installed the Codeblocks IDE. Codeblocks has an option to install the MinGW GCC. I do not understand what was wrong but this method works. The exact same command with the exact same C file compiles Here is a simple video that shows the process:https://www.youtube....
I am trying to figure out how to implement a Key Security Module (KSM) for Apple FairPlay into our Key Server but as far as I understand from the sample "Server Reference Implementation" project in Apple FairPlay SDK which is written in C, they want or they advice us to implement in C. But in one of their FairPlay sl...
I've written a Fairplay implementation in Python and specified an implementation for Java - it can be written in any language you choose as long as you have the necessary crypto libraries available (or know how to implement some of the required asymmetric cryptography).
The following program gives output as 17,29,45; I can't understand what does**++pp;mean. Can anyone explain the program in detail. ``` #include <stdio.h> int main() { static int a[] = {10, 22, 17, 29, 45}; static int *p[] = {a, a + 2, a + 1, a + 4, a + 3}; int **pp = p; **++pp; ...
In your code,**++pp;is the same as* (* ( ++pp));. It first increments the pointer, then deferences twice (the first dereference result is of pointer type, to be elaborate). However, the value obtained by dereferencing is not used. If you have compiler warnings enabled, you'll get to see something like warning: value...
This question already has answers here:Is it possible to modify a string of char in C?(9 answers)Closed7 years ago. Im doing something wrong. This is the piece of code from ARM code (Keil5 IDE): ``` uint8_t * at_ss_data = (uint8_t *)("\n\rAT$SS=AA AA\n\r"); at_ss_data[12] = 0; ``` but the 12th index (the lastA) do...
You must not modify a string literal (which isundefined behavior). You should use an array initialized with a string literal. This way, your code should be: ``` uint8_t at_ss_data[] = "\n\rAT$SS=AA AA\n\r"; at_ss_data[12] = 0; ```
This is one of the most important reasons for me to use C/C++ in writing some classes of system software, but it's been nothing more than a compiler extension which happens to be very common. Why isn't the committee considering to support it officially? Was it incompatible with any clauses in the existing spec, such a...
Why isn't the committee considering to support it officially? Because nobody proposed it. The closest thing to such a proposal wasN3986 (PDF), which only works for bitfields. Thecomments from the discussionsuggest that the committee would be interested, but they want to understand what existing practice does before t...
Given the following lines: ``` char szInline[80]; char szDescription[80] = { NULL }; float fCost = 0; sscanf (szInline, "%80[^,], %f", szDescription, &fCost); ``` What does the %80[^,] do?
Read at most 80 chars up to the next,comma. Btw, theszDescriptionbuffer is too small by 1.
This question already has answers here:The "backspace" escape character '\b': unexpected behavior?(5 answers)Closed7 years ago. Here is the code below: ``` #include <stdio.h> int main(int argc, char* argv[]) { printf("WORD\b\b WORD\b\b"); return 0; } ``` which generates this output: ``` WO WORD ``` The q...
It does have an affect, the affect is moving the cursor back, but'\b'won't delete any characters unless you overwrite them. in case you want to print something else afterwards, printing will resume from the current cursor position. note: this behavior is dependent on the terminal you use to display text.
This is my test code: ``` #include <cstdio> struct A { int a; int b; int c __attribute__((aligned(4096))); int d; }t; int main() { printf("%d\n",sizeof(t)); return 0; } ``` The result is 8192, but I can't figure out the reason.
There are a few facts about alignment in structs that are worth mentioning: The size of a type is always a multiple of its alignment.The alignment of a struct is always a multiple of the alignment of all its members. So, since one of these members has an alignment of 4096, the alignment of the struct itself is at le...
I have just started to learn C. But the first program in the book which i am referring generates an error that "printf was not declared in this scope" I am typing the code exactly as it is given in the book. Still the error is being given.
The book is outdated. Add ``` #include <stdio.h> ``` to your program. It provides the declaration ofprintfand many other functions. For a complete list of functions defined in the file, lookupits documentation.
During program termination, how do you unblock a thread that has been previously blocked with a call toGetQueuedCompletionStatus()?
You could post termination message to the IO completion port usingPostQueuedCompletionStatusAPI call or simply closeIOCPhandle usingCloseHandle. If a call toGetQueuedCompletionStatusfails because the completion port handle associated with it is closed while the call is outstanding, the function returnsFALSE,*lpOv...
So I'm facing a problem with Visual Studio 2013 This code shows no compilation errors but a debug error Stack around the variable 'Joueur' was corrupted. This is the code: == Source.cpp ``` #include <stdlib.h> #include <stdio.h> #include "Header.h" int main() { Personne Joueur[2]; printf("***** Bienvenue ...
ChangePersonne Joueur[2]; -> Personne Joueur[3]; You do not have enough memory to hold more than 2 structures.
Is anyway to get a global C String const property in Objective-C? I'm doing something like this: ``` const char *content_type = [@"application/vnd.ccm.pmsg.v1+json" UTF8String]; @implementation StringChannelCallable ... @end ``` And I get this error: Initializer element is not a compile-time constant If I decl...
you can't use method in the variable or constant‘s declare and you should use c language grammar to declareconst char *, like this : ``` const char *content_type = "application/vnd.ccm.pmsg.v1+json"; ```
How to keep adding for-loopntimes? For example, ifn = 3then for-looping 3 times like below: ``` for() { for() { for() { //keep adding for-loops depending on n } } } ``` I speculate that recursion might work. Any ideas?
``` void recursiveForLoops(int n, int limit) { int i; if(n == 0) { //do something return; } for(i = 0; i < limit; ++i) { recursiveForLoops(n - 1, limit); } } ``` This will generatennestedforloops, each one iteratinglimittimes. You could accomplish the same outpu...
I know what a delimiter is, but what does the string" \t\r\n\a"stand for in the example below? ``` #define DELIMITER " \t\r\n\a" ```
``` \t = tab \r = carriage return \n = newline \a = alert (bell) ``` Looks like the author was creating a preprocessor DEFINE containing these common delimiters.
I am a little bit confused, it seemed to that my flow is right, but I am getting Seg. fault (line 15) My struct in header: ``` typedef struct ringBuf_t { uint32_t data[BUF_CAPACITY]; int head; int tail; uint32_t capacity; } ringBuf_t; ``` and how I use it: ``` ringBuf_t *create() { ringBuf_t bu...
In line 5 you create a local variable on the stack, and when the function return it address the scope ends and the object memory is free. Hence if you use that address later you got a seg-fault
This question already has answers here:Unexpected output in c [duplicate](4 answers)Closed7 years ago. ``` #include<stdio.h> #define sqr(i) i*i int main() { printf("%d %d", sqr(3), sqr(3+1)); //output 9,7 return 0;` } ``` why the out put is 9,7? can anybody explain with steps how that 7 is get...
The macrosqr(i) i*iforsqr(3+1)will be evaluated to3+1*3+1which is ...7. Put the arguments of the macro in parentheses: ``` #define sqr(i) (i) * (i) ``` if you really want to use a macro for this.
If you want to useQt, you have to embracequint8,quint16and so forth. If you want to useGLib, you have to welcomeguint8,guint16and so forth. OnLinuxthere areu32,s16and so forth. uC/OSdefinesSINT32,UINT16and so forth. And if you have to use some combination of those things, you better be prepared for trouble. Becaus...
stdint.hdidn't exist back when these libraries were being developed. So each library made its owntypedefs.
This question already has answers here:Is ((void *) -1) a valid address?(3 answers)Closed7 years ago. I was looking at the documentation ofsbrksystem call and foundthis: On success,sbrk()returns the previous program break. (If the break was increased, then this value is a pointer to the start of the newly allocated...
``` (void *) -1 == (size_t) -1 ``` It's0xFFFFFFFFon 32 bit machine and0xFFFFFFFFFFFFFFFFon 64 bit machine, an invalid address that is supposed to be bigger than any other address.
I want to declare adoubletype array dynamically, so here is my code ``` void function(int length, ...) { ... double *a = malloc(sizeof(double) * length); memset(a, 1, sizeof(double) * length); for (int i = 0; i < length; i++) { printf("%f", a[i]); } ... } ``` When I pass alength...
memsetsets bytes. You're trying to set doubles. Just loop from0tolengthand set each one to1.0: ``` for (int i = 0; i < length; i ++) { a[i] = 1; // or 1.0 if you want to be explicit } ```
This question already has answers here:How does the Comma Operator work(9 answers)Closed7 years ago. I came across a code snippet which used a statementint k=(a++,++a)in it. I don't understand which type of statement is this(a++,++a)and how it will be evaluated. Why is the bracket is used here? Is it a function call?...
It's not a function call. This is an example of using the comma operator, which evaluates each expression from left to right and returns the result of the rightmost expression. It's the same as writing ``` a++; k = ++a; ``` If it had been written ``` k = a++, ++a; ``` then it would have been parsed as ``` (k = ...
Somewhere in my code I useint array[L]. I specify the array length:#define L 64. Everything is ok. But what if I want to specify this value 64 in a (external) text file, not in the code? How can I read a text file into #define?
But what if I want to specify this value 64 in a (external) text file, not in the code? There are two methods to set the value of a macro that I can think of. Define it in code. A text file won't do for this purpose.Define it as command line option in the compiler (-DL=64).If you usemake, you can define the option i...
A solution from atop answeris To check a bit, shift the number x to the right, then bitwise AND it:bit = (number >> x) & 1;That will put the value of bit x into the variable bit. What confuses me is this, when assuming the following: ``` unsigned number = 5; //0101 int x = 2; // ``` After a shift(number >> x)we ge...
Yes, you are doing the bitwise AND against the third bit. Considerxto be zero-indexed, i.e. the first bit is bit 0.
What is maximum length of user space APC queue to one thread in Windows? I read Windows Internals 6 Part 1 and didn't finded any information about this.
There is no fixed limit. KAPC structures are allocated fromnonpaged pooland linked to a thread by a singleLIST_ENTRYstructure. Nonpaged pool islimited by available system resources only.
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.Closed7 years ago.Improve this question Like n fork calls will create 2^n processes, but to specifically create k processes what to do?
You should have to use thread concept instead of using fork(). ``` for(i=0; i < Num_OF_Thread; i++) { pthread_create( &thread_id[i], NULL, print_message_function, NULL ); } void print_message_function( ) { // Task wich u want ro perform } ```
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.Closed7 years ago.Improve this question One purpose of left shift operator is multiply the left Operand with 2 and right shift for integer Division...
Only beginners would ever use a shift for division or multiplication (including people who are writing software for decades and are still beginners). Shift operations are for shifting bits. When you want to shift bits you use them. If you don't know what shifting bits means, you don't want to use them.
Let's say I use winsock'sshutdown(s, SD_RECEIVE)for TCP.What happens when after the shutdown, the peer sends packets. According to MSDN,https://msdn.microsoft.com/en-us/library/windows/desktop/ms740481.aspx For TCP sockets, if there is still data queued on the socket waiting to be received, or data arrives subsequen...
That's what it means, but only in Windows. On UNIX the packets are acknowledged and thrown away. On Linux they are acknowledged and buffered, which will eventually stall the sender.
This question already has answers here:How does the Comma Operator work(9 answers)Closed7 years ago. I came across a code snippet which used a statementint k=(a++,++a)in it. I don't understand which type of statement is this(a++,++a)and how it will be evaluated. Why is the bracket is used here? Is it a function call?...
It's not a function call. This is an example of using the comma operator, which evaluates each expression from left to right and returns the result of the rightmost expression. It's the same as writing ``` a++; k = ++a; ``` If it had been written ``` k = a++, ++a; ``` then it would have been parsed as ``` (k = ...
Somewhere in my code I useint array[L]. I specify the array length:#define L 64. Everything is ok. But what if I want to specify this value 64 in a (external) text file, not in the code? How can I read a text file into #define?
But what if I want to specify this value 64 in a (external) text file, not in the code? There are two methods to set the value of a macro that I can think of. Define it in code. A text file won't do for this purpose.Define it as command line option in the compiler (-DL=64).If you usemake, you can define the option i...
A solution from atop answeris To check a bit, shift the number x to the right, then bitwise AND it:bit = (number >> x) & 1;That will put the value of bit x into the variable bit. What confuses me is this, when assuming the following: ``` unsigned number = 5; //0101 int x = 2; // ``` After a shift(number >> x)we ge...
Yes, you are doing the bitwise AND against the third bit. Considerxto be zero-indexed, i.e. the first bit is bit 0.
I was studying the code for the Kilo text editor here: https://github.com/antirez/kilo/blob/master/kilo.c And I noticed that the includes definedstdlib.htwice (UPDATE: Comments are mine): ``` #include <termios.h> #include <stdlib.h> // first time #include <stdio.h> #include <errno.h> #include <string.h> #include <...
As stdlib.h has an include guard, there is no point in including it twice. Probably the mistake was caused by merging two files, both dependant on stdlib.h.
I'm writing a C program. During "code & fix" phase I use DDD (gdb UI) to debug. I compile with gcc -g and invoke ddd with ``` ddd ./a.out ``` DDD has worked well until, suddenly, when I invoke it, the code doesn't appear anymore. All I visualize is the DDD default screen (the same screen that pops up when opening ...
I have figured it out. I have uninstalled ddd with purge options: ``` sudo apt-get remove --purge ddd ``` Then remove ddd folder ``` rm -r ~/.ddd ``` Then ``` sudo apt-get install ddd ``` Now it works!
I am using C language in an embedded system. I have this uint8 array. ``` static uint8_t data_array[20]; ``` Content of data_array is terminated with'\n'. I want to check whether the first 3 bytes are "ABC". This is how I do it. ``` if (data_array[0]=='A' && data_array[1]=='B' && data_array[2]=='C') { printf("...
Just use a loop: ``` static uint8_t data_array[20] = "ABC"; static uint8_t s[4] = "ABC"; static uint8_t length = 3; uint8_t bool = 1; for (int i = 0; i < length; i++) { if (s[i] != data_array[i]) { bool = 0; break; } } if (bool) { printf("pattern found\n"); } ``` Live code here
An exampleprintkcall: ``` printk(KERN_INFO "Log message.\n"); ``` Perhaps this question is more about C in general, because I've never seen a function in C before that separated parameters without a comma. How does this work? What does the compiler do with this information? Since the log level is an integer and the...
Theprintk()function only takes oneconst char*argument. TheKERN_INFOmacro expands to"\001" "6", yielding: ``` printk("\001" "6" "Log message.\n"); ``` The C lexer concatenates adjacent string literal tokens which means that the above is converted into: ``` printk("\0016Log message.\n"); ```
What is the reason for the-Wlong-longgcc warning? From the gcc man page: ``` -Wlong-long Warn if long long type is used. This is enabled by either -Wpedantic or -Wtraditional in ISO C90 and C++98 modes. To inhibit the warning messages, use -Wno-long-long. ``` As I understand it,long longis required to be a...
There was nolong longtype yet in ISO C90 and C++98. It has only been added in ISO C99 and C++11. GCC provided it as an extension prior to standardization, though.
I was studying the code for the Kilo text editor here: https://github.com/antirez/kilo/blob/master/kilo.c And I noticed that the includes definedstdlib.htwice (UPDATE: Comments are mine): ``` #include <termios.h> #include <stdlib.h> // first time #include <stdio.h> #include <errno.h> #include <string.h> #include <...
As stdlib.h has an include guard, there is no point in including it twice. Probably the mistake was caused by merging two files, both dependant on stdlib.h.
I'm writing a C program. During "code & fix" phase I use DDD (gdb UI) to debug. I compile with gcc -g and invoke ddd with ``` ddd ./a.out ``` DDD has worked well until, suddenly, when I invoke it, the code doesn't appear anymore. All I visualize is the DDD default screen (the same screen that pops up when opening ...
I have figured it out. I have uninstalled ddd with purge options: ``` sudo apt-get remove --purge ddd ``` Then remove ddd folder ``` rm -r ~/.ddd ``` Then ``` sudo apt-get install ddd ``` Now it works!
I am using C language in an embedded system. I have this uint8 array. ``` static uint8_t data_array[20]; ``` Content of data_array is terminated with'\n'. I want to check whether the first 3 bytes are "ABC". This is how I do it. ``` if (data_array[0]=='A' && data_array[1]=='B' && data_array[2]=='C') { printf("...
Just use a loop: ``` static uint8_t data_array[20] = "ABC"; static uint8_t s[4] = "ABC"; static uint8_t length = 3; uint8_t bool = 1; for (int i = 0; i < length; i++) { if (s[i] != data_array[i]) { bool = 0; break; } } if (bool) { printf("pattern found\n"); } ``` Live code here
I am trying to create threads in C that have contiguous id numbers. For example let us say I want to create 10 threads, then I want to give them the id's 1 through 10. Later on, I want to be able to access these id's and print them out from the thread function. Is this feasible? I know this may seem simple but I have...
Thread IDs are created by the OS or threading library. You can't control what they will be. You don't need the IDs to be consecutive. Create an array and store each thread's ID in the array. Then you can use the array to access them in order. Something like this (assuming you use pthreads): ``` pthread_t thread_...
...or any Python object that exists in an importable library. I have found PyDateTime_* functions in thedocumentationfor creating objects from the datetime module, but I can't find anything to do with the python decimal module. Is this possible? Looking for a Boost.Python way if there is one, but the native API's wil...
In Boost.Python that would be something like ``` bp::object decimal = bp::import("decimal").attr("Decimal"); bp::object decimal_obj = decimal(1, 4); ```
This question already has answers here:Is an empty initializer list valid C code?(4 answers)Closed7 years ago. Is the below declaration valid in C? ``` char key[] = {}; ``` If not why not?
Per theonline C2011 standard, it is not valid; you may not have an empty initializer list (see 6.7.9, Syntax). That doesn't mean a specific implementation can't offer an empty initializer list as an extension, but the utility would be unclear. Beyond that, the compiler has no way of knowing how much storage to set a...
Using JNI I am storing a reference to a Java method object (obj) in order to call it later from C: ``` jobject obj = (*newEnv)->NewObject(newEnv, cls, mid); ``` wherenewEnvis my environment,clsis my class ID andmidis my method ID. Everything works fine except that upon creating this object to be used as a reference...
Thanks to Gabe Sechan's comments I was able to figure it out: ``` jmethodID construct = (*newEnv)->GetMethodID(newEnv,cls,"<init>","()V"); jobject obj = (*newEnv)->NewObject(newEnv, cls, construct); ``` Then I can call the method I want using: ``` (*newEnv)->CallVoidMethod(newEnv, obj, mid); ```
I got 32 bit integers that i want to store themin a dynamically allocated arrayand then send this array to others processes (in MPI ) ``` int32_t data; ``` I am confused ,which type of data should i use so that i can have an array of size lets say ,Nwith 32 bit integers? How can this be implemented?
... which type of data should i use so that i can have an array of size lets say ,Nwith 32 bit integers? ``` // The type of `p` is a pointer to a 32-bit signed integer. int32 *p; ``` How can this be implemented? ``` // No need to use `int32_t` in the next line of code // size of 1 element ---v-------v ...
``` #include <stdio.h> int main(void) { double height; //Error happens if I write double height instead of float height! printf("Height(inch): "); scanf("%f",&height); printf("%f inch = %f cm \n",height,height*2.54); } ``` As you can see in the comment, error happens if I write double height instead...
The%fformat specifier forscanfexpects a pointer to afloat, not adouble. This is significant because the two are different sizes. Passing in the address of adoublewill result in some but not all of the bytes comprising thedoubleto be populated, resulting in undefined behavior. To read a value into adouble, use%lf. ...
Using JNI I am storing a reference to a Java method object (obj) in order to call it later from C: ``` jobject obj = (*newEnv)->NewObject(newEnv, cls, mid); ``` wherenewEnvis my environment,clsis my class ID andmidis my method ID. Everything works fine except that upon creating this object to be used as a reference...
Thanks to Gabe Sechan's comments I was able to figure it out: ``` jmethodID construct = (*newEnv)->GetMethodID(newEnv,cls,"<init>","()V"); jobject obj = (*newEnv)->NewObject(newEnv, cls, construct); ``` Then I can call the method I want using: ``` (*newEnv)->CallVoidMethod(newEnv, obj, mid); ```
I got 32 bit integers that i want to store themin a dynamically allocated arrayand then send this array to others processes (in MPI ) ``` int32_t data; ``` I am confused ,which type of data should i use so that i can have an array of size lets say ,Nwith 32 bit integers? How can this be implemented?
... which type of data should i use so that i can have an array of size lets say ,Nwith 32 bit integers? ``` // The type of `p` is a pointer to a 32-bit signed integer. int32 *p; ``` How can this be implemented? ``` // No need to use `int32_t` in the next line of code // size of 1 element ---v-------v ...
``` #include <stdio.h> int main(void) { double height; //Error happens if I write double height instead of float height! printf("Height(inch): "); scanf("%f",&height); printf("%f inch = %f cm \n",height,height*2.54); } ``` As you can see in the comment, error happens if I write double height instead...
The%fformat specifier forscanfexpects a pointer to afloat, not adouble. This is significant because the two are different sizes. Passing in the address of adoublewill result in some but not all of the bytes comprising thedoubleto be populated, resulting in undefined behavior. To read a value into adouble, use%lf. ...
Is there a way to return a new array allocated with the static keyword after each invocation of a function? I can create a new array if i make a clone to the function, but not from the same function. Consider the following program: ``` #include <stdio.h> char *CrArray1(void); char *CrArray2(void); int main(void) {...
No,staticobjectsby definitionhave only one instance. You'll need to usemalloc()and callers of your function will need tofree()the memory.
Why*strptr = 0truncate the string?(C) Why the ascii value 30 of 0 become 0 of null? Here I'm confused with the number 0, string 0 and the string termianl 0. your explaination will be appreciated.
More precisely, there are three lexical elements that contain a zero character:0(unquoted),'0'(quoted, typically (but not always) equal to48or0x30unquoted) and'\0'(equal to0, but in character notation). The question is talking about two distinct values...'0' != '\0'. Forget about 30, 48, etc. Just remember'0'and'\0'a...
Following definition of structure is defined in one of my header file ``` typedef struct REMDEV_ADDR { UINT8 addr[DEVICE_ADDR_SIZE]; } RemDev_Addr; typedef RemDev_Addr BTDEV_ADDR; ``` Now I have following function which I want to use. ``` hci_acl_connect(UCHAR * bd_addr,UINT16 * handle); ``` So I made a glo...
Assuming that you want the function to do something with the arrayaddrin the structure, then there is no need for the casting. Just pass theaddrmember: ``` hci_acl_connect(hsu_addr.addr, &cont_hand); ``` That's assuming that bothUINT8andUCHARare both aliases ofunsigned char(which seems like a safe assumption).
I have the following structs in a C program. ``` typedef struct { unsigned char msg_id : 8; unsigned char msg_num : 8; } Message_Header_Type; typedef struct { Message_Header_Type header; int msg[32]; } Raw_Message_Type; ``` What I'm seeing is that the header in the Raw_Message_Type is taking up 4 bytes but I...
What you are looking for isstruct packing, which is platform and compiler dependent, the details are not specified in the C standard. With GCC, on a 32-bit platform, you could do the following to get a struct of size 2: ``` typedef struct __attribute__((__packed__)) { unsigned char msg_id; unsigned char msg_...
As much as I know after every function call the local variables are discarded. But when I executed this piece of code the variables retain their previous value. What is this behavior? Compiler: gcc 4.8.4 ``` #include<stdio.h> void t(); int main(void){ t(); t(); t(); return 0; } void t(){ int i; ...
The behavior of your program is undefined.iis uninitialized so any use ofibesides setting its values is undefined behavior. Most likely what you are seeing isigets the same "stack space" allocated to it each time so you are just reusing the previous value. Do note that when anint(or any type) goes out of scope the c...