question
stringlengths
25
894
answer
stringlengths
4
863
As I compile my app.cpp file into app.js using Emscripten, I'm not seeing a difference between the -o1/2/3 optimization levels when I inspect the app.js file. They are all unoptimized/unminified and human readable. I've run the emcc update/install commands, and I use ``` emcc -o3 app.cpp -o app.js ``` to compile i...
Yup, it was obvious. The command is case sensitive. Needs to be a capital 'O'. I don't have much experience with the command line. This is what happens.
I am trying to debug my C program that accesses a postgres database. I would like to dump the contents of PGresult using some postgres provided routine. Is there a postgres provided routine that will dump PGresult in a human readable way? I will add that as an option to the logging that will dump the contents of PG...
Insrc/interfaces/libpq/fe-print.cthere is a public functionPQprint; it'sin the manual.
I have a multi-dimensional structure in R in which I'm accessing a list on those ways: model$a$bormodel[[5]][[4]] But how to do this in a C extension? Right now I'm trying it like that: VECTOR_ELT(VECTOR_ETL(model, (R_xlen_t) 4), (R_xlen_t) 3) But it behaves more likemodel[5][4]thanmodel[[5]][[4]]
Got it by using coerceVector with generic vector (VECSXP) after first VECTOR_ELT and coerceVector with integer vector (INTSXP) after second VECTOR_ELT
Is there any difference between null pointer and uninitialized pointer? This question was asked in one of the interviews. Could you please explain the difference that they have?
Well, the difference is exactly that. Null pointer is initialized to null, and as such has defined meaning. You can check it for null, and dereferencing it will (on all platforms I know) cause a program to crash with meaningful diagnostics. You can also use null pointers in some specific hacks. Unitinialized pointers,...
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed8 years ago.Improve this question Is my definition of machine code right? Machine code is the programming language which i...
Machine code is the code written in the native instruction set of the machine. i.e. the CPU. It is possible to write code which can run on different OSes, and different processors, though this is usually only done when there is relatively minor differences. I used to have a program which could run on a Z80 or x86, o...
The following call fails to dynamically load the library, complaining that it cannot load more objects with static TLS: ``` dlopen("libfoo.so",RTLD_LOCAL | RTLD_NOW); ``` However after I examine it: ``` readelf -a libfoo.so | grep TLS ``` There are no TLS symbols. Any ideas why it would be failing to load?
Any ideas why it would be failing to load This library probably depends on some other library with a TLS segment. You can runldd libfoo.so, and thenreadelf -lon each dependent library. One of them has to have aTLSsegment, or you wouldn't be getting the error you are getting.
I'm using CooCox CoIDE and GCC ARM embedded 4.9q2 and I use the cmsis library, programming on an ARM Cortex-M4 STM32F3 MCU. I'm currently trying to do some quick saturating arithmetics inside an interrupt. I was under the impression that I could do that using the ARM C Language Extension (ACLE) to avoid having some a...
You should ``` #include <core_cm4_simd.h> ``` From the CMSIS headers. It defines the instructions as inline functions, prefixed by__.
``` #include <stdio.h> int main() { int i=-1; !i; printf(i); } ``` Output: 0 Why is the outputzero?
In your code, ``` printf(i); ``` isinvalid, becauseprintf()expects aconst char *as the first argument, and you're passing anint. It invokesundefined behaviour. Turn up the compiler warnings. With the basic level of warning turned on, you should get some message along the line warning: passing argument 1 of ‘printf...
Let's say i have source and header files for C code (bus-driver.candbus-driver.h)can i call functions inside them from node.js for examplebus-driver.h ``` void bus_init(void); void bus_write(char *buf); ``` I want to call these functions from node.js.
The nodeffi seems to be simplest way to do that. I didn't test it so it can has problems that I don't realize now. But I would suggest to do something like that, following thetutorial. Installnodeffi: Generate a library for your bus-driver if you don't have one, let's call it libbusdriver. Then in your javascript d...
With IBM's cc compiler there is one option -brtl. cc-brtl ..... This option does the following:- -brtl Tells the linkage editor to accept both .so and .a library file types. I am using gcc compiler now on ubuntu. I want to know what is the corresponding option in gcc to achieve the same thing?
You don't need that option forgcc. The link editor will accept both so and a files by default, with so files being preferred. You can think ofgccas having the opposite behaviour to IBM's C compiler: The behaviour without any options is as if you provided-brtlto IBM's C compiler, while the option-staticturns of dynamic...
I have a variable i: ``` int i; if(b){ i=1; } else{ i=-1; } ``` Isiundefined behavior because ofint i;exists? Or Should we alwaysint i=0first?
Absolutely fine. You are initialisingion all program control paths, and not reading the value until initialisation is complete. I prefer using the ternary operator in such instances. int i = b ? 1 : -1; as that's less vulnerable to accidental reference to an uninitialisedi.
``` #include <stdio.h> #include <stdlib.h> int main() { FILE * fp; fp = fopen ("file.txt", "w+"); fclose(fp); return(0); } ``` the above programs will create a file . i need that file needs to be placed in specific directory. please help
Add path into the parameter offopen(). ``` fp = fopen ("/path/to/file.txt", "w+"); ```
For a project I have to change the zero-driver to produce an infinite amount of 'a' instead of the usual zero. So I modified /usr/src/drivers/memory/memory.c This was the original: ``` /* Initialize /dev/zero. Simply write zeros into the buffer. */ for (i=0; i<ZERO_BUF_SIZE; i++) { dev_zero[i] = '\0'; //This is ...
Assuming you are editing the kernel source code, you probably need to reboot to see your changes take effect.
Go through the following C code ``` # define swap(a,b) temp=a; a=b; b=temp; main( ) { int i, j, temp; i=5; j=10; temp=0; if( i > j) swap ( i, j ); printf ( "%d %d %d", i, j, temp); } ``` Compiler Output: ``` 10 0 0 ``` I am Expecting this output ``` 10 5 0 ``` Why am I wrong??
It's the lack of braces. This is one of the common pitfalls with macros. Let's see what happens: ``` if(i > j) swap(i, j); ``` becomes: ``` if(i > j) temp = a; a = b; b = temp;; ``` Made a little more readable: ``` if(i > j) temp = a; a = b; b = temp; ``` So the linesa = b;andb = temp;will always be ...
I recently started using Dev C++ 4.9.9.2 to experiment with graphics program in C(thanks to thistutorial). But for some reasonsetbkcolor()does absolutely nothing. Here's the code... ``` #include <stdio.h> #include <graphics.h> #include <conio.h> int main() { initwindow(800,600); setbkcolor(GREEN); //FAILED...
Thedocumentationsays in theWindows notespart: Also, only future drawing will use the new background color (anything currently drawn in the old background color will stay in the old color). Callingsetbkcolor(0)will change the background color to the current color at index[0]of the palette (rather than always changing ...
I am trying to understandsscanfformatting. Can it take arrays of C strings to output to (the code below gives a segfault, which is what prompted the question)? Also, when trying to take only specific characters for a string, is the format%[abc]swhereabcis the set of characters to keep? ``` char s[] = "This is a 345...
Re-write thesscanfline as follows - ``` sscanf(s,"%s %*s %*s %lf %s",str[0],&f,str[1]); ^address of float variable required ``` And infor loopprint value of arraystr. See working code here-https://ideone.com/hFpvDJ
i'm calling setsockopt function as shown below to turn off the loop back of the same data gram which I send from the server to the client. ``` char loop_back = 0; if((loop_back_flag = setsockopt(sock, IPPROTO_UDP, IP_MULTICAST_LOOP, (char *)&loop_back, sizeof(loop_back))) == -1) { // Print Error message ...
EDIT: just declareloop_backasint ``` int loop_back = 0; ``` if you look at the man guide,setsockoptreturn anint
What does this macro mean or what is the result? ``` #define MOD_TYPE_12 0x11, 0x20, 0x0C, 0x00, 0x02, 0x00, 0x07, 0x0F, 0x42, 0x40, 0x01, 0xC9, 0xC3, 0x80, 0x00, 0x02 ``` Is this evaluated to an array? I couldn't find anything... Maybe because I don`t know what I have to search for ^^
All the MOD_TYPE_12 in your program will be replaced with 0x11, 0x20, 0x0C There is no specialty with commas
I created a for-loop in C, which should work, Eclipse however told me that I used an undeclared variable, here's my code: ``` #include <stdio.h> int main( int argc, char ** argv ) { for(int i = 1; i <= 5; ++i) { printf("i is %d\n", i); } return 0; } ``` according to Eclipse the undeclared variable, ision thepri...
In ANSI C (unlike C90/C11) you cannot declare variables in for loop. You unfortunatelly have to to this (or change your compiler to a more modern one, you won't be compatible with the ANSI standard though): ``` int main( int argc, char ** argv ) { int i; for(i = 1; i <= 5; ++i) { printf("i is %d\n", i); } return ...
I have a C-function which returns astructdata type with several items in it (size_t, char*, int, unsigned and other structs). When I call this function there is no output in python. After some googling I think the problem is that I didn't declare the data type in my interface file. But this turns out to be not that ea...
You need to %include the header first. You need the headers for the nested structs too, in dependency order! After you've done that, Swig should automatically wrap the struct so that a call to your function will return a proxy object with the appropriate members. A typemap is for when you want to change Swig's defau...
Is there any other method to print names in left justified and the numbers in right justified manner in file without usingprintf("%10d")in c language?
How about this? ``` void print_uint32_right_justify(uint32_t num, int width) { char b[width + 2]; char *p = b + width + 1; *(p--) = 0; if(!num) *(p--) = '0'; while(num > 0) { *(p--) = '0' + num % 10; num /= 10; } while(p > b) *(p--) = ' '; write(1, b + 1, width); } ```
I have a code which looks something like this ``` void * mypointer; void * array = malloc(sizeof(void*)*10) loop{ mypointer = malloc(some random size); memset(mypointer,start,end) array[i++] = mypointer++ } ``` Now this is throwing an exception that ``` 'void*' is unknown size for array ...
Sincearrayis supposed to be an array of pointers, use: ``` void ** array = malloc(sizeof(void*)*10) ``` When you use ``` void* array = ... ``` you cannot indexarraylike you are doing in the following line. ``` array[i++] = mypointer++; ``` Remember that ``` array[k] = *(array+k); ``` array+kcan be evaluated on...
When I run my program within Code::Blocks it works fine. But when I build it and then click on the executable I get an error saying The program can't start becauselibgcc_s_dw2-1.dllis missing from your computer. Try reinstalling the program to fix this problem. I'm not to sure why that happens I did everything that ...
You should copylibgcc_s_dw2-1.dll(it should be located somewhere similar toC:\MinGW\binorC:\Program Files\CodeBlocks\MinGW\bin) into the same folder as the.exe.
I just came to know aboutbool. It seems that bothboolandwhile (true)orwhile (1)are the same endless function. Doesboolhave any advantages overwhile (true)orwhile (1)?. I can't see any difference. bool: ``` #include <stdio.h> #include <stdlib.h> #include <stdbool.h> int main(void) { bool keep_going = true; // ...
While(true) is an infinite loop. Boolean is a data type with true and false values. Bool is used in case if you want to change to false at any stage. So you can change the value of bool inside for loop to stop loop.
``` addr4 = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr; internal_addr = inet_netof(*addr4); printf("IPv4 MASK %08x \n",internal_addr); ``` I have the above code. It is printing the IPv4 MASK as ``` IPv4 MASK 00ffffff ``` I am assuming this represents255.255.255.0. Is that correct assumption...
Per your desire to convert it to the number of mask bits (CIDR notation), just count the number of one bits in the mask. Just loop through the 32-bit, unsigned integer (0x00ffffff), checking if it is greater than 0, if it is greater than 0 add 1 to your answer, then divide the unsigned integer by 2 (or shift it right...
I would like to get (almost) exactly the same result of htmlSAXParseDoc in Java, for an Android mail parsing module. Specifically, sincemailcore 2uses htmlSAXParseDoc to "flatten" html (in method "flattenHTMLAndShowBlockquoteAndLink"), with certain state passed in as parameter. I wonder if there are similar method in...
ok it looks like Android does have libxml2 included in its core package. Will go from there first.
Please take a look at this screenshot: As you can see, the"Executable modules"and"Threads"child windows are free to roam about in the sandbox-like"Themida"parent window, and if they get dragged past the edge the overflow simply gets hidden. How can I create this effect?
That is aMultiple Document Interface(MDI) application. The containing window, with the dark grey background is the MDI client window, and the windows inside are the MDI child windows. The use of MDI has been discouraged by Microsoft for many years so you may wish to think twice about using it in a new application.
``` void main() { int u, t, h ; printf("\n Enter a number (with 3 digits) \n"); printf("\n Enter the unit digit number \n"); scanf("%d",&u); printf("\n Enter the tenth digit number \n"); scanf("%d",&t); printf("\n Enter the hundredth digit number \n"); scanf("%d",&h); } ``` I...
With this solution the final string stored instris portable throughout your program. ``` char str[16]; sprintf(str, "%d", (h*100) + (t*10) + u); printf("%s\n", str); ```
I just started migrating to Mac OS X and I wanted to port a couple of tools I wrote for Windows. The question is what is the equivalent for the following: ``` CreateFile() CreateFileMapping() MapViewOfFile() ``` I would appreciate if someone could either guide me to a place where I can read about it or if there is s...
The equivalent ofCreateFilewould beopen. The latter two steps for mapping a file,CreateFileMappingandMapViewOfFile, are condensed into one step on Mac OS X, with themmapfunction.
I'm writing a library that works withHWNDandHDCunder the hood.ReleaseDCtakes aHWNDas a parameter, but what if the window has already been destroyed? Does Windows free theHDCautomatically, or does this cause a resource leak?
When testing on Windows 10, it appears that a DC retrieved withGetDCis automatically released when the window is destroyed. An infinite loop that creates a window, retrieves a DC, and destroys the window had no increase of memory usage after the first iteration. To make sure some internal reference count wasn't being...
I am trying to inverse a hexadecimal value. The result is wrong, however. ``` #include <stdio.h> #include <stdint.h> #include <netinet/in.h> int main(void) { uint32_t acc = 0xBBD1; printf("0x%X", htons(~acc)); // prints 0x2E44 } ``` Let's do the inversion by hand: ``` 0xBBD1 = 1011 1011 1101 0001 ~101...
Technically, no. But why are you usinghtons? It changes the endianess of a 16 bit datum to big-endian (that is, network byte order). First is your variable not 16 bit but 32 bit, souint16_t acc = 0xBBD1would be more appropriate. Second, as your on a little-endian machine, the bytes are exchanged, hence the output.
installing festival speech synthesis system fromhttp://festvox.org/...directly by running general script. Facing below given problem .....this problem will effect my working on festival framework or not ????? ``` eps.c: In function ‘getd’: eps.c:142:7: warning: ignoring return value of ‘fscanf’, declared with att...
Read documentation offscanf(3). You should use the returned count of successfully scanned items, e.g. code something like: ``` int x = 0, y = 0; if (fscanf(fp, "%d %d", &x, &y) < 2) { fprintf(stderr, "missing numbers at offset %ld\n", ftell(fp)); exit(EXIT_FAILURE); } ``` so you could improve theeps.cfile (and...
``` idx x, z ; for (x = 0 ; x < k ; ++x) { if (mots[x].mot) { printf("%s :", mots[x].mot) ; //Below not working properly how to write all my refs ? // printf("%i ", mots[x].refs -> cdr ->ref); // while (mots[x].refs -> cdr) printf("%i ", mots[x].refs -> ref...
``` if (mots[x].mot) { printf("%s :", mots[x].mot) ; struct node *node = mots[x].refs; while (node) { printf("%i ", node->ref); node = node->cdr; } printf("\n"); } ```
This question already has an answer here:The program control flow doesn't work as expected(1 answer)Closed8 years ago. I'm learning C and to get something done I need to ask the user to input 2 characters, like in this example: "b [enter] t". and store them in two different variables, but my code is not working that ...
The problem is thatawill be set to'b'butbwill be set to'\n'(fromEnter). If you want sane user input, always read a whole line first (e.g. withfgets), then process it (e.g. take the first character or convert it to a number, etc).
I'm trying to solve a problem where I want a bash script to call acprogram and a value from thecprogram to be returned to the bach script and be stored in a variable. Here is an example (code isn't really written properly): Bash script: ``` $value = ./foo echo $value ``` C program: ``` int main() { //Have a v...
You can get the return value of the last program you executed by using$?or you can print the value to stdout and then capture it. ``` #include <stdio.h> int main() { printf("my_value"); return 0; } ``` and then in bash do ``` value=$(./my_program) echo $value ``` the result will bemy_value
I remember being constantly told that the C preprocessor does not know C. It doesn't know about types, doesn't remember declared symbols, etc. If that's the case, how can it possibly act differently based on the type of its parameter?
The_Genericfeature is not processed by the preprocessor. It is aprimary expressionthat is treated with higher preference than most other expressions.
So I am starting to learn C. I am learning from the classic K&R book. In the book they have the following function: ``` /*squeeze: delete all c from s */ void squeeze(char s[], int c) { int i, j; for (i = j = 0; s[i] != '\0'; i++) if (s[i] != c) s[j++] = s[i]; s[j] = '\0'; } ``` My q...
A string in c is just an array of characters with a null terminator,\0, signifying the end. Characters can still exist after the null terminator, but any functions using c strings, ie.printforstrcpywill use the null terminator to mark the end, so it will effectively be treated as if there were nothing after the\0.
Is there anything similar to Java's Integer.MIN_VALUE in C, which gives the smallest possible value of a signed integer, or do I just have to hard code the value myself?
You can uselimits.hhttp://en.cppreference.com/w/c/types/limits I think this is what you're looking for:INT_MIN = minimum value for an int
Why is this code not working properly? The intent of this code is to generate and print two random numbers separately as many times as user choose. M.T. Thanks. ``` #include <stdio.h> #include <stdlib.h> #include <time.h> #define random(x) rand() % x #define randomize srand((unsigned)time(NULL)) int i=...
You are callingsrandmore than once. Placerandomize;outside theforloop. Another problem is with the statement ``` scanf("%d",x); ``` you forget to place&beforex. Also You need to correct the loop conditiony = xtoy < xas mentioned in comment by @Cool Guy.
``` FILE *fp = fopen("./con", "w"); char *s = "hello!"; fwrite(s, sizeof(char), strlen(s), fp); fclose(fp); return 0; ``` If my file name is "con", thenfwrite()will work just likeprintf(). How does it work?
Windows/DOS has a number ofreserved filenamesincluding CON, PRN, AUX, CLOCK$, NUL COM1, COM2, COM3, COM4 LPT1, LPT2, LPT3, LPT4 and others. CONis the standard console (output), so that is where the data went. Credits: @BLUEPIXY @Joachim Pileborg
Is there a way to hide the Scrollbar thumb, for example in this image Notepad does not have a thumb for both Scrollbars: I have tried to setSCROLLINFO.nPageto0but it did not work. Edit:I am talking about a control Scrollbar.
When you callSetScrollInfo, set theSIF_DISABLENOSCROLLflag in thefMaskfield. The scrollbar will then be disabled (and the thumb hidden) if the scroll bar's parameters make the scroll bar unnecessary. However that technique only works for the non-client window scrollbars. If you want to disable a control scrollbar you...
What is the difference in += and normal add ``` a = a + b; a += b; ``` what is the different in above two lines?Is there any increase in CPU cycles for "+=" operator?Which would be the preferable method of coding.?
Beside single evaluation of first operand, there is second difference, that occurs whenbis an expression, involving operators with lower precedence. For instance: ``` int a = 1; a += 0 || 1; ``` yields two, while: ``` int a = 1; a = a + 0 || 1; ``` stores one intoa. The equivalent of former statement would be: ``...
``` FILE *fp = fopen("./con", "w"); char *s = "hello!"; fwrite(s, sizeof(char), strlen(s), fp); fclose(fp); return 0; ``` If my file name is "con", thenfwrite()will work just likeprintf(). How does it work?
Windows/DOS has a number ofreserved filenamesincluding CON, PRN, AUX, CLOCK$, NUL COM1, COM2, COM3, COM4 LPT1, LPT2, LPT3, LPT4 and others. CONis the standard console (output), so that is where the data went. Credits: @BLUEPIXY @Joachim Pileborg
Is there a way to hide the Scrollbar thumb, for example in this image Notepad does not have a thumb for both Scrollbars: I have tried to setSCROLLINFO.nPageto0but it did not work. Edit:I am talking about a control Scrollbar.
When you callSetScrollInfo, set theSIF_DISABLENOSCROLLflag in thefMaskfield. The scrollbar will then be disabled (and the thumb hidden) if the scroll bar's parameters make the scroll bar unnecessary. However that technique only works for the non-client window scrollbars. If you want to disable a control scrollbar you...
What is the difference in += and normal add ``` a = a + b; a += b; ``` what is the different in above two lines?Is there any increase in CPU cycles for "+=" operator?Which would be the preferable method of coding.?
Beside single evaluation of first operand, there is second difference, that occurs whenbis an expression, involving operators with lower precedence. For instance: ``` int a = 1; a += 0 || 1; ``` yields two, while: ``` int a = 1; a = a + 0 || 1; ``` stores one intoa. The equivalent of former statement would be: ``...
If I mention ``` int ar[100]={1,1}; ``` and I want to know the number of elements present in it rather than the size of it, what commands should I use?
In case of anarray, the size is always the number of elements multiplied by the size of each element. Neither of them (number of element or size) vary, once it is defined. If you meant to find out themeaningful(to you) elements present in the array, well, you need to have asentinel valuesomewhere (thereby marking the...
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 I am a student, at the moment I finished my first language C fundamentals course. I ...
It sounds like you want to use Raspberry Pi to control other hardware using the general purpose I/O pins. In this case there are libraries for bothPythonandCavailable to access those pins.
I am getting "variable may be used before being set" when I create a pointer to a structureexample *e. If I use a variable insteadexample e, I am not getting the error. Is this because I haven't allocated memory for the pointer? ``` typedef struct example { int a; }example; void test (){ example *e; e->...
eis NOT pointing to anything. You are using an uninitialized pointer. You "set" through an invalid pointer, and then trying to access it. Your pointer should point to anexampleinstance. For example: ``` example exampleInstance; example * examplePointer = &exampleInstance; ```
I'm trying to celebrate 10,000,000 questions on StackOverflow with a simple console application written in C, but I don't want to waste any memory. What's the most efficient way to store the number 10,000,000 in memory?
The type you're looking for isint_least32_t, fromstdint.h, which will give you the smallest type with at least 32 bits. This type is guaranteed to exist on C99 implementations. Exact-width typedefs such asint32_tare not guaranteed to exist, though you'd be hard pressed to find a platform without it.
Let me be judged as a Noob in programming, I have been learning obfuscated way of programming in c/c++, as the c compiler compiles a statement from the right hand side towards the left hand side. I have the following code: ``` int main(){ int x=5, y=20, z=1; int k = x > y < z; printf("%d", k); return...
Changez=-1orx=0and find out. Also changeint main()to the more correctint main ( void ) Changingz = -1will ouput0, whereaskwill be1if you assign itx > y == zifz = 0. So in short: ``` k = x > y < z; ``` is the same as writing ``` k = (x > y) < z; ``` left-to-right.
I'm doing a very basic printout of scientific notation. But, it appears to me its not working and I can't figure out why? Code: ``` size_t result = 0; printf("%e \n",result); ``` Value it prints is below: ``` 1.278341e-307 ``` What would be right way to do scientific notations?
If you use a floating-point printf format code, like%e, the matching argument must be adouble. But you are passing it an integer (size_t). Printf does not know the types of its arguments, so you have to tell it what they are by using the correct format code. If you lie to it, you will get undefined results. And if y...
I'm doing a very basic printout of scientific notation. But, it appears to me its not working and I can't figure out why? Code: ``` size_t result = 0; printf("%e \n",result); ``` Value it prints is below: ``` 1.278341e-307 ``` What would be right way to do scientific notations?
If you use a floating-point printf format code, like%e, the matching argument must be adouble. But you are passing it an integer (size_t). Printf does not know the types of its arguments, so you have to tell it what they are by using the correct format code. If you lie to it, you will get undefined results. And if y...
Is it possible to read a character and an integer in one time? Like this: ``` char name[32]; int age; printf("Give name and age: "); scanf("%s%d%*c", name, &age); ``` It blocks all the time.
UPDATED:You only accept input but not printing any thing. See the below code (working and tested) ``` #include <stdio.h> int main(void) { char name[32]; int age; printf("Give name and age: "); scanf("%31s%d", name, &age); printf("Your name is %s and age is %d",name,age); } ``` intput: Shaz 30Output: Your name is ...
My goal is to parse potentially garbled ASCII data containing text and numbers. So far I've been doing fine with getting a pointer to numbers within the text withstrcmpand hard-coded pointer arithmetic and then converting them withstrtol, but I feel there must be a better way. Is there a function with the effect ofsc...
You'll be wantingsscanf. Note that it does expect a null-terminated string.
From a Fortran Code, I intend to run a C code (to read a file) and fetch the read information. The main program is the Fortran code, which uses a function written in C to do the processing. In this C code, is it necessary to run a main function?
If Fortran only calls the C function, then the C code does not need amain()function. Themain()function of C is the program entry point. The system loads the .exe, transfers control to the startup code, which address is mentioned in the .exe file (the startup code is calledcrt, C run-time start-up). The run-time start...
The ISO C Standard requiresCHAR_BITto be at least 8. With POSIX mandatingCHAR_BITbe equal to 8, and (almost?) all networking and communication standards usingoctets, is thereanycontemporary C implementation whereCHAR_BIT> 8? (Note: I'm not interested in historic computer architectures using 18 or 36 bit words. It's ...
TMS320C28xDSP from Texas Instruments has a byte with 16 bits. Documentationfor the compiler specifiesCHAR_BITas 16 on page 101. This appears to be a modern processor (currently being sold), compilers supporting C99 and C++03.
I have a string which captures details stored indata User 6%, System 18%, IOW 0%, IRQ 0% What i am doing is sscanf(data,"User %d,System %d,IOW %d,IRQ %d",&user,&sys,&iow,&irq); I am getting wrong output . why ? Is is like i am missing something ?
You left out the%symbols and some spaces - try: ``` sscanf(data,"User %d%%, System %d%%, IOW %d%%, IRQ %d%%",&user,&sys,&iow,&irq); ```
My PC configuration is Intel Core i3-2100 CPU @3.10GHz Windows7 64 bit But when I'm executing below code why it's printing 1000? ``` #include<stdio.h> #include<conio.h> #include<time.h> main() { printf("Clock %d",CLOCKS_PER_SEC); getch(); } ``` The actual clock speed should be around 3.1x10^12 per sec rig...
Clock ticks are units of time of a constant but system-specific length, as those returned by functionclock. It has nothing to do with the processor speed.
I have the following linked list: ``` struct node { int d; struct node *next; }; int main() { struct node *l = 0; struct node *k = l; k = malloc(sizeof(struct node)); /* l->d = 8; */ return 0; } ``` Why is the commented code wrong to use? I don't understand why the memory isn't alloca...
Let's take it apart. Look at the comments ``` struct node{ int d; struct node * next; }; int main(){ struct node * l = 0; // Now l = 0 (or NULL) struct node * k = l; // Now k=l=0 k = malloc(sizeof(struct node)); // Now k=<some address allocated> /* l->d = 8; ...
My goal is to parse potentially garbled ASCII data containing text and numbers. So far I've been doing fine with getting a pointer to numbers within the text withstrcmpand hard-coded pointer arithmetic and then converting them withstrtol, but I feel there must be a better way. Is there a function with the effect ofsc...
You'll be wantingsscanf. Note that it does expect a null-terminated string.
From a Fortran Code, I intend to run a C code (to read a file) and fetch the read information. The main program is the Fortran code, which uses a function written in C to do the processing. In this C code, is it necessary to run a main function?
If Fortran only calls the C function, then the C code does not need amain()function. Themain()function of C is the program entry point. The system loads the .exe, transfers control to the startup code, which address is mentioned in the .exe file (the startup code is calledcrt, C run-time start-up). The run-time start...
This is a question for deeper understanding. Let's say I have the following code: ``` #define DEF 1,2,3 #if (DEF > 3) #endif ``` If I am right the if should always be true, as 1 and 2 are Expressions that have no affect and only 3 will be checked. (This should at least be true in normalC/C++-code) But is that righ...
DEFwill expand to give#if (1, 2, 3 > 3). Because,has low precedence, the only expression that "does" anything is3 > 3which, of course, is false.
Of course I know that we don't cast the result ofmalloc(), but what aboutmkl_malloc()? Here is theprototype:void* mkl_malloc (size_t alloc_size, int alignment); It has the same return type asmalloc(), as you can see:void* malloc (size_t size); As a result, I would not cast the result, for thesereasons. But the Inte...
Casting the result is superfluous and doesn't make much sense, so you shouldn't do it for that reason. But it is not super-important, it is a minor trifle. The whole "cast the result of malloc" debate has gone out of proportion on Stack Overflow, and the most valid concerns of why you shouldn't went obsolete 16 years...
What's the difference between (1) ``` char s[5] = {'a', 'b', 'c', 'd', '\0'}; char s2[strlen(s) + 1]; strcpy(s2, s); ``` And (2) ``` char s[5] = {'a', 'b', 'c', 'd', '\0'}; char *s2 = malloc(strlen(s) + 1); strcpy(s2, s); ``` In what situation should you use each of these? Can you only use the first one when you ...
In case 1, ``` char s2[strlen(s) + 1]; ``` s2is an array. In case 2, ``` char *s2 = malloc(strlen(s) + 1); ``` s2is a pointer. FWIW, the first approach won't work if the compiler does not supportVLA. As per the latest standard,C11, VLA is anoptionalfeature which compiler(s) is (are) notbound tosupport. The secon...
I have a situation where i have to callwake_up_interruptible()on a wait queue, which may not holding any process to sleep. Is it ok to callwake_up_interruptible()on an unused wait queue ?
Yes, as long as the queue is initialized you are fine.
I am creating cross platform code(Win and Linux) and in windowsVS the file path is usually used as ``` "Folder1\\folder2\\file" ``` where as in gcc it should be '/' in the place of '\' ``` "Folder1/folder2/file" ``` Can anyone suggest a way to use that or is there any #define macro that I can use in assigning this...
Use/on both platforms. The C APIs for Windows accept both/and\.
Consider the following code: ``` #define P1(x) x+x #define P2(x) 2*P1(x) int main() { int a = P1(1) ? 1 : 0; int b = P2(a)&a; return 0; } ``` Now, I thought that the compiler first replacing the macros with their values and soint b = 2*a+a&a;(and sincea=1thenb=3). Why isn't it so?
This is because&has lowerprecedencethan that of addition+operator. The grouping of operands will take place as ``` int b = ( (2*a + a) & a ); ``` Therefore,(2*a + a) = 3and3 & 1 = 1(011 & 001 = 001).
I have searched for that several times but I have no obvious answer I want to make a C function that takes a variable as an argument and then uses that argument to replace a placeholder in another template file in the form like that Port %PORT% I need that when that function get called the %PORT% is replaced with ...
Have you considered usingsed? It is available on most linux systems, you should be able to accomplish what you want using this examples, which reads template file tmpl.txt and creates a file called specific.txt where the value %Port% is replaced with a 4242 which was saved in a variable PVAR: tmpl.txt ``` Port %PORT...
What does this expression mean: ``` typedef char foo [FOO]; ``` I am just struggeling with the meaning of the expression between the squared brackets.
It readsfoois the type of an array ofFOO-manycharelements. In this case,FOOis a constant, defined somewhere as#define FOO 100 ``` typedef int pair[2]; // Pair is an array of two ints. ```
This is a question for deeper understanding. Let's say I have the following code: ``` #define DEF 1,2,3 #if (DEF > 3) #endif ``` If I am right the if should always be true, as 1 and 2 are Expressions that have no affect and only 3 will be checked. (This should at least be true in normalC/C++-code) But is that righ...
DEFwill expand to give#if (1, 2, 3 > 3). Because,has low precedence, the only expression that "does" anything is3 > 3which, of course, is false.
Of course I know that we don't cast the result ofmalloc(), but what aboutmkl_malloc()? Here is theprototype:void* mkl_malloc (size_t alloc_size, int alignment); It has the same return type asmalloc(), as you can see:void* malloc (size_t size); As a result, I would not cast the result, for thesereasons. But the Inte...
Casting the result is superfluous and doesn't make much sense, so you shouldn't do it for that reason. But it is not super-important, it is a minor trifle. The whole "cast the result of malloc" debate has gone out of proportion on Stack Overflow, and the most valid concerns of why you shouldn't went obsolete 16 years...
What's the difference between (1) ``` char s[5] = {'a', 'b', 'c', 'd', '\0'}; char s2[strlen(s) + 1]; strcpy(s2, s); ``` And (2) ``` char s[5] = {'a', 'b', 'c', 'd', '\0'}; char *s2 = malloc(strlen(s) + 1); strcpy(s2, s); ``` In what situation should you use each of these? Can you only use the first one when you ...
In case 1, ``` char s2[strlen(s) + 1]; ``` s2is an array. In case 2, ``` char *s2 = malloc(strlen(s) + 1); ``` s2is a pointer. FWIW, the first approach won't work if the compiler does not supportVLA. As per the latest standard,C11, VLA is anoptionalfeature which compiler(s) is (are) notbound tosupport. The secon...
I have a situation where i have to callwake_up_interruptible()on a wait queue, which may not holding any process to sleep. Is it ok to callwake_up_interruptible()on an unused wait queue ?
Yes, as long as the queue is initialized you are fine.
I am creating cross platform code(Win and Linux) and in windowsVS the file path is usually used as ``` "Folder1\\folder2\\file" ``` where as in gcc it should be '/' in the place of '\' ``` "Folder1/folder2/file" ``` Can anyone suggest a way to use that or is there any #define macro that I can use in assigning this...
Use/on both platforms. The C APIs for Windows accept both/and\.
``` int main() { int a=10,b=11,c=13; *((a)?&b:&c)=a?b:c; printf("%d %d %d ,"a,b,c); return 0; } ``` I don't understand the output of*((a)?&b:&c)=a?b:c;statement
Lets comprehend this monster: *((a)?&b:&c)=a?b:c; Take the first evaluated part:(a)?&b:&c: simply means ifais not zero then get the address ofb, otherwise get the address ofc. Second evaluated part: *(...)dereferences an address to the actual value. In this case this evaluates to*&bwhich is justb(*is the inverse o...
I want to define a specific memory region in the STM32 micro where to store some strings. I'm using IAR compiler but I don't find a simple example that can help me to create the region in the correct way using the icf file. How can I create the region and use this region in the code? Thanks
I found this solution: In the icf file I define the memory region in this way: ``` define region LANGUAGE_region = mem:[from 0x080FB000 to 0x080FC000]; "LANGUAGE_PLACE":place at start of LANGUAGE_region { section .LANGUAGE_PLACE.noinit }; ``` I will fill this region with an external srec file using a programmer....
``` curl_easy_setopt(curl, CURLOPT_URL, "127.0.0.1:8081/get.php"); curl_easy_setopt(curl, CURLOPT_POSTFIELDS,"pulse=70 & temp=35" ); ``` this above code run successfully but when I pass this ``` int pulsedata = 70; int tempdata = 35; curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "pulse=pulsedata & temp = tempdata"); ...
A possible C solution: ``` char sendbuffer[100]; snprintf(sendbuffer, sizeof(sendbuffer), "pulse=%d&temp=%d", pulsedate, tempdata); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, sendbuffer); ```
I am making an uno card game with structure of card with fields: ``` struct card { int rank char *color char *action. } ``` I am able to make it sort by color with insertion. I wonder how could I first sort the array of uno card by color, then sort the rank of each color.
Thanks to Bo Persoson, this is the solution to my question ``` void sort(card *a, int length) { int j; for (int i = 1; i < length; i++) { j = i; while (j > 0 && a[j].color < a[j - 1].color || (a[j].color == a[j - 1].color && a[j].rank < a[j - 1].rank)) { swap(&a[j], &a[j - 1]); j--; } } ``...
I need to somehow enable XML file transfer in the way that some machine, which generates a XML file sends the XML file through HTTP to another client. This other client would be based on C, receive the XML file and process it. Is this possible in any way? I only found results for sending XML files to a HTTP server us...
maybe you can use libcurl here is a http POST example:http://curl.haxx.se/libcurl/c/http-post.html on the receiving computer has to be a listening socket. here is a socket example:http://www.codeproject.com/Articles/586000/Networking-and-Socket-programming-tutorial-in-C this socket takes the incoming data for later...
``` #include<stdio.h> int main() { char ch; for(ch='0';ch<=127;ch++) printf("%c %d",ch,ch); return 0; } ``` How ever this becomes an infinite loop when executed. I want to know exact reason behind it? Is type casting to and fro from int to char the reason? Also one small question Whether all files...
Here, you are comparingchartoint ``` for(ch='0';ch<=127;ch++) ``` int value of a char can range from 0 to 255 or -128 to 127, depending on implementation. In your case, acharis asigned char, which can hold the value of a range to -128 to +127. Therefore once the value reaches 127 in your case, it overflows and you ...
I'm trying to send an encrypted message in a simple server-client chat program. This is thesend()call: ``` int send(int sockfd, const void *msg, int len, int flags); ``` Can I pass anintarray as*msg?
I think you can use thesend()system call. But be aware, that thelenis thelength of the message in bytes. So i think for an array of 5int. You need to specify thelenas5*(sizeof(int)). Additionally, on the receiving side, you need to interpret it accordingly. As Naveen pointed out, a more detailed answer to your quest...
it seems that escaped characters passed in write() don't work (at least) properly. ``` printf("test"); printf("\r1234); ``` return ``` 123 ``` as expected, but ``` printf("test"); write(1, "\r1234, 5); ``` return ``` 1234test ``` so the line is not overwritten I would like to know how to erase/overwrite a lin...
Try flushing the output stream: Code: ``` #include <stdio.h> #include <unistd.h> int main() { printf("test"); fflush(stdout); write(1, "\r1234", 5); return 0; } ``` Output: ``` 1234 ```
I am using Code Composer Studio (CCS) for developing an embedded application. It is very helpful if I can use printf to print something on console of CCS. But it is not working. I includedstdio.h. The Code compiles. When I run, I see data in putty, but I see nothing in CCS. Is is possible to see something in console l...
this link:http://processors.wiki.ti.com/index.php/Printf_support_for_MSP430_CCSTUDIO_compiler contains the details on how to use printf() (per some compiler settings in the CCS) to display the results of printf() statements on the CCS console in the 'properties' window, in the 'Library Function Assumptions' sub page...
i want to make statements in for loop condition based on another condition. E.g. Given two numbers a and b, if a>b I want to put condition of i-- and otherwise i++. This can be done with two for statements in if, but I want to do it with one for loop only. something like this.. ``` for(i=a; if(a>b),put i>=b here els...
This was not working on some online compiler. I tried to use it in local machine in codeblocks. It is working as intended. I don't know why it was not working on online compiler.
A code snippet is as follows: ``` struct wer { unsigned int a:5; unsigned int:0; unsigned int b:3; unsigned int c:2; unsigned int:0; }v; ``` I know that all of these are packed bit fields but how to find the storage which would be needed for v.
You can get the storage required forvusingsizeof(v).
I am not trying to use a DPI call, but a simple Verilog program which internally uses its PLI to call a function written in C language. I don't know about static linking. I am using edaplayground. Can anyone tell me which simulator should I use and switch should I pass to link both Verilog and C? Should I include the...
I put your C code in a new file named test.c, and added SV-DPI to your Verilog code, removed dollar sign from $hello task to become a DPI call. See the simulator output and it should be the expected result from your sample code.
``` int var = (1 == 1) ? (5) : (10); ``` This outputs5, which is correct. ``` int var = 100 + (1 == 1) ? (5) : (10); ``` this again outputs5. Why? I know I can fix the problem with adding braces around the entire ternary statement, but that doesn't explain what happens with the addition and why it behaves like t...
In C every non-zero value is “true”, here the value of100 + (1 == 1)is101, which is also “true”, therefore(5)is selected. Since?:has a very low precedence, the parentheses should be((1==1) ? 5 : 10)to have the effect you want.
I have this simple code, and can't figure out how to allocate memory for scanf ``` char* string= (char*) malloc (sizeof(char)); printf("insert string: \n"); scanf("%s", string); free(string); ``` doesn't matter how many chars my string is, it's an error. I want to use malloc for the char*, any way to set memory for ...
You are just request 1 byte. You need to allocate more than that if you want store more than just the0terminator in the string: ``` char* string= malloc (256); //256 bytes, arbitrary value... ``` I removed: sizeof(char)because it's always guaranteed to be1.(char*)because casting the return value ofmalloc()is needle...
i want to make statements in for loop condition based on another condition. E.g. Given two numbers a and b, if a>b I want to put condition of i-- and otherwise i++. This can be done with two for statements in if, but I want to do it with one for loop only. something like this.. ``` for(i=a; if(a>b),put i>=b here els...
This was not working on some online compiler. I tried to use it in local machine in codeblocks. It is working as intended. I don't know why it was not working on online compiler.
A code snippet is as follows: ``` struct wer { unsigned int a:5; unsigned int:0; unsigned int b:3; unsigned int c:2; unsigned int:0; }v; ``` I know that all of these are packed bit fields but how to find the storage which would be needed for v.
You can get the storage required forvusingsizeof(v).
I am not trying to use a DPI call, but a simple Verilog program which internally uses its PLI to call a function written in C language. I don't know about static linking. I am using edaplayground. Can anyone tell me which simulator should I use and switch should I pass to link both Verilog and C? Should I include the...
I put your C code in a new file named test.c, and added SV-DPI to your Verilog code, removed dollar sign from $hello task to become a DPI call. See the simulator output and it should be the expected result from your sample code.
``` int var = (1 == 1) ? (5) : (10); ``` This outputs5, which is correct. ``` int var = 100 + (1 == 1) ? (5) : (10); ``` this again outputs5. Why? I know I can fix the problem with adding braces around the entire ternary statement, but that doesn't explain what happens with the addition and why it behaves like t...
In C every non-zero value is “true”, here the value of100 + (1 == 1)is101, which is also “true”, therefore(5)is selected. Since?:has a very low precedence, the parentheses should be((1==1) ? 5 : 10)to have the effect you want.
I have this simple code, and can't figure out how to allocate memory for scanf ``` char* string= (char*) malloc (sizeof(char)); printf("insert string: \n"); scanf("%s", string); free(string); ``` doesn't matter how many chars my string is, it's an error. I want to use malloc for the char*, any way to set memory for ...
You are just request 1 byte. You need to allocate more than that if you want store more than just the0terminator in the string: ``` char* string= malloc (256); //256 bytes, arbitrary value... ``` I removed: sizeof(char)because it's always guaranteed to be1.(char*)because casting the return value ofmalloc()is needle...
I was wondering if I can create macro that creating value with custom "shift" (or other way to create it in compile time). I mean, concatenate two numbers or something... Something like that (of course it's not working): ``` #define CUSTOM_DOUBLE(shift) 1.05E shift ``` I know I can do: ``` #define CUSTOM_DOUBLE(sh...
As long asshiftargument is passed asinteger constant(of decimal form) this can be accomplished by##operator, that concatenates preprocessing tokens. For instance, it may be implemented as: ``` #include <stdio.h> #define CUSTOM_DOUBLE(shift) (1.05E ## shift) int main(void) { double d = CUSTOM_DOUBLE(3); pri...
I have this simple code for writing to a file in c ``` FILE* fp = fopen ("file.txt", "w+"); fprintf(fp, "bla"); free(fp); ``` i'm getting tons of errors when running valgrind, ``` Address "xxxxxxx" is 192 bytes inside a block of size 568 free'd Address "xxxxxxx" is 168 bytes inside a block of size 568 free'd ``` ...
You should replace free(fp) with fclose(fp). Also check fp for NULL
I have this code ``` char* chars = (char*) malloc (sizeof(char)); memcpy(chars, "", 0); char* hey = "hello doit"; chars = (char*) realloc (chars, 10); memcpy(chars, hey, 10); printf("string: %s\n", chars); free(chars); ``` and I'm getting an error in memory ``` Address "xxxxxxx" is 0 bytes after a block of size 10 ...
10 bytes is not enough to contain"hello doit"including a string terminator. You don't use any string function here, but perhaps there is other code that does. Please show the complete verifiable example. You didn't post the whole code, but have now commented"When I print the string..."(and edited the question as I ty...
Consider the following macro: ``` #define FOO(a,b) (--a)* 8 + (--b); ``` Now ``` int graph[8][8] = { 0 }; int *graph_p = &(graph[0][0]); int *p = graph_p + FOO(2, 3); ``` Why do I get the error: IntelliSense: expression must be a modifiable lvalue
It's because you are passing aninteger constantto function-like macroFOO(a, b), that applies pre-increment--operator to its arguments. The result of this macro expansion looks as: ``` int *p = graph_p + (--2)* 8 + (--3);; ``` which is illegal in C, as operator requires amodifiable lvalueas its operand. Another iss...
I've been tasked to build a Cocoa interface for a C terminal application. There are no requirments other than the GUI. My question is: Would it be best and/or fastest to make the terminal calls or get source code (which I do have authorization to use) and call the functions directly from Cocoa? Please state pros a...
It would be best (faster, easier) to call the functions directly from Cocoa. Of course you realise that Cocoa apps must be Sandboxed if they are going on the Mac App Store and Sandboxing can make many, previously trivial, operations much more complicated?
I would like parse two numbers. From a RTC IC I get 7 bits, where bit 6, 5, 4 are upper digits (first digit in number of seconds 0 - 5) and bits 3, 2, 1, 0 are unit digits (0 - 9). Now I would like to create a function that parses these two numbers and return the number of seconds. Here is a table of the second numb...
It's pretty straightforward, just split the bits as documented : ``` uint8_t i = getBcd(); return (i >> 4 & 0x7) * 10 + (i & 0xf); ```
My sourcecode: ``` #include <stdio.h> int main() { char myArray[150]; int n = sizeof(myArray); for(int i = 0; i < n; i++) { myArray[i] = i + 1; printf("%d\n", myArray[i]); } return 0; } ``` I'm using Ubuntu 14 and gcc to compile it, what it prints out is: ``` 1 2 3 ... 125...
intvalue of acharcan range from 0 to 255 or -127 to 127, depending on implementation. Therefore once the value reaches 127 in your case, it overflows and you get negative value as output.