question
stringlengths
25
894
answer
stringlengths
4
863
I have a client/ server program written i c language, a client can send and receive .txt documents to the server, i wish to Open the file received to visualize it with command nano For example, inside the running process: Something like this: Exec( nano, "file-to-Open.txt") but i dont know how to do do this), can You help me? Sorry For my english Thank's a lot
Try this: ``` execlp("nano", "nano", "file.txt", NULL); ``` Thenanoeditor must be in your path, thefile.txtmust be in the current directory of the running client process, and most importantly, whatever display the editor is going to display on must be accessible, be it the terminal from where the client is run or the appropriate X-Windows display.
Is there a way to make that the entropy of /dev/urandom is and stay uninitialized? My goal is to simulate an initialized or simply uninitialize /dev/urandom. How can I do a such thing? edit: I see my question has been downvoted. I am sure the person who did has a legitimate reason. I have spent time searching the answer online but I didn't find anything.
As /dev/random and urandom are vital for security functions, allowing to tamper them would contradict their purpose. But you can add your own driver, or just replace calls to them with dummies (or use named pipes from a dummy for testing) instead. Note: do not replace the driver on a production system.
I would need to send a pretty large amount (logs) amount of data from multiple processes to one master processes. They are all running independent on the system. What would be the best way to do this? Is interprocess communication a good way to do that or should I use shared memory? Maybe there is a different way I don't know yet. The language used is C on Linux, because I have to implement it in a existing program. How would you accomplish it?
Apart from Inter process communication using pipes/named pipeSee this SO questionand shared memorySee this SO questionandSo questionfor fastest and large size data discussion .(It directs on using shared memory(fast and large) and pipes(easy). You can try using Sockets. Where master listens on a port and all slaves connect to that port and master accepts connection.But this may lead to packeting and resource overhead.
I observed thatrand()library function when it is called just once within a loop, it almost always produces positive numbers. ``` for (i = 0; i < 100; i++) { printf("%d\n", rand()); } ``` But when I add tworand()calls, the numbers generated now have more negative numbers. ``` for (i = 0; i < 100; i++) { printf("%d = %d\n", rand(), (rand() + rand())); } ``` Can someone explain why I am seeing negative numbers in the second case? PS: I initialize the seed before the loop assrand(time(NULL)).
rand()is defined to return an integer between0andRAND_MAX. ``` rand() + rand() ``` could overflow. What you observe is likely a result ofundefined behaviourcaused by integer overflow.
Given a number(int a = 0XABCDE98)I am trying to set theDbit to6. ie after the Bit manipulation the number should be(0XABC6E98). I have written a small C program to do the bit manipulation, but somehow I am not able to see the correct bit change. Please help me in finding what might be missing in the program. ``` #include<stdio.h> int main() { int n = 0xABCDE98; n |= (n & 0X0000) | 0x6000; printf("%x\n", n); return 0; } o/p - abcfe98 ```
In your code ``` n |= (n & 0X0000) | 0x6000; ``` is wrong beacuse of is equal to 0xABCDE98 & 0x0000 = 0and0x0000 | 0x6000 = 0x6000and0xABCDE98 | 0x6000 = 0xABCFDE98 Instead you must write ``` n = (n & 0XFFF0FFF) | 0x6000; ```
I know the individual uses ofSIGPIPEandSIGIGN. What does ``` signal(SIGPIPE, SIG_IGN); ``` exactly do?
``` signal(SIGPIPE, SIG_IGN); ``` simply ignores the signalSIGPIPE. PassingSIG_IGNashandlerignores a given signal (except the signalsSIGKILLandSIGSTOPwhich can't caught or ignored). As an aside, it's generally recommended to usesigaction(2)oversignal(2)assigactionoffers better control and also don't need to "reset" the handler on some systems (which follow the System V signal behaviour).
I am writing a simple application that links tolibxml2on the system. It works for almost all users, but one user reported this error when reading a particular xml file from the web: ``` Unsupported encoding ISO8859-1 ``` This error typically indicates that libxml2 was built--without-iconv. Is there any way I can explicitly test if the libxml2 dynamic library on the system has iconv support?
I can think of two ways to do this: Write a short, simple test program that uses the iconv feature of xml. It should behave differently if it is not present. This is what the GNU configure software does - it tests for features being present by exercising them.This is a hack - find a common iconv symbol present in libxml with iconv but not if iconv is missing. Use a utility likenmto list the symbols in the library file. Or just avoid the issue by packaging a working libxml with your application.
Can the c function pthread_cancel() block or does it always return immediately? My man page states that: The above steps happen asynchronously with respect to the pthread_cancel() call; the return status of pthread_cancel() merely informs the caller whether the cancellation request was successfully queued. Which certainly suggests not. Are there any situations where the call can block? Thanks in advance.
No, the call topthread_cancel()does not block. It merely registers a cancel request. The only situation where it could block is if a thread tried to cancel itself, but that is taken care of in the function implementation:check this link
``` memcpy(a, b, sizeof(a)); ``` v.s. ``` a[0] = b[0]; a[1] = b[1]; ... ``` Suppose thatmemcpyshould have smaller code size and high efficiency, but is there any risk tomemcpyin multi-thread system?
If the buffers are exclusive, meaning that threads are not competing for access to the data involved in the copying, thenmemcpyis perfectly safe to use in multi-threaded environment. The function has no persistent state and no other side-effects besides modifying the target buffer.Also, you can safely perform muti-threaded copyingfroma buffer shared by any number of threads, as long as no thread attempts to change that buffer.But once there's a competition between the threads forwritinginto any shared buffers,memcpyno longer guarantees thread safety, i.e. the operation is not atomic. Aside from what is described in 2, two simultaneousmemcpys operating on the same buffer will interfere with each other and produce unpredictable results.
I have seen many articles explaining how to callC functions from Swift, but I would like to explore the converse (if possible), to callSwift functions from C. I have seen examples illustrating Swift functions in objC, but these do not get me any closer to my goal. Is this task even supported?
The only supported way to call Swift code from C code is to use Objective-C between the two. That's not to say that it's entirely impossible, but someone would have to come up with aNSInvocation-like utility and wrappers for objects that don't have an exact C representation.
I have this piece of code ``` HLOCAL localHandle; char *lpText; localHandle = LocalAlloc(LMEM_MOVEABLE, 40); if(localHandle) { lpText = (char*)LocalLock(localHandle); //Call LocalFree(localHandle) or LocalFree(lpText) ???? } ``` Should I callLocalFree(localHandle);orLocalFree(lpText);?
ThehMemparameter forLocalFreeis documented as: A handle to the local memory object. This handle is returned by either theLocalAllocorLocalReAllocfunction. It is not safe to free memory allocated withGlobalAlloc. So in your sample you need to call: ``` LocalFree(localHandle); ``` Don't forget to callLocalUnlockbefore callingLocalFree, to decrement the reference count. This is mandatory when usingLMEM_MOVEABLE.
I have seen many articles explaining how to callC functions from Swift, but I would like to explore the converse (if possible), to callSwift functions from C. I have seen examples illustrating Swift functions in objC, but these do not get me any closer to my goal. Is this task even supported?
The only supported way to call Swift code from C code is to use Objective-C between the two. That's not to say that it's entirely impossible, but someone would have to come up with aNSInvocation-like utility and wrappers for objects that don't have an exact C representation.
I have this piece of code ``` HLOCAL localHandle; char *lpText; localHandle = LocalAlloc(LMEM_MOVEABLE, 40); if(localHandle) { lpText = (char*)LocalLock(localHandle); //Call LocalFree(localHandle) or LocalFree(lpText) ???? } ``` Should I callLocalFree(localHandle);orLocalFree(lpText);?
ThehMemparameter forLocalFreeis documented as: A handle to the local memory object. This handle is returned by either theLocalAllocorLocalReAllocfunction. It is not safe to free memory allocated withGlobalAlloc. So in your sample you need to call: ``` LocalFree(localHandle); ``` Don't forget to callLocalUnlockbefore callingLocalFree, to decrement the reference count. This is mandatory when usingLMEM_MOVEABLE.
I would like to enable floating point exceptions on some critical code using fpeenableexcept or _MM_SET_EXCEPTION_MASK (on Mac OS X). Is there any case on x86/x86-64 where changing the enabled exceptions will hurt the program performancewhen no error occurs? I am only asking about numerical code after the exception is changed and code which is not throwing any exception.
After some times running my application with the exception enables, I did not encounter any performance regression.
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed8 years ago. In C, is ``` a[i] = a[++i]; ``` equivalent to ``` a[i] = a[i+1]; i++; ``` That is, which side of the assignment is evaluated first and what value ofiis used on the left side? Or is this assignment ambiguous?
In the same sequence point you are using and incrementingi ``` a[i] = a[i++]; ``` which will lead to undefined behavior. ``` a[i] = a[i+1]; i++; ``` is good. And to answer your questionare they same? No they are not !! One if well defined and another is not. Check thisanswer
This question already has answers here:Stack overflow caused by recursive function(6 answers)Closed8 years ago. I tried following example in C++ with visual studio. ``` void egg(); void chicken () { return egg (); } void egg () { return chicken (); } int _tmain(int argc, _TCHAR* argv[]) { chicken(); return 0; } ``` While running I got error like stackoverflow exception. Could any body please explain me why such error came. I was assuming this will go for infinite loop.
Each time yourchicken ()callsegg()andegg()callschicken (), theirreturnaddress are pushed ontothe stack. As the stack is finite memory, you are getting "error likestackoverflow exception". Readthisfor more understanding.
On my computer. When I test the code: ``` int main() { int i=123; return 0; } ``` using ``` g++ -g test.cpp -o test ``` I found when I enter: ``` print &i output: 0x7fffffffe18c print sizeof(&i) output: 8 ``` I was confused, the address of i is 6 byte, whysizeof(&i)==8? Thanks a lot
When you do this, you are getting the address of i ``` print &i output: 0x7fffffffe18c ``` The output show the address number that the variable i is stored, but printf will remove the leading zero, so you could only see0x7fffffffe18cinstead of0x00007fffffffe18c, you could use a debugger to verify it When you call sizeof(&i) ``` print sizeof(&i) output: 8 ``` You getting 8 bytes, because you are getting the sizeof the address and not the variable i size, if you want to get the variable size just do ``` sizeof(i) ```
If I attempt to use the functiongdk_pixbuf_xlib_get_from_drawable, it results in the following linker error: ``` undefined reference to gdk_pixbuf_xlib_get_from_drawable ``` I am compiling it using thegtk+-2.0andlibwnck-1.0pkg-config options, like this: ``` ... `pkg-config gtk+-2.0 libwnck-1.0 --cflags --libs` ``` I have also tried addinggdk-2.0andx11to the pkg-config options, but it still did not work. My code looks roughly like this: ``` wnck_window_get_geometry (window, &xp, &yp, &widthp, &heightp); pixbuf = gdk_pixbuf_xlib_get_from_drawable (pixbuf, gdk_window, NULL, NULL, 0, 0, 0, 0, widthp, heightp); ```
You need to add gdk-pixbuf-xlib-2.0 to your pkg-config checks, and include gdk-pixbuf-xlib.h.
This question already has answers here:Stack overflow caused by recursive function(6 answers)Closed8 years ago. I tried following example in C++ with visual studio. ``` void egg(); void chicken () { return egg (); } void egg () { return chicken (); } int _tmain(int argc, _TCHAR* argv[]) { chicken(); return 0; } ``` While running I got error like stackoverflow exception. Could any body please explain me why such error came. I was assuming this will go for infinite loop.
Each time yourchicken ()callsegg()andegg()callschicken (), theirreturnaddress are pushed ontothe stack. As the stack is finite memory, you are getting "error likestackoverflow exception". Readthisfor more understanding.
On my computer. When I test the code: ``` int main() { int i=123; return 0; } ``` using ``` g++ -g test.cpp -o test ``` I found when I enter: ``` print &i output: 0x7fffffffe18c print sizeof(&i) output: 8 ``` I was confused, the address of i is 6 byte, whysizeof(&i)==8? Thanks a lot
When you do this, you are getting the address of i ``` print &i output: 0x7fffffffe18c ``` The output show the address number that the variable i is stored, but printf will remove the leading zero, so you could only see0x7fffffffe18cinstead of0x00007fffffffe18c, you could use a debugger to verify it When you call sizeof(&i) ``` print sizeof(&i) output: 8 ``` You getting 8 bytes, because you are getting the sizeof the address and not the variable i size, if you want to get the variable size just do ``` sizeof(i) ```
If I attempt to use the functiongdk_pixbuf_xlib_get_from_drawable, it results in the following linker error: ``` undefined reference to gdk_pixbuf_xlib_get_from_drawable ``` I am compiling it using thegtk+-2.0andlibwnck-1.0pkg-config options, like this: ``` ... `pkg-config gtk+-2.0 libwnck-1.0 --cflags --libs` ``` I have also tried addinggdk-2.0andx11to the pkg-config options, but it still did not work. My code looks roughly like this: ``` wnck_window_get_geometry (window, &xp, &yp, &widthp, &heightp); pixbuf = gdk_pixbuf_xlib_get_from_drawable (pixbuf, gdk_window, NULL, NULL, 0, 0, 0, 0, widthp, heightp); ```
You need to add gdk-pixbuf-xlib-2.0 to your pkg-config checks, and include gdk-pixbuf-xlib.h.
I wanted to try to get only the four bits from the right in a byte by using only bit shift operations but it sometimes worked and sometimes not, but I don't understand why. Here's an example: ``` unsigned char b = foo; //say foo is 1000 1010 unsigned char temp=0u; temp |= ((b << 4) >> 4);//I want this to be 00001010 ``` PS: I know I can use amask=Fand dotemp =(mask&=b).
Shift operator only only works on integral types. Using<<causes implicit integral promotion, type castingbto anintand "protecting" the higher bits. To solve, usetemp = ((unsigned char)(b << 4)) >> 4;
I have a 16 bit address 0-15, I need to check at value of bit corresponding to their position in C for example at 15 place i have 1, 14 has 0, and soo on! |1|0|0|0|1|0|1|0|1|1|1|1|1|0|1|0| I was thinking to create 16 new addresses with all zero and the position i am looking
Use a macro similar to this: ``` #define CHECK_BIT(x, i) ( ((x) & (1 << (i)) != 0 ) ) ``` CHECK_BIT(x, i)will returntrueif the i'th bit ofxis one, false otherwise.
If I wanted to generate code that looks like this: ``` CALL FUNC0 CALL FUNC1 CALL FUNC2 CALL FUNC3 CALL FUNC4 CALL FUNC5 ... CALL FUNC19 ``` How can I use a repeat block generate such code, using something similar to the code below: ``` .equ SYMBOL, 0 .rept 20 CALL FUNC(SMYBOL) .equ SYMBOL, (SYMBOL+1) .endr ``` Macros are fine too. I'd like to know how to do this in C as well.
You can use a macro do this: ``` .altmacro .macro call_funcs count .if \count call_funcs %(count-1) .endif CALL FUNC\count .endm call_funcs 20 ``` The.altmacrodirective enables the use of%to evaluatecount - 1before passing recursively as a macro argument. Otherwise you getCALL FUNC20-1-1-1-1which not what you want. As far as I know there's no way to what you want in C. For that I would write a program that generates the C code you need.
I wrote this code that reads from a .txt a string and settles it in a char *, but it gives me error that the variable "string" is not initialized, even if i initialized it inside the fscanf, can u tell me where i wrong? Thanks! ``` char *string; FILE *fp = fopen("words.txt", "r"); fscanf(fp, "%s", string); ```
That's normal, you didn't allocate string. C needs you to allocate it in memory before you use it. Also you will have to know its size. In your code, string points to nowhere into memory so it doesn't exist (to be exact it points to somewhere you have a lot of chance that you can't access it) See how malloc works.
I want to create an array of 10 × 10, which contains'.'for each element. So I write as : ``` int A[10][10]={ '.','.','.','.', ``` (wait a minute I have to write 100 full stops and 100 commas) ``` '.','.','.'} ``` Another method is to write'.',10 times and then copy paste it 10 times, but still this takes time and I don't think this is the smartest method. Is there a smarter method? I don't want to write so long full stops.
The only feasible way toinitializean array like this, is (unfortunately) by using a flood of macros: ``` #define ONE_DOT '.', #define TWO_DOTS ONE_DOT ONE_DOT #define FIVE_DOTS TWO_DOTS TWO_DOTS ONE_DOT #define TEN_DOTS { FIVE_DOTS FIVE_DOTS }, #define TWENTY_DOTS TEN_DOTS TEN_DOTS #define FIFTY_DOTS TWENTY_DOTS TWENTY_DOTS TEN_DOTS #define ONE_HUNDRED_DOTS FIFTY_DOTS FIFTY_DOTS int A[10][10] = { ONE_HUNDRED_DOTS }; ```
For example, we have the following simple code: ``` #include "stdio.h" int main() { int* pointer_to_check; printf("%x\n", pointer_to_check); return 0; } ``` With gcc, we will get zero at output (as for me, normal behavior, because pointer isn't associated with memory), but clang gives us a real address, which can be accessed without "segmentation fault". I have two questions: What is the normal behavior according to the C standard (and C++)?Why does this happen?
pointer_to_checkto check is uninitialized. It points to some "random" location. Accessing uninitialized variables leads toUndefined Behaviorwhich means that anything can happen. Also, pointers should be printed using the%pformat specifier. with gcc code, we will get zero at output Anything can be the output. It is Undefined. You shouldn't rely on this behavior.
``` int main(){ // Comment the next line, Garbage value is printed. However, this shows an integer value. int x=32; printf("%d"); return 0; } ``` Any reason for this behaviour, or is it random??
You toldprintf()how toprintsomething (the format specifier%d), but you did not tellprintf()whatto print. To elaborate, you forgot to supply the required argument for the supplied format specifier%d. Cstandard says, if there are insufficient argument for supplied format specifier, thebehaviour is undefined. FWIW, just specifying the format specifier won't magically consider the argument for it. You need to write something like ``` printf("%d", x); ``` to print the value ofx.
``` char input[1000]; ``` I want to copy input into a dynamically allocated character array, how do I approach this problem. So far I have used strncpy, but get lots of errors.
Are you looking for something like this: ``` #include <stdlib.h> #include <stdio.h> #include <string.h> int main() { int i; char input[1000] = "Sample string"; char *in = malloc(1000 * sizeof(char)); // use dynamic number instead of 1000 strcpy(in, input); for (i = 0; i < 5; ++i) { // intentionally printing the first 5 character printf("%c", in[i]); } } ``` The output is: Sampl Edit:InC++the cast is required formalloc, so I write: ``` (char *)malloc(1000 * sizeof(char)) ``` But inC,never cast the result of malloc().
I've foundthis questionwhich is basically asking the same, but got no real answer. Where is themake's config file / database file where it remembers the file timestamps, so it can tell what changed? I checked and there's no.makeor similar in my project, nor in the home directory. Or does it somehow store the information inside the files themselves, perhaps by modifying the timestamps? (That sounds fishy though)
There is no such "database". The program simply compare the filesystems modification and creation timestamps of source and target files. Lets say you have the following rule: ``` some_target: some_source_1 some_source_2 ``` Then if the modified timestamp of eithersome_source_1orsome_source_2is later than the modification/creation time ofsome_targetthen the rule will activate and the target will be rebuilt.
If i have N x N 2 dimensional array and the name is a. ``` int a[N][N]; ``` When i Insert any value in any array, for example,a[N-1][N-1]=1, how much time does it take? O(N^2)orO(1)?
You are not inserting, right? You are assigning, direct to a specific address and you don't need to figure out the right position before hand. That means you don't need to do any loop, don't need to go through any computing before find the position and assign, and the memory is already allocated. so it's O(1), constant doesn't matter the input.
This is my code: ``` #include <stdlib.h> #include <stdio.h> int sum(int,int); int sum(int x, int size) { int sum = 0; printf("%p\n", &x); printf("%p\n", &size); printf("%p\n", &sum); sum(x,size); return 0; } int main() { sum(2,4); return 0; } ``` And the error I am getting is: ``` hello.c:11:5: error: called object type 'int' is not a function or function pointer sum(x,size); ~~~^ ```
You changed the meaning ofsumhere: ``` int sum = 0; ``` From now on, in the scope in which it was declared,sumis anint, and this becomes nonsense: ``` sum(x,size); /* Wat? sum is an int!!! */ ``` Don't do that, and your code will compile. Once it compiles, you can worry about stopping the recursion.
I have a string like"03FE"holding hexadecimal values. I need to split this string in two parts, and convert each individual part to the equivalent hexadecimal. That is, I need0x03in one variable and0xFEin another variable. For example, if I didn't have to split the string, this is how I would have done it: ``` char *p; uint32_t uv=0; uv=strtoul(&string_to_convert, &p, 16); ``` How shall I proceed if I needed to split the string?
Split the output ofstrtoulinstead: ``` uint8_t uv_hi = uv >> 8; uint8_t uv_lo = uv & 0xFF; ```
What I am trying to do is check if the word entered by the user has first five alphabetical letters and if it has, I need to copy those letters to another array.But it gives me an error saying "passing argument 1 of strcpy makes pointer from integer without cast[enabled by default]". ``` char s1[100]; char a1[100]; char alpha[5]={'a','b','c','d','e'}; int i,j,k=0; printf("Enter a word"); fgets(s1,100,stdin); for(i=0;i<strlen(s1);i++) { for(j=0;j<5;j++) { if(s1[i]==alpha[j]) { strcpy(a1[k],s1[i]); k++; } } } ``` Need help to figure out what is wrong with this
strcpyhas two input parameterschar *. You can't use it for two characters. If you want to copy one character from one array to another then you need to use= operatorasa1[k] = s1[i]
I am understanding recursion and so I tried writing reverse a linked list program. I have written the below function but it says segmentation error (core dumped). ``` void reverse(){ if (head -> next == NULL){ return; } reverse (head -> next); struct node *q = (struct node*) malloc (sizeof(struct node)); q = head -> next; q -> next = head; head -> next = NULL; } ``` Please can someone guide me. Thank you.
Shouldn't reverse take an argument? And please be aware that you cannot change a pointer in a function and have that be a lasting change. That is, in a C function, the only lasting changes are those that use *var = something.
I want to use enumeration type in C. I know how to use them but I have a question. I have an example like this ``` enum S { A,B,C,G }; ``` I know this works but can i do something like this? ``` enum S {^,*,/,%}; ``` Thanks for your time.
No. You can only use alphanumeric characters and underscores in identifiers (variable, function, and type names) in C. And the identifier cannot start with a number. Also, you can't use certain reserved keywords. http://www.cprogrammingexpert.com/C/Tutorial/fundamentals/identifiers.aspx(link broken) UPDATE: Newer link that's not broken:https://www.w3schools.in/c-programming/identifiers
This question already has answers here:Simple C scanf does not work? [duplicate](5 answers)Closed8 years ago. I need to get words from user which contains space as I expressed at title with struct statement. For example : ``` #include <stdio.h> struct knowledge { char name[30]; }person; int main() { scanf("%s",person.name); printf("\n\n%s",person.name); } ``` When I run this program and enter a sentence like "sentence" there is no problem. It show me again "sentence". However, when I enter "sentence aaa" it shows me just first word ("sentence"). What is the matter here? Why it doesn't show me all ("sentence aaa") I entered?
Instead ofscanf()use ``` fgets(person.name,sizeof(person.name),stdin); ``` It is always a bad idea to usescanf()to read strings. The best option is to usefgets()using which you avoid buffer overflows. PS:fgets()comes with a newline character
I am confused about this example: ``` typedef int32_t voltage_dc_estimate_t[1]; ``` Everything is OK but that[1]at the end of the type definition confuse me. Could someone please help me to understand that situation?
[1]means an array of1element. voltage_dc_estimate_tis a type of an array of1element of typeint32_t.
I'm trying to use #ifndef as below. ``` #ifndef MACRO1 || #ifndef MACRO2 .... #endif ``` I already tried: ``` #ifndef (MACRO1 || MACRO2) .. #endif ``` But for both cases am getting below error error: extra tokens at end of #ifndef directive
Use the#ifpreprocessor directive instead: ``` #if !defined(MACRO1) || !defined(MACRO2) ```
I am try to create tui via ncurses. And I have same problem. There are two fields: ``` Name _______ Password _______ ``` How to implement backspace-support in each field ? And how to use '*' to show each character in password-field ? (Now I usefield_opts_off(field[1], O_PUBLIC);and it doesn't show characters in password-field, only move cursor). Thank you.
There is no tutorial for the forms package that I recall. However, the ncurses test-programs (which are available separately asncurses-examples) contains a programdemo_formswhich does implement deletion by maintaining the edited field contents as a hidden field buffer, and decrementing its length in the case forREQ_DEL_CHAR. Here is a screenshot of the program: Regarding the "non-ncurses" suggestion:dialogisa curses/ncurses application, and has no particular dependency uponbash.
``` int arrSize = 10; double* arr = new double [arrSize]; for(int i = 0; i < arrSize; i++){ arr[i] = i; } for(int i = 0; i < arrSize; i++){ printf("%d", arr[i]); //std::cout<<arr[i]; } ``` Here printf()prints 0000000000.coutprints 0123456789. Why ?
Using a wrong format specifier for any particular argument inprintf()invokesundefined behaviour. arris adoublearray, hencearr[i]produces adoubletype value. you need%fformat specifier to print that. If you use%dto print adouble, your program faces UB and the result cannot be justified, in can beanything. OTOH, the<<used withcoutis an overloaded operator which canadaptbased on the type of the supplied variable. So, it prints the output as expected.
``` #include<stdio.h> int main() { printf("%d",EOF); } ``` generates -1 which is totally fine, but ``` #include<stdio.h> int main() { printf("%f",EOF); } ``` produces 0.000 . How can someone explain this when the expected output is -1.000?
Using a wrong format specifier for any particular argument inprintf()invokesundefined behaviour. EOFis of typeint. You can only use%dfor aninttype variable. FWIW, if you want a floating point representation of anint, you have tocastthe variable (but I personally recommend to avoid this) ``` printf("%f",(float)EOF); ```
I want to use the clang front-end to convert mips.c to mips.ll which is a llvm IR. So I use the command:clang -cc1 O3 mips.c -emit-llvm. A fatal error occurs: 'stdio.h'(which is included in mips.c) file not found. Then I change the command as following:clang -Xclang -cc1 O3 mips.c -emit-llvm. Another error occurs: -emit-llvm cannot be used when linking How can I solve the problem?
As written in the error message, you can only compile when emitting LLVM IR, not link. Either add-cfor the bitcode or-Sfor the readable form to your command line: ``` clang -Xclang -cc1 -O3 mips.c -emit-llvm -S ```
Let's say I have ``` const uint16_t n = 0x0001; ``` Then can I cast like this? ``` const jint j = (jint) n; ``` Without worrying about endianness of the native platform? Supplement I have a function changes a value into an char array. ``` char * value_to_array(void * value, const size_t size) { char * array = malloc(size); if (array != NULL) { memcpy(array, value, size); } return array; } ``` Now I should care about the endianness, right? What about the above simple cast?
Then can I cast like this? Yes.JNI primitive types are machine-dependent. Your second example preserves whatever endian-ness was present in the source, which you haven't specified.
Can i write assignment operator in a cascaded manner.Following are two statements how can i write them ``` total_marks/=1000; total_marks*=100; ``` Can we do something like but where we place 100 ``` total_marks*=total_marks/=1000; ```
No. The result of a/=or*=operator will not return an lvalue, and therefore cannot be used to the left of another assignment. What's wrong with the simple, obvious, readable: ``` total_marks = (total_marks / 1000) * 100; ```
I would like to generate compile time error for X-macro for allX(a, b)wherea > b ``` /* X(a, b) */ #define LIST \ X(10, 20) \ X(5, 20) \ X(30, 20) \ X(1, 20) ``` So, generate error forX(30, 20) Is this possible in C? EDIT: example usageFor me, left number is for example sizeof of some large struct and right number is fixed space to store this struct. If the struct is bigger then available space, I need compiler to generate error. ``` //e.g. X(sizeof(struct conf), 2*PAGE) ```
Yes, here's a proof of concept: ``` #pragma push_macro("X") #undef X #define X(a,b) typedef int x[(a>b)?-1:1]; LIST #pragma pop_macro("X") ``` So, we defineXto define a type of array of ints, with either -1 or 1, depending whetherais greater thanb. If it is, the array of -1 elements will cause an error. If using C11, the typedef line can be done usingstatic_assert(a<=b)fromassert.h
I can't figure out what seems to be the problem that I get a segmentation fault from this: ``` #include <stdio.h> #include <stdlib.h> #include <cstring> void alloc(unsigned char *data) { data = (unsigned char *) malloc(20); memset(data, 0, 20); } void main() { unsigned char *data = NULL; int i; alloc(data); for (i = 0; i < 20; i++) { data[i] = i; printf("%d ", *(data + i)); } free(data); } ``` Unsigned char is 1 byte so the loop through 20 should be correct
``` void alloc(unsigned char *data) { data = (unsigned char *) malloc(20); memset(data, 0, 20); } ``` modifies a localcopyof your pointer. You could pass it by reference to make your example work: ``` void alloc(unsigned char *&data) { data = (unsigned char *) malloc(20); memset(data, 0, 20); } ```
This question already has answers here:What is printf's behaviour when printing an int as float?(3 answers)Closed8 years ago. I'm usinggccto compile this: ``` int a=1; printf("%d\n",a); printf("%f\n",a); printf("%f\n",(float)a); ``` I get: 10.0000001.000000 Why does the implicit conversion give a wrong output?
There is no conversion. printf is not a function that accepts a float. It is a function that accepts an argument list that could be of any type. The compiler assumes that a float was given and you are seeing basically undefined behaviour. There is no mechanism that will parse your input string and then apply custom conversion on each parameter. You should be very careful with what you pass to printf cause exploits can be opened this way.
I am programmingATmega16and I chose that controller in device manager(atmel studio 6.2) but the registers don't match with the registers in the datasheet for ATmega16. I am using ICE 3 and I tried with the simulator but it is the same result. RegisterUCSRCis different, from some other controller and can't write in it, even though I setMSBtoone.
according todatasheetof ATMEGA16, it is not required to setMSBofUCSRCas its initial value is1. When you are working with UART you need to make sure that, You are setting properUBRRLandUBRRH, according to controller clock using formula as below:FOSC/16/BAUD-1EnableRXENandTXENfromUCSRBSet the proper bits inUCSRCaccording to your requirement ofstop bitandparity bit Please refer following image :
I have: ``` const char *ptr = "int"; ``` If I have to declare usingptr: ``` int a; ``` ptrcan point to anything arbitrarychar,string,<anythihg>. I have to delcare a variable of that type whatptris pointing at. Is it possible?
No. C++ is not an interpreted language."int"has a meaning to the compiler, but at runtime there's nothing which understands"int".
This question already has answers here:Casting integer to function pointer in signal code - why does this work?(3 answers)Closed8 years ago. I just found this. ``` // /usr/include/sys/signal.h // OS X #define SIG_ERR ((void (*)(int))-1) ``` What does((void (*)(int))-1)part mean? Is it different to ``` #define SIG_ERR -1 ``` ?
This is cast to a function-pointer: ``` ((type) value) ``` Where type isvoid (*)(int)which is pointer to function accepting oneintargument and returningvoid, which is actually is a signature of a signal handler: ``` typedef void (*sighandler_t)(int); ``` You may decode such types withcdecltool or web-site:http://cdecl.org/
This question already has answers here:Case Insensitive String Comparison in C(12 answers)Closed8 years ago. I want to do a case-insensitive string comparison. What would be the easiest way to accomplish that? I have the below code which performs a case-sensitive operation. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { char *str1 = "String"; char *str2 = "STRING"; if (strncmp(str1, str2, 100) != 0) { printf("=("); exit(EXIT_FAILURE); } return 0; } ```
If you can afford deviating a little from strictCstandard, you can make use ofstrcasecmp(). It is a POSIX API. Otherwise, you always have the option to convert the strings to a certain case (UPPER or lower) and then perform the normal comparison usingstrcmp().
I am thinking about a way to create a matrix of pointers in C. Creating a matrix is easy as follow: ``` struct foo **m = malloc(n * sizeof *m); //loop to alocate each column now ``` right? But I don't need this. When I dom[i][j], the pointer is dereferenced. As I see, the only way to do this is having a structure to hold the pointer I need (because I have to access the same pointer from several indexes inm). ``` struct foo { struct bar *p; }; ... struct foo **m = ... ``` Is there any other solution for doing this?
The best solution indeed is the second structure, although you can use a three star poitnerstruct foo ***, it's normally not a good solution, since you can always havestructs to give morestructureto your data, and make your code less error prone.
This question already has answers here:What is printf's behaviour when printing an int as float?(3 answers)Closed8 years ago. I'm usinggccto compile this: ``` int a=1; printf("%d\n",a); printf("%f\n",a); printf("%f\n",(float)a); ``` I get: 10.0000001.000000 Why does the implicit conversion give a wrong output?
There is no conversion. printf is not a function that accepts a float. It is a function that accepts an argument list that could be of any type. The compiler assumes that a float was given and you are seeing basically undefined behaviour. There is no mechanism that will parse your input string and then apply custom conversion on each parameter. You should be very careful with what you pass to printf cause exploits can be opened this way.
I am programmingATmega16and I chose that controller in device manager(atmel studio 6.2) but the registers don't match with the registers in the datasheet for ATmega16. I am using ICE 3 and I tried with the simulator but it is the same result. RegisterUCSRCis different, from some other controller and can't write in it, even though I setMSBtoone.
according todatasheetof ATMEGA16, it is not required to setMSBofUCSRCas its initial value is1. When you are working with UART you need to make sure that, You are setting properUBRRLandUBRRH, according to controller clock using formula as below:FOSC/16/BAUD-1EnableRXENandTXENfromUCSRBSet the proper bits inUCSRCaccording to your requirement ofstop bitandparity bit Please refer following image :
I have: ``` const char *ptr = "int"; ``` If I have to declare usingptr: ``` int a; ``` ptrcan point to anything arbitrarychar,string,<anythihg>. I have to delcare a variable of that type whatptris pointing at. Is it possible?
No. C++ is not an interpreted language."int"has a meaning to the compiler, but at runtime there's nothing which understands"int".
This question already has answers here:Casting integer to function pointer in signal code - why does this work?(3 answers)Closed8 years ago. I just found this. ``` // /usr/include/sys/signal.h // OS X #define SIG_ERR ((void (*)(int))-1) ``` What does((void (*)(int))-1)part mean? Is it different to ``` #define SIG_ERR -1 ``` ?
This is cast to a function-pointer: ``` ((type) value) ``` Where type isvoid (*)(int)which is pointer to function accepting oneintargument and returningvoid, which is actually is a signature of a signal handler: ``` typedef void (*sighandler_t)(int); ``` You may decode such types withcdecltool or web-site:http://cdecl.org/
This question already has answers here:Case Insensitive String Comparison in C(12 answers)Closed8 years ago. I want to do a case-insensitive string comparison. What would be the easiest way to accomplish that? I have the below code which performs a case-sensitive operation. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { char *str1 = "String"; char *str2 = "STRING"; if (strncmp(str1, str2, 100) != 0) { printf("=("); exit(EXIT_FAILURE); } return 0; } ```
If you can afford deviating a little from strictCstandard, you can make use ofstrcasecmp(). It is a POSIX API. Otherwise, you always have the option to convert the strings to a certain case (UPPER or lower) and then perform the normal comparison usingstrcmp().
I am thinking about a way to create a matrix of pointers in C. Creating a matrix is easy as follow: ``` struct foo **m = malloc(n * sizeof *m); //loop to alocate each column now ``` right? But I don't need this. When I dom[i][j], the pointer is dereferenced. As I see, the only way to do this is having a structure to hold the pointer I need (because I have to access the same pointer from several indexes inm). ``` struct foo { struct bar *p; }; ... struct foo **m = ... ``` Is there any other solution for doing this?
The best solution indeed is the second structure, although you can use a three star poitnerstruct foo ***, it's normally not a good solution, since you can always havestructs to give morestructureto your data, and make your code less error prone.
I have: ``` const char *ptr = "int"; ``` If I have to declare usingptr: ``` int a; ``` ptrcan point to anything arbitrarychar,string,<anythihg>. I have to delcare a variable of that type whatptris pointing at. Is it possible?
No. C++ is not an interpreted language."int"has a meaning to the compiler, but at runtime there's nothing which understands"int".
This question already has answers here:Casting integer to function pointer in signal code - why does this work?(3 answers)Closed8 years ago. I just found this. ``` // /usr/include/sys/signal.h // OS X #define SIG_ERR ((void (*)(int))-1) ``` What does((void (*)(int))-1)part mean? Is it different to ``` #define SIG_ERR -1 ``` ?
This is cast to a function-pointer: ``` ((type) value) ``` Where type isvoid (*)(int)which is pointer to function accepting oneintargument and returningvoid, which is actually is a signature of a signal handler: ``` typedef void (*sighandler_t)(int); ``` You may decode such types withcdecltool or web-site:http://cdecl.org/
This question already has answers here:Case Insensitive String Comparison in C(12 answers)Closed8 years ago. I want to do a case-insensitive string comparison. What would be the easiest way to accomplish that? I have the below code which performs a case-sensitive operation. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { char *str1 = "String"; char *str2 = "STRING"; if (strncmp(str1, str2, 100) != 0) { printf("=("); exit(EXIT_FAILURE); } return 0; } ```
If you can afford deviating a little from strictCstandard, you can make use ofstrcasecmp(). It is a POSIX API. Otherwise, you always have the option to convert the strings to a certain case (UPPER or lower) and then perform the normal comparison usingstrcmp().
I am thinking about a way to create a matrix of pointers in C. Creating a matrix is easy as follow: ``` struct foo **m = malloc(n * sizeof *m); //loop to alocate each column now ``` right? But I don't need this. When I dom[i][j], the pointer is dereferenced. As I see, the only way to do this is having a structure to hold the pointer I need (because I have to access the same pointer from several indexes inm). ``` struct foo { struct bar *p; }; ... struct foo **m = ... ``` Is there any other solution for doing this?
The best solution indeed is the second structure, although you can use a three star poitnerstruct foo ***, it's normally not a good solution, since you can always havestructs to give morestructureto your data, and make your code less error prone.
I try to uselea rax, [rip]in acprogram. My program is following: ``` ... asm volatile ("lea %%rax, %[rip]" :); ... ``` However, the program does not compile, throwing an error:undefined name operand. My platform is Ubuntu 1404 on a x86-64 architecture (as virtual machine).
In order to uselea rax, [rip]in inline assembly with GCC you need to convert it to AT&T syntax and the quote it correctly so the % characters aren't interpreted as operand substitutions. So for example: ``` asm volatile ("lea (%%rip),%%rax" ::: "rax"); ``` Note that since this doesn't actually do anything useful, you have no access to the value stored in RAX in your C code, you should specify an output operand: ``` long long ip; asm ("lea (%%rip),%0" : "=r" (ip)); ``` This will let you access the value through the variableip.
I have been reading C for Dummies book, and there was this example where I can edit my previous source code and then save it to a different name. But when I run the code, it ran the previous code. I only made some small changes. How do I run the new code on visual studio 2013? I always keep ending up creating a new project, is there a solution to this?
you have many options , one option I prefer is : 1-Make a duplicate of the file you want to edit ; you can make this by copying the code and pasting it into a new file with a different name. 2-Make the changes you want to do on the new file. 3-Exclude the first file from build by right click , properties and then exclude from build. you are now having the original copy of the file excluded from build , and you have an edited version for it . Also: Don't forget to make backup copies of your edited files occasionally ,
I want to copy certain number of bits from a variable to certain position in another variable Example: I have 8 bit of data. I want to extract higher 4 bits of this byte and transfer them to a 32 bit data variable from bit position 19. How best this can be accomplished? I tried following, but does not seem to be working. instead of 19, I should be able to copy to even from zero position. ``` int bitPos=19; // Position where the extracted data needs to be copied int var1; //32 bit data unsigned char testByte; testByte&=0xF0; // Lower nibbles not needed testByte=testByte>>4; // Get only higher nibble var1|=testByte<<bitPos; ```
I tried to run your code, it seems to be working. For testbyte = 64, I got var1 = 2097152. May be int is not 32 bit for your platform, I can't think of any other reason.
``` int main() { double inf = INFINITY; double pi = acos(-1.0); printf("[1]: %f %f\n", atan(inf) / pi, atan(-inf) / pi); printf("[2]: %f %f\n", tan(inf) / pi, tan(-inf) / pi); return 0; } ``` outputs ``` [1]: 0.500000 -0.500000 [2]: -nan -nan ``` Is such behaviour defined by the standard? Is[2]undefined behaviour? unspecified? I want to be sure at least[1]is a guaranteed result.
Both are well defined behaviour. Quoting fromhttp://en.cppreference.com tanIf the argument is ±0, it is returned unmodified.If the argument is ±∞, NaN is returned and FE_INVALID is raised.If the argument is NaN, NaN is returned.atanIf the argument is ±0, it is returned unmodified.If the argument is +∞, +π/2 is returned.If the argument is -∞, -π/2 is returned.If the argument is NaN, NaN is returned.
When I try to convert string_1="20001" using the code below, I get the array: string_1[0]=2 and string_1[1]=0. what is the reason behind that ? when it's "20125" it's okay but when it's more than one zero it's not okay. ``` for(j=0;j<strlen(string_1);j++) { string_1[j]=(string_1[j]-8)%10; } ``` What I expect to get is :string_1[0]=2 , string_1[1]=0 , string_1[3]=0 ,string_1[3]=0 and string_1[4]=1.
You are modifying the string in the loop, which means the condition no longer will work as you callstrlen(string_1)every iteration (remember thatstrlenlooks for the string termination'\0'which is equal to zero to find the end). Either get the length once before and put it in a variable you use in the condition, or use another array for the destination.
I was given a unix prgramming project (with of cours a use of signal handling and fork()) but i have some issues with my ubuntu and i prefer to work on windows. So is there a solution ? I installed Cygwin but i don't think it will be enough to compile and execute the files like in Linux.
Just do the project in Ubuntu. You're going to have a hard enough time learning about signals and process handling without having to worry about various differences between Cygwin and actual unix/linux. Another option is to install virtualbox and run Ubuntu within that. There should be no differences there.https://www.virtualbox.org/wiki/Downloads
I'm trying to get libusb to work withepollinstead ofpoll, as I'm already using epoll in an application that needs scalability and will only be running on Linux. I'm wondering if theeventsflags returned bylibusb_get_pollfds, which are intended for poll, are compatible with epoll. Can thePOLLINflag, for example, be registered withepolland achieve the same behavior as theEPOLLINflag, or do I need to map these event flags to their corresponding epoll version?
Can thePOLLINflag, for example, be registered withepolland achieve the same behavior as theEPOLLINflag, or do I need to map these event flags to their corresponding epoll version? Thisansweris telling. Excerpt: The most glaring problem withepolldocumentation is its failure to state in "bold caps" thatepollevents, are, in fact, fully identical topoll(2) events.
When I tried below code I got strange results.I am trying to change value of constant by using the pointers.But when I output the results pointer value and the original variable variable value its giving two different values.Can anyone explain what exactly happens when explicit conversion take place? ``` int main() { int *p ; const int a = 20; p=(int *)&a; *p = *p +10; cout<<"p is"<<*p<<"\na is"<<a; } ``` output: p is 30 a is 20
Both C and C++ say that any attempt to modify an object declared with theconstqualifier results in undefined behavior. So asais object is const qualified, the*p = *p +10;statement invokes undefined behavior.
I have a function which has a function pointer input. I can easily give function names to it as input. But I wonder if it's possible to define a function as input. For example I have a function like this; ``` void exampleFunction ( void (*functionPointer)( void ) ) { codes ... } ``` Can I give an input like this inside the brackets? For example; ``` exampleFunction( void helloFunction ( void ) { printf("Hello"); } ); ``` It gives compilation error like this but is there any other ways to do it?
This is impossible in C. In C++, you can use a lambda-expression: ``` exampleFunction([](){ std::cout << "Hello"; }); ```
I have this struct: ``` typedef struct { int start; int end; char board[10][10]; } move; ``` when I try initializing it this way: ``` char new_board[10][10] move struct new_move = {0, 0, new_board} ``` I get this error: warning C4047: 'initializing' : 'char' differs in levels of indirection from 'char (*)[10]' any suggestions?
If you want to initialize the array by zeroes then you can write simply ``` move new_move = { 0 }; ``` If you want that the structure array would contain values of arraychar new_board[10][10]then you have to copy its element in the structure array. for example ``` char new_board[10][10] = { /* some initializers */ }; move new_move = { 0 }; memcpy( new_move.board, new_board, sizeof( new_board ) ); ``` Ifboardis an array of strings then you could also to copy using a loop each string in the structure array using standard C functionstrcpy.
I know how to find Big O for "for loops" and nested "for loops", but what happens when we have two for loops, not nested but two separate for loops in the same function.
It just gets added. See for e.g. : ``` for(i=0;i<n;i++) //statements for(i=0;i<m;i++) //statements ``` So the total complexity is O(m+n). lets say m=3n then its O(4n) which is O(n) only . let m = n^2 then its O(n^2+n) which is O(n^2)
I need to know if i want to make an array that every element of the array is a pointer to a linked list and pass the array to a function, the function isvoidbecause I need to change the array ``` typedef struct n{ char *S; int num; }list; int (main){ list *Array[50]; return 0; } ``` should the function bevoid changeArray(list A[]);orvoid changeArray(list *A[]);orvoid changeArray(list **A[]);
The function could be eithervoid changeArray(list *A[])orvoid changeArray(list **A). Both signatures would accept an array of pointers, and let you change elements of that array: ``` void changeArray(list *A[]) { ... A[0] = malloc(list); } ```
For Embedded systems where the program runs independently on amicro-controller: Are the programs always static linked ? or in certain occasions it may be dynamic linked ?
FromWikipedia: a dynamic linker is the part of an operating system that loads and links the shared libraries needed by an executable when it is executed (at "run time"), by copying the content of libraries from persistent storage to RAM, and filling jump tables and relocating pointers. So it implies that dynamic linking is possible only if:1) You have a some kind of OS2) You have some kind of persistent storage / file system. On a bare-metal micros it is usually not the case.
I am coding a raytracer engine in C using X11 on a Linux. I would like to add a screenshot feature but I can't use any other lib than the standard X11. Is there a "simple" way to do that, or do I have to create a bmp file myself from the pixels I have?
You will manually have to get color values of all the pixels and then convert it to a format of your choice. AFAIK, there is no "simple" way to do it. You can check with this question here:How do take a screenshot correctly with xlib?
In my code: ``` #include <stdio.h> #include <stdlib.h> #include <math.h> #include <ctype.h> void flushstdin() { int c; while((c = getchar()) != '\n' && c != EOF); int main () { float a, b, c; float s=0, ar1=0, ar2=0; printf("Inform the value of size A."); while(scanf("%f",&a) != 1 || a <= 0){ printf("Invalid value!"); ``` What does "while(scanf("%f",&a) != 1 || a <=0){" means?
Well, scanf returns either the number of arguments matched in the given pattern (the %f part) read, or a -1 if an EOF was encountered (meaning end of input). Then a <= 0 should be somewhat self explanatory. These two combined this code will result in an input loop until either the user enters a value greater than 0 or nothing at all. For more information on scanf, check out the docs:http://www.cplusplus.com/reference/cstdio/scanf/
The C code is like this: ``` #include <stdio.h> typedef unsigned char BYTE; int main(void) { unsigned int num, *p; p=&num; num=0; *(BYTE *)p=0xff; } ``` But I do not understand the meaning inside the main function. Can anybody help?
numis anunsigned intpis a pointer to that same int.(BYTE*)pmeans"pretend its really a pointer to a byte instead".*(BYTE*)p =means"Go set that byte to be the value on the RHS."the value on the RHS is0xFF. Result: num is a 4-byte integer.One byte of that int will be set to0xFF(it could be the high-byte or the low-byte depending on your platform) Sonumwill either end up being0xFF 00 00 00, or possibly0x00 00 00 FF
How do I define a 2D array where the first dimension is already defined with MAX_VALUES. I wish to be able to allocate memory to the second dimension. Below is what I have attempted. I want an array with A[1000][mallocd] ``` #define MAX_VALUES 1000 int main(){ int n= 10; int *A[MAX_VALUES] = malloc(10 * sizeof(int)); } ```
Try this ``` int (*A)[n] = malloc(MAX_VALUES * sizeof(*A)); ``` It will allocate contiguous 2D array.
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed8 years ago.Improve this question Why does this: ``` printf("%d\n", pow(1,0)); /* outputs 0 */ ``` returns0? I expected it to return1.
pow()returns adoubletype. You need to use%fformat specifier to print adouble. Using inappropriate format specifier for the supplied argument type causesundefined behaviour. Check chapter §7.21.6.1 of the C standard N1570 (C11). (Yes, this has nothing specific toC89, IMHO)
What is the difference between.cpp.o:,.o:and%.o: %.c?Here's a simple Makefile example: ``` CC=g++ CFLAGS=-c -Wall SOURCES=file1.cpp file2.cpp OBJECTS=$(SOURCES:.cpp=.o) EXECUTABLE=program $(EXECUTABLE): $(OBJECTS) $(CC) $(OBJECTS) -o $@ #.o: #.cpp.o: %.o: %.c $(CC) $(CFLAGS) $< -o $@ all: $(SOURCES) $(EXECUTABLE) clean: rm -rf $(OBJECTS) $(EXECUTABLE) ``` I have noticed that the output is same, but I guess they are interpreted on a different way internally. Is there a preferred way of doing this?
``` .cpp.o: # build *.o from *.cpp (old style notation) %.o: %.c # build *.o from *.c (new style notation) ``` Both work but the new style is more powerful because it allows you to write more complicated constructions thanks to pattern matching: ``` %.uuu: %.vvv %.www ```
It's a familiar fact that in C you can write"a" "b"and get"ab". This is discussed in theC11standard: In translation phase 6, the multibyte character sequences specified by any sequence of adjacent character and identically-prefixed string literal tokens are concatenated into a single multibyte character sequence. The phrase "character and..." would seem to suggest you can get the same results by writing'a' "b", but I've never come across that usage and GCC and the Microsoft compiler both reject it. Am I missing something?
No, maybe we're getting a wrong meaning out of the statement made there. Let me quote fromC11, chapter §5.1.1.2,Translation phases, paragraph 6, Adjacent string literal tokens are concatenated. Here, we don't have any confusion betweencharandstringliterals, it's clearly mentioned aboutstringliterals only.
I recently came across the following C-code: ``` *(STRUCT_T*)(0xC6) ``` STRUCT_Tis atypedefed structure. Can someone explain what this means? My guess:STRUCT_T*casts the address0xC6to a structure pointer and*then retrieves the value (struct) stored at the address0xC6?
Yes, you're correct but I guess, this question needs a little more elaborated answer forwhywe are doing this. To start with, let's see what is done by the unary*operator. Itdereferencesit's operand based on thetypeof the operand. To elaborate in very simple terms, *ptr, whenptris of typechar *will readsizeof(char)i.e., 1 bytes of data starting fromptr*ptr, whenptris of typeint *will readsizeof(int)i.e., 4 bytes of data (on 32 bit system) starting fromptr So, by saying*(STRUCT_T*)(0xC6), we're enforcing treat the pointer (address)0xC6as a pointer to typeSTRUCT_T.dereference the same to get the value of typeSTRUCT_T.
In C/C++ you can initialize a set of variables to the same value by this syntax:a = b = c = 1; Would this work formalloc? I.E. something along the lines of: ``` char *a, *b; a = b = malloc(SOME_SIZE * sizeof(char)); ``` Would this create two arrays of the same size, but each has its own memory? Or would it assign both arrays to the same place in address space?
If you break down your multiple assign line to single assignment lines, the solution would become more clear to you. ``` a = b = malloc(SOME_SIZE * sizeof(char)); ``` OR ``` b = malloc(SOME_SIZE * sizeof(char)); // b points to the alloced memory a = b; // a got the value of b i.e., a points to where b is pointing. ```
Say I have a number which is counting from 0 to 10000,0,1,2,3 ... 9998, 9999, 10000 How am I able to only display the last digit on this number. eg: 0,1,2,3,4,5,6,7,8,9,0,1,2... I have this code but i'm not sure how to implement what I want. ``` if (count_a > 9) { //something here count_a = 0; //resets it back to 0 } else { //count_a is less than 9 count_a =((newtime-original_time)/100); //to get ms //this counts up in the way which I have stated above. ``` How can I loop the((newtime-original_time)/100)to go back to 0 once it is >9?
To extract the last (decimal) digit from a numberx, use: ``` x % 10 ``` The%represents themodulooperator, which equals the remainder after dividing by 10.
I am making a program that reads disk images in C. I am trying to make something portable, so I do not want to use too many OS-specific libraries. I am aware there are many disk images that are very large files but I am unsure how to support these files. I have read up onfseekand it seems to use along intwhich is not guaranteed to support values over 231-1.fsetposseems to support a larger value withfpos_tbut an absolute position cannot be specified. I have also though about using several relative seeks withfseekbut am unsure if this is portable. How can I support portably support large files in C?
There is no portable way. On Linux there arefseeko()andftello(), pair (need some defines, checkftello()). On Windows, I believe you have to use_fseeki64()and_ftelli64() #ifdefis your friend
I am trying to implement the C++11std::find()in my C application. I looked online and found this reference:std::find in C++ My question, how can I usestring.end(),string.begin()in C? Basically how would I use the function provided forstd::find()with pure C? So if I were to do: ``` std::string myString = "hello\n\n"; pos = myString.find("\n\n"); ``` I would want the similar to this in C. How can I do this?
C has the functionstrstrwhich searched one string for another string and returns a pointer to the first character when found. If the substring doesn't appear, it returns a NULL pointer ``` const char *my_string = "hello\n\n"; const char *nl = strstr(my_string, "\n\n"); size_t index = -1; // now subtract the difference to get the index of the substring if (nl != NULL) { index = nl - my_string; } ```
I am working with some open source code in C that uses the assert.h header file ``` #include <assert.h> ``` I think I know what assert is used for and why it is in the program, i.e. it is a macro used for debugging purposes which tests some condition and will possibly abort the program if the condition is not met. My question: there is noassert.hheader file found within the code proper. This confuses me. Isassert.ha universal header file, or is this uniquely written for each program?
assert.h(orcassertin C++) are in the standard library, similar to<math.h>or<stdlib.h>. These header files are supplied by the compiler and are automatically in your include path. http://en.wikipedia.org/wiki/C_standard_library
Neither gcc 5 nor clang 3.6 give warnings where the constraints of therestrictqualifier are violated, even when called with-Wall. Consider the following code fragment: ``` extern void f(char *restrict p, char *restrict q); void g(char *p) { f(p, p); } ``` Naively, I'd expect that the violation can be determined statically, and I was expecting that-Wallwould give a warning. Have I missed a flag somewhere, or is there some problem with giving warnings that I'm not seeing?
Starting with version 8, gcc gives a helpful warning for the above code: ``` a.c: In function ‘g’: a.c:5:5: warning: passing argument 1 to restrict-qualified parameter aliases with argument 2 [-Wrestrict] f(p, p); ^ ```
I can not find how to work properly with mq_timedreceive, can anyone give me an example? ``` ssize_t mq_timedreceive(mqd_t mqdes, char *msg_ptr, size_t msg_len, unsigned *msg_prio, const struct timespec *abs_timeout); ``` I want timereceive to do not spent more than 20 seconds waiting. Thank you very much.
``` struct timespec tm; clock_gettime(CLOCK_REALTIME, &tm); tm.tv_sec += 20; // Set for 20 seconds if( 0 > mq_timedreceive( fd, buf, 4096, NULL, &tm ) ) { ... } ``` Take a look at the full descriptionhere
Suppose in C I have the following code: ``` int foo0(int a) { int b = 0; return a + b; } int foo1(int a) { int b = 1; return a + b; } ... registerCallback(foo0); registerCallback(foo1); ``` I need to make two functionsfoo0andfoo1to make the code work, although they shared the same structure. I want to write only one functionint foo(int a, int b) { return a + b;}and pass parameters to "make" new functions likefoo0andfoo1. Is that possible?
Use: ``` int bar2(int a, int b) { return bar(a); } ... registerCallback(bar2) ```
I wrote a simple program below: ``` #include <stdio.h> unsigned int *time = 0; int main(){ printf("time = %u\n", *time); return 0; } ``` This will gives me segmentation fault on x86-64. Could someone explain the root cause?
As some of the comments mention, you are dereferencing a pointer that is pointing into an area of memory that it should not be. ``` unsigned int *time = 0; ``` is declaring a pointer to an unsigned integer, and the memory address it is pointing to is address 0x0. You are then dereferencing this pointer, which is a problem, because you are asking to read the contents at address 0x0, which results in a segmentation fault. Perhaps if you elaborate more on what you are trying to do, we could give you some additional information on how to proceed, but I'm not really sure exactly what you are going for with the above program.
I started my adventure withcmockalibrary, and I have two questions. Is it possible to find out if free() operation was made correctly? I mean, I would like to test function which is cleaning up tree structure. I've read about test_free(), but honestly I don't understand idea behind that.The second thing is case of catching standard library exceptions. I know about functionexpect_assert_failure, but how to use it? For example I would to do something what will throw segmentation fault, but I would like to pass test anyway.
You need to add ``` #define UNIT_TESTING 1 ``` before you include thecmocka.hheader file, thenmalloc,reallocand free get overridden and will warn you about memory leaks. expect_assert_failure()if for checking that anassert()condition is really hit.
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.Closed8 years ago.Improve this question If a function, sayfoo(), is called in different ways on varius platforms, is it bad practice to use a macro? For example: ``` #ifdef WIN32 #define ffoo(a) foo(0) #else #define ffoo(a) foo(a) #endif ```
In C++ it is considered bad practice, there you have so many other possibilities like inheritance, overloading etc that it is not really needed.
Has anyone had any experience with linking libuv in xcode? I've created a submodule in git to allow easy updating to the library but I can't quite figure out how to correctly add the library to the project to allow me to include uv.h. Any help would me greatly appreciated.
You can use GYP to generate an xcodeproj for libuv (as explained in libuv's README) and add this xcodeproj to your main Xcode project. It can be automated (for easy updating) with a simple shell script (assumes you put the libuv submodule inExternals/libuv, but can be changed): ``` git submodule update --init git clone https://chromium.googlesource.com/external/gyp.git Externals/libuv/build/gyp Externals/libuv/gyp_uv.py -f xcode ``` Then you'll be able to add libuv as a dependency and to the libraries to link your target to: The last thing to do is to tell Xcode where are libuv's headers:
I am working with some open source code in C that uses the assert.h header file ``` #include <assert.h> ``` I think I know what assert is used for and why it is in the program, i.e. it is a macro used for debugging purposes which tests some condition and will possibly abort the program if the condition is not met. My question: there is noassert.hheader file found within the code proper. This confuses me. Isassert.ha universal header file, or is this uniquely written for each program?
assert.h(orcassertin C++) are in the standard library, similar to<math.h>or<stdlib.h>. These header files are supplied by the compiler and are automatically in your include path. http://en.wikipedia.org/wiki/C_standard_library
Neither gcc 5 nor clang 3.6 give warnings where the constraints of therestrictqualifier are violated, even when called with-Wall. Consider the following code fragment: ``` extern void f(char *restrict p, char *restrict q); void g(char *p) { f(p, p); } ``` Naively, I'd expect that the violation can be determined statically, and I was expecting that-Wallwould give a warning. Have I missed a flag somewhere, or is there some problem with giving warnings that I'm not seeing?
Starting with version 8, gcc gives a helpful warning for the above code: ``` a.c: In function ‘g’: a.c:5:5: warning: passing argument 1 to restrict-qualified parameter aliases with argument 2 [-Wrestrict] f(p, p); ^ ```
I can not find how to work properly with mq_timedreceive, can anyone give me an example? ``` ssize_t mq_timedreceive(mqd_t mqdes, char *msg_ptr, size_t msg_len, unsigned *msg_prio, const struct timespec *abs_timeout); ``` I want timereceive to do not spent more than 20 seconds waiting. Thank you very much.
``` struct timespec tm; clock_gettime(CLOCK_REALTIME, &tm); tm.tv_sec += 20; // Set for 20 seconds if( 0 > mq_timedreceive( fd, buf, 4096, NULL, &tm ) ) { ... } ``` Take a look at the full descriptionhere
Suppose in C I have the following code: ``` int foo0(int a) { int b = 0; return a + b; } int foo1(int a) { int b = 1; return a + b; } ... registerCallback(foo0); registerCallback(foo1); ``` I need to make two functionsfoo0andfoo1to make the code work, although they shared the same structure. I want to write only one functionint foo(int a, int b) { return a + b;}and pass parameters to "make" new functions likefoo0andfoo1. Is that possible?
Use: ``` int bar2(int a, int b) { return bar(a); } ... registerCallback(bar2) ```