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("%d\n",&T); while(T--) { scanf("%d\n",&N); sol=fact(N); printf("%d\n",sol); } return 0; } int fact(int n) { int value; while(n>0) { value=n*fact(n-1); n=n-1; } return value; } ```
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, (3200*4) - inRead); inRead += bytesRead; } ``` All the data is written in 1 write but it takes two read calls to get all the data. The first read returns 11584 and the second returns 1216. The problem is that the second read call just reads zeros. However if I uncomment the sleep call, it reads all the correct data. Is there a better way to get the data without sleeping?
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() { GetCurrentIp(); return 0; } ``` ``` > g++ f.C > a.out signature of GetCurrentIp: void* GetCurrentIp() ``` So, the attribute is not part of the signature.
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 node? It would similar to the doubly linked list implementation in the kernel.
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, bothnextandprevfields ofstruct list_headmay point either to node or to the head. Single type for them is not an advantage, butnecessity.
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 something similar? are there any magic numbers in the beginning of an executable C-program?
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 compile all the c files so that i can make a merged shared library that is accessible through java?
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 ``` Which can still compile without errors, and I check c keywords, 'http' seems not a keyword, what is the reason?
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 functions where the end of the string is. So techinally we can store 9 characters and the \0 to terminate the string.
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. After compiling and running, only the second \t works.
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 b; }; ``` What doesstruct_type[1]actually mean?
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, let's assume that the code is compiled using gcc with debug symbols. Subsidiarily, is the behavior the same in C++ ? Thank you.
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 callingOpenProcess(). Handles themselves do not have ACLs. Provided you havePROCESS_DUP_HANDLEyou can duplicate any valid handle in the process.
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 compile a program consuming this library, the compiler checks the types with the signatures defined in thesomeLib.h, so as long as I useints, everything should compile fine. But what happens when in my compiler'sintis longer or shorter than in the compiler that was used compilesomeLib.lib? Will it be detected during linking? Will it cause runtime errors? Can I safely use thesomeLib.libwithout knowing how it was compiled?
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 HBITMAP representing it that you can select into a source DC and thus blit to the display.
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; return 0; } ``` Is this a proper way to do like this?
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; // Return the stored 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 answered with facts and citations.Closed7 years ago.Improve this question I was looking through a programming textbook and saw a particular header i didn't recognize. Later I looked it up on the internet but I was wondering where the source code of C can be found on a macbook. Is it just in the compiler? (I use gcc) Please help.
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 stored inbso the output would be 7. If on the other hand you inputted4x5, the 4 would be stored inabut thexwould halt reading of further input because it does not match-. Thenbwould have an undefined value and the result of adding a value to it would also be undefined.
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 callingOpenProcess(). Handles themselves do not have ACLs. Provided you havePROCESS_DUP_HANDLEyou can duplicate any valid handle in the process.
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 compile a program consuming this library, the compiler checks the types with the signatures defined in thesomeLib.h, so as long as I useints, everything should compile fine. But what happens when in my compiler'sintis longer or shorter than in the compiler that was used compilesomeLib.lib? Will it be detected during linking? Will it cause runtime errors? Can I safely use thesomeLib.libwithout knowing how it was compiled?
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 HBITMAP representing it that you can select into a source DC and thus blit to the display.
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 string "This". I am using MinGw v 4.9.3 to compile this on Windows10.
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 Validation. To enable%nsupport, see_set_printf_count_output. The default invalid parameter handler aborts your program. Either enable via_set_printf_count_output(1)or compile with-D__USE_MINGW_ANSI_STDIO=1to use it.
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 threads will always read the same [consistent] value from it. You can declare something like: ``` /* Global scope */ sigset_t g_set; ``` And pass it topthread_sigmask(): ``` /* Assuming `g_set` is already properly set at this point and won't be modified in the future */ pthread_sigmask(how, &g_set, NULL); ```
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 callgcc -o myfile myfile.c -lpthread.
-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:How do I link to a library with Code::Blocks?
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? ``` int ffunction(int x, int y) { int z = x % y; return z < 0 ? z + y : 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##_seq, t##_len, t##_rep} ```
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 answer.
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 callgcc -o myfile myfile.c -lpthread.
-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:How do I link to a library with Code::Blocks?
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? ``` int ffunction(int x, int y) { int z = x % y; return z < 0 ? z + y : 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##_seq, t##_len, t##_rep} ```
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 answer.
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: 2236940288 mmap-2: 140503502090240 mmap-1: 3425849344 mmap-2: 140612065181696 mmap-1: 249544704 mmap-2: 139625341366272 ``` mmapworks just fine, but the "addresses" returnedsyscallresult inSegmentation fault. The values fromsyscallseem to be cast to 32 bits or something. What am I doing wrong?
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 very short example: ``` .... real *ptr; real delta_force; for(i<particles;...) { ...some calculations ptr=&FORCE(i,...); //FORCE is a macro returning the current force on a particle *(++ptr) += delta_force; ... } ... ``` How can I interpret*(++ptr)?
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 to just use remove(filename) and ignore the return value? EDIT: By remove, I'm referring tothis
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 wants to knowwhya file was not deleted (seestd::perror).
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 overloading. They are two separate operators. When it comes to#includedirectives the answer is that they are processed by the pre-processor. After the pre-processor step the<and>are gone - the line has been replaced by the entire contents of the include file.
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 it could be one of these also :+,-,*,\,= so that we increment in a loop thenumberOfCharsfor every one of these. so for :a = b + cwe will get3.
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; struct node *next; /* Why this statement ? */ } Node; ```
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 instead of using the multiplication operator. ``` multiply(5, 3) + multiply(9, 6); ```
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 generated and how I could print them out one after another. Unfortunately, I am not very strong in C, and it seems that the compressor handles distances as pointers, and not as ints. Could somebody please tell me if there is a simple way to print out the sequence of tuples as the algorithm runs, and point me to the appropriate location in the code.
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 causing this problem and how do i fix it? Using df shows: ``` $ df Filesystem 1K-blocks Used Available Use% Mounted on C:/Program Files/Git 975996924 171439984 804556940 18% / I: 260614460 219965568 40648892 85% /i ```
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.com/watch?v=3B4hPHZNtNw
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 overloading. They are two separate operators. When it comes to#includedirectives the answer is that they are processed by the pre-processor. After the pre-processor step the<and>are gone - the line has been replaced by the entire contents of the include file.
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 it could be one of these also :+,-,*,\,= so that we increment in a loop thenumberOfCharsfor every one of these. so for :a = b + cwe will get3.
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; struct node *next; /* Why this statement ? */ } Node; ```
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 instead of using the multiplication operator. ``` multiply(5, 3) + multiply(9, 6); ```
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 generated and how I could print them out one after another. Unfortunately, I am not very strong in C, and it seems that the compressor handles distances as pointers, and not as ints. Could somebody please tell me if there is a simple way to print out the sequence of tuples as the algorithm runs, and point me to the appropriate location in the code.
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 causing this problem and how do i fix it? Using df shows: ``` $ df Filesystem 1K-blocks Used Available Use% Mounted on C:/Program Files/Git 975996924 171439984 804556940 18% / I: 260614460 219965568 40648892 85% /i ```
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.com/watch?v=3B4hPHZNtNw
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 slide, it says that: Implement KSM logic from scratch using protocol specification, orCustomize the C reference implementation in the SDK (language, integration) The first sentence tells us that we can implement it from scratch.So, does anyone implement Apple FairPlay Key Security Module in another language rather than C? Thanks.
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; printf("%d %d %d", **pp, *pp[3], pp[0][2]); } ```
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 computed is not used You can remove the dereferencing, it's no use.
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) does not change in the variable when the code is pushed to the ARM embedded board. My goal is to change theAA AAsubstring in theat_ss_dataarray to00 00
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 asDoes public and private have any influence on the memory layout of an object?
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 trying to move forward on standardizing it. Since then, whomever was responsible for that proposal decided not to continue to pursue it.
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 question is why the last\bdoes not have effect on the second word more specifically when they are at the end of the string?
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 least 4096. It will most likely be exactly that. But since it needs a padding of 4080 bytes beforec, the size of the struct is at least 4104, but it must be a multple of 4096, its alignment. So it grows to 8192.
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,*lpOverlappedwill beNULL, andGetLastErrorwill returnERROR_ABANDONED_WAIT_0.
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 ***** \n \n \n"); int k ; for (k = 0; k < 3; k++) { printf("Bonjour Joueur %d :\n", k+1); printf("Nom: "); fgets(Joueur[k].Nom,50,stdin); printf("Votre nom est: %s", &Joueur[k].Nom); printf("\n \n"); } return 0; } ``` == Header.h ``` typedef struct Personne Personne; struct Personne { char Nom[1500]; char Prenom[1500]; int Age; int Tel; double Moy; }; ```
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 declare thecontent_typeinside a method, this works, but I need to have it for global purpose to don't duplicate code
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 output using a regular, singleforloop with afor(i = 0; i < k; ++i)wherekislimit^n(limitto then'th power).
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 buf = {.capacity = BUF_CAPACITY, .head = 0, .tail = 0}; return &buf; } int push(ringBuf_t *buf, uint32_t item) { if (buf->head + 1 == buf->tail) { return -1; } buf->data[buf->head] = item; buf->head = (buf->head + 1) % buf->capacity; return 0; } ```
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 getting evaluated
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. Because on your machineu32will betypedefd overlongandquint32will betypedefd overintand the compilerwill complain. Why does everybody do this, if there is<stdint.h>? Is this some kind of tradition for libraries?
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 memory). On error,(void *) -1is returned, anderrnois set toENOMEM. Now, What's the significance of(void *) -1?What is the exact memory address it points to? (if it does at all)How is it guaranteed that(void *) -1is not a valid address that can be returned bysbrk()on success?
``` (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 alengthof2, the code does not print all 1s. It just prints the following: ``` 7.7486e-304 7.7486e-304 ``` So, what should I do to fix it?
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? Here is the code. ``` #include <stdio.h> int main(void) { int a=5; int k=(a++,++a); printf("%d\n",k); return 0; } ``` The output I get is 7 — why is that?
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 = a++), ++a; ``` and evaluated as ``` k = a++; ++a; ```
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 in the appropriateMakefile.If you use an IDE, you'll need to figure out how to do that in the various settings that IDEs provide.
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 get0001. But we shifted off bits 1 and 2 and so when we do thebitwise AND, aren't we doing it against thethirdbit and not thesecond, wherex = 2? Doesn't this mean that if I want to check if bitxis set, shouldn't I do: ``` bit = (number >> (x - 1)) & 1); ```
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. Both have also constraints like undefined behavioursLinketc. I do not understand what will be the real use. I am even not confident to use them for Division or multiplication.
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 subsequently, the connection is reset, since the data cannot be delivered to the user. By "reset" does it mean that RST is sent to the peer by the local TCP? which in turn means, there won't be a graceful shutdown?
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? Here is the code. ``` #include <stdio.h> int main(void) { int a=5; int k=(a++,++a); printf("%d\n",k); return 0; } ``` The output I get is 7 — why is that?
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 = a++), ++a; ``` and evaluated as ``` k = a++; ++a; ```
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 in the appropriateMakefile.If you use an IDE, you'll need to figure out how to do that in the various settings that IDEs provide.
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 get0001. But we shifted off bits 1 and 2 and so when we do thebitwise AND, aren't we doing it against thethirdbit and not thesecond, wherex = 2? Doesn't this mean that if I want to check if bitxis set, shouldn't I do: ``` bit = (number >> (x - 1)) & 1); ```
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 <stdlib.h> // second time #include <ctype.h> ``` Is this merely an error? Or is there something to it? I ask because the author of the code doesn't seem like someone who makes a lot of mistakes. I wouldn't want to suggest a change in ignorance.
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 ddd with no parameters). I can start program from DDD as usual with Run command from Program menu. I haven't modified any configuration files, and the change happened in the middle of the work, in absence of previous restarts. Then, I have tried to restart, and also to reinstall ddd, but with no success. Gdb works well. I work on Linux Mint 17.3. Any ideas? Thank you!
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("pattern found\n"); } ``` Are there more elegant ways to detect the pattern? My method can be cumbersome if the pattern consists of 10 bytes.
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 message is a pointer to a char array, it must pass them separately.
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 at least 64-bits (practically it is always 64-bits, at least with today's compilers). Was this not the case for ISO C90 or C++98, or is there some other reason not to uselong long? I know about<stdint.h>types likeint64_tand friends, but some not-so-old compilers (e.g. VS2005, and Green Hills ARM 3.5) do not provide<stdint.h>, and I thoughtlong longwould be (at least) 64 bits for those and newer toolchains.
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 <stdlib.h> // second time #include <ctype.h> ``` Is this merely an error? Or is there something to it? I ask because the author of the code doesn't seem like someone who makes a lot of mistakes. I wouldn't want to suggest a change in ignorance.
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 ddd with no parameters). I can start program from DDD as usual with Run command from Program menu. I haven't modified any configuration files, and the change happened in the middle of the work, in absence of previous restarts. Then, I have tried to restart, and also to reinstall ddd, but with no success. Gdb works well. I work on Linux Mint 17.3. Any ideas? Thank you!
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("pattern found\n"); } ``` Are there more elegant ways to detect the pattern? My method can be cumbersome if the pattern consists of 10 bytes.
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 haven't managed to find a solution to this anywhere. Thanks
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_list[100]; int thread_count = 0; ... pthread_create(&thread_list[thread_count++], NULL, thread_function, NULL); ```
...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 will suffice if not.
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 aside for the array.
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 later, it actually calls the method right away. I would like to just create the object for later and not call the method immediately.
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 * v--- element count p = /* no cast needed here */ malloc(sizeof *p * N); if (p == NULL) return Handle_Failure(); for (size_t i=0; i<N; i++) { // do something with p[i] p[i] = 42; } // free when done free(p); ```
``` #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 of float height! What's wrong with my code?
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. ``` double height; scanf("%lf",&height); ```
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 later, it actually calls the method right away. I would like to just create the object for later and not call the method immediately.
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 * v--- element count p = /* no cast needed here */ malloc(sizeof *p * N); if (p == NULL) return Handle_Failure(); for (size_t i=0; i<N; i++) { // do something with p[i] p[i] = 42; } // free when done free(p); ```
``` #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 of float height! What's wrong with my code?
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. ``` double height; scanf("%lf",&height); ```
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) { char *p1 = CrArray1(); strcpy(p1, "Hello, "); char *p2 = CrArray1(); strcat(p2, "World"); char *q1 = CrArray2(); strcpy(q1, "Different String"); printf("p1 is : %s\n", p1); printf("q1 is : %s\n", q1); return 0; } char *CrArray1(void) { static char Array[128]; return Array; } char *CrArray2(void) { static char Array[128]; return Array; } ```
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'are different characters, and'\0'is a string terminator that has a value of0... I think you meant to use'0'(emphasis on the quotation marks).
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 global instance of the above structure in my c file ``` BTDEV_ADDR hsu_addr ``` and calling the function like this ``` hci_acl_connect((unsigned char *)&hsu_addr,&cont_hand); ``` Is typecasting is correct "(unsigned char *)&hsu_addr" ?
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 only want it to take only 2. How would I go about doing this?
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_num; } Message_Header_Type; ``` From the GCC documentation: packedThis attribute, attached to an enum, struct, or union type definition, specified that the minimum required memory be used to represent the type.
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; i++; printf("%d\n",i); } ``` Output: ``` 4bh1@mybox:~/C-fi$ ./test 1 2 3 ```
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 compiler does not reset it value to something as that would be wasted cpu cycles. This is why you can see the value increasing as it is just reusing what was in the memory space.