question
stringlengths
25
894
answer
stringlengths
4
863
``` main() { int a,b=0,c=1,d=1; a=++b&&++c||++d; printf("%d %d %d",b,c,d); //1 2 1 b=0,c=1,d=1; a=b&&++c||++d; printf("%d %d %d",b,c,d); //0 1 2 } ``` Why second printf gives answer 0 1 2 instead of 0 2 1 ?
Why second printf gives answer 0 1 2 instead of 0 2 1 ? &&isshort-circuiting. In ``` a=b&&++c||++d; ``` ++cwill not be evaluated ifbis0which is the case here. Hencecis1instead of2.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed7 years ago.Improve this question In LISP, Ruby, Tcl, and several other dynamic languages, the procedure/method/function returns by default, the last value. I.e., there is no need to explicitly use the return command in the last evaluated statement.Is there a C variant with the same functionality?
There are no C "variants"; there is C, and there are other languages. And C doesn't do as you wish. For what it's worth, I don't think that style of programming is very clear at all.I propose you re-evaluate whether youreallywant to use it.
The sizeof(char) in C gives 1 and sizeof("a") gives 2. Please help
Achari.e. a character has size 1. Thestring literal"a"isnota character. It is a "string" (and by string I meanchar[]). All "strings" in C are null-terminated, so your "string" is actually: ``` {'a','\0'} ``` And that's two characters. So size is 2.
Is it possible to write a new format specifier in C? For example, let's say, %g is a format specifier which prints the ip address in A.B.C.D format from the unsigned integer equivalent. ``` int ip_addr = Some integer printf("ip address = %g", ip_addr); ``` output: prints ip address in A.B.C.D format
You would have to reimplement the printf function (more precisely its format parsing function). What you can do is wrap printf inside a function that supports ip addresses or do this: ``` #define FMT_IP "%d.%d.%d.%d" #define FMT_IP_ARG(ip) getA(ip), getB(ip), getC(ip), getD(ip) ``` Where the getX functions or macros get the X part of the given integer representing an IP address. Then: ``` printf("ip address = " FMT_IP "\n", FMT_IP_ARG(ip)); ```
i'm trying to take a user's input and check if it is equal to some option('+','-','*','x') ``` do { printf("Select the op.: "); scanf("%c", &option); } while (option != '+' || option != '-' || option != '*' || option != 'x'); printf("%c", option); ``` This is the output: ``` Select the op.:Select the op.:Select the op.:Select the op.: ``` As you can see theprintf("Select the op.: ")is executed multiple times and I cannot understand the reason, thus if I try to insert, eg+, this is the print output: ``` ++ ``` Thanks in advance
``` while(option != '+' || option != '-' || option != '*' || option != 'x'); ``` This condition is always true.
I have a struct in C that looks like this: ``` struct Database { int row_size; int name_size; struct Address *; }; ``` This struct will be put into the heap via a malloc(...) call. I will then havestruct Address*point to another region in the heap via another malloc(...) call. If I use fwrite(...) to write this struct to disk, what will happen? Will fwrite(...) automatically follow (or dereference) the pointerstruct Address *, or will it simply copy the pointer itself (which would be useless) to disk?
fwrite will write the memory content of your structure, meaning it will simply copy the pointer itself to disk, which would be useless in your own term.
Environment As per my understandingNetwork layeris responsible for reassembly of fragmented datagrams and then it supplies the reassembled data to upperTransport layer. I have collected packet traces usinglibpcapand i want to reassemble fragmented packets at layer 3 on my own. This linksays that i need fragment flag, fragment offset, identification number and buffer value for reassembly of segments. Question At the arrival of first segment how to know what should be size of buffer to be initialized for complete reassembly of datagram. Thanks.
The IP header only gives you the size of the fragment. So you need to reserve a buffer the size of the largest possible IP packet, i.e. 65535 bytes. Only once you get the last fragment can you determine the length of the complete packet.
When I execute a C program in vim using:!./%<, I would like to be able to see my code (on the left side of a split screen), as well as the stdout results from the execution of the program (on the right side of the split screen). At the moment, the output of the program execution is blocking the view of my code until I hitENTER, but then I can no longer see the program output. How do I execute a C program in vim so that I can see both of its code and its execution results together on a split screen ?? I tried piping the output using:!./%<|vert copen, but failed. I am using Linux. Any help will be much appreciated.
Installvimshellthen type:VimShellInteractiveto transform a vim window (a split for example) into an instance of a shell where you can still use vim commands.
``` #include <stdio.h> #define all_mem (sizeof(x) /sizeof(x[0])) int x[] ={1,2,3,4,5,6,7,8,9,10}; int main(void) { // printf("The condition is %d",(all_mem-2)); int i; for(i=-1;i<=(all_mem-2);i++) { printf("The number is %d",i); } return 0; } ``` In the above code for loop is not even executing for a single time, i tried printing condition and its satisfies for loop condition. Any insights how macro expression in for loop condition is evaluated to the value less than -1?
Theall_memmacro is returning asize_tvalue; integer promotion rules mean the comparison ofi <= (all_mem - 2)is promotingito asize_t, which means the value is huge, rather than-1. Try casting to ensure signed comparison: ``` for(i = -1; i <=(ssize_t)(all_mem- 2); ++i) ```
This question already has answers here:Why does non-equality check of one variable against many values always return true?(3 answers)Why does the message print twice?(4 answers)Closed7 years ago. I have the following piece of code. I want a user to enteraorrand continue executing the program, or try to get user input if he enters something else. But my problem is, when I enter an illegal value the program shows the message twice, and not just once. How can I make the message only ever show once? ``` label: puts ("a/r?"); c = getchar (); if (c != 'a' || c != 'r') goto label; ```
You should use:if (c != 'a' && c != 'r') Also to avoid duplicated messages you should replacegetchar()withscanf("%c", &c)
I have the followingfor loopinCthat I want to mimic in Python: ``` for (index = 0; index < n; ++index) { for (i = 0, j = index; j < n; ++i, ++j) { 'do something' } } ``` Is there a more elegant/Pythonic way to do this, or do I have to declare a variable outside of the loop like so: ``` for index in range(m): i = 0 for j in range(index, m): 'do something' i += 1 ```
It's hard to say without knowing more about what is going in the second loop, but as it's written I would say: ``` for index in range(n): for i,j in enumerate(range(index,n)): 'do something' ``` would be the way you'd do that.
I have this problem in a bigger project, in which for some reason thereallocfunction does absolutely nothing. Am I missing something obvious? Here is a simplified example: ``` #include <stdio.h> #include <string.h> int main() { int x = 1, y = 2, z = 3; int* arr, *arr1; int** arra; arra = (int**)malloc(sizeof(int*)); arr = (int*)malloc(sizeof(int)); arr[0] = x; arra[0] = arr; arra = (int*)realloc(arra, sizeof(int*) + sizeof(int*)); arr1 = (int*)malloc(sizeof(int)); arr1[0] = y; arra[1] = arr1; } ``` When I debugged, the finalarrawas{{1}}, even though to my understanding it should be{{1},{2}}.
The debugger does not know thatarrais any more than a single pointer. If you want the debugger to print out the contents ofarraas an array, you need to walk the elements yourself, or cast it to an array type before printing.
The existence of a macro named__func__is part of C99 and its intent is clear but is the exact text that it expands to within a given function standardized?
Yes. The macro is defined to expand to the name of the function. C11, §6.4.2.2 The identifier _func_ shall be implicitly declared by the translator as if immediately following the opening brace of each function definition, the declarationstatic const char _func_[] = "function-name";appeared, where function-name is the name of the lexically-enclosing function. The standard describes it as equivalent to having astring literalwith the exact function name. So I don't think there is any other interpretation of that.
I'd like to use ls from execl and redirect the output to a file, which exists. I tried with this: int value = execl("/bin/ls","ls","-l",">/home/sbam/myfile",NULL); But it doesn't work... How can I do? Thanks.
Redirection is part of the shell and not something the commands handles. Either invoke a shell and execute the command through the shell, or you could open the file usingopenand usedup2to make the file the process standard output. Something like ``` int fd = open("/home/sbam/myfile", O_CREAT | O_WRONLY, 0644); if (fd != -1) { if (dup2(fd, STDOUT_FILENO) != -1) { if (execl("/bin/ls", "ls", "-l", NULL) == -1) perror("execl"); } else perror("dup2"); } else perror("open"); ```
So, i have been trying to create program that i failed to do in a test. It should be capable of 1) searching a word in substring. I got that part with some help down. Now comes the part where user inputs a number(here its a k), and the program prints out the words in front of/behind the word in string. I think it should be done by counting characters(here an s) until i encounter one more Space character than is the value of the input number(should be m). For some reason however, when this loop ends, the s is always equal to m. ``` for(int h = 0; h < 100; h++){ if (*(found+h) = ' '){ m++; } s++; if(m > k){ break; } } ```
``` if (*(found+h) = ' '){ ``` should be ``` if (*(found+h) == ' '){ ``` you need a test for equality.
I've defined a macro to set my values(C code), for example: ``` .h file typedef struct { uint8_t details; uint8_t info[20]; } values_struct; #define INIT_VALUES_STRUCT(X) values_struct X = {.details = 0x00, .info = { 0x01 } } .c file INIT_VALUES_STRUCT(pro_struct); ``` but I need to set a "struct array" like: ``` values_struct pro_struct[10]; ``` and to set default values with a macro, it's possible and how I can do that?
Redefine that macro as ``` #define INIT_VALUES_STRUCT {.details = 0x00, .info = { 0x01 } } ``` And then you can have ``` struct values_struct pro_struct = INIT_VALUES_STRUCT; struct values_struct pro_struct_arr[] = { INIT_VALUES_STRUCT, INIT_VALUES_STRUCT, INIT_VALUES_STRUCT }; ```
I tried to replace characters with substraction. It works but it leaves a blank with this method: ``` #include <stdio.h> int main(void) { int c; while((c = getchar()) != EOF) { if (c == '\t') putchar('t'); if(c == '\t') c = c - '\t'; putchar(c); } } ``` Its the substraction that gives the unwanted output and I couldn't figure out why. Example input: Hello tab tab tab Output: Hello tabt tabt tab Goal is Hello tabttabttab.
The "blank" is the result of printing NUL (0) character. Whenever you input'\t', you are printing NUL, which is not a printable character. ``` if(c == '\t') c = c - '\t'; putchar(c); // same as putchar(0); if c == '\t' ``` Perhaps, you wanted to replace tabs with-: ``` if(c == '\t') c = '-'; putchar(c); ```
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.Closed7 years ago.Improve this question I am new to C and I would like to know if it is possible to make colorful console menus with simple graphics, like old DOS programs used to look. I am programming on Windows PC and portability is not important for this one.
Take a look atPDCurseswhich is a dos/windows curses implementation (curses does all the console richness in unix/linux environments).
Suppose we have 2 files 1) file1.c ``` int Appples[10]; ``` 2) file2.c ``` extern int *Appples; ``` Is there any prob with this type of declaration except that i will have to handle size independently ?
This is covered inC FAQs 6.1 The type pointer-to-type-T is not the same as array-of-type-T. Use extern char a[]. whilethis answeraddresses the issue more specifically. The final point is: an array isn't a pointer and you shouldn't treat one as such.
For example, I need a char array with contains theNUL '\0'character followed by char '1'. Initializing the char array as: ``` char *str = "foo\01bar"; ``` result in the following equivalent hex representation: ``` <hex values of foo> 0x1 <hex values of bar>` ``` whereas I require: ``` <hex values of foo> 0x0 <hex value of char '1'> <hex values of bar> ``` How to define such char array (in thechar *str = <mycustomarray>;way); I know, that having a modified append routine which also appends the NUL character will do the trick, but I'm not interested in that.
From the C++ Standard: octal-escape-sequence:\ octal-digit\ octal-digit octal-digit\ octal-digit octal-digit octal-digit You can use: ``` char *str = "foo\0001bar"; ``` or ``` char *str = "foo\0" "1bar"; ```
I found that a single-linelanguage: c.travis.yml file basically does all I need, with the exception that I don't wantmake testto happen. Is there a way I could make Travis just run./configure && make?
Have you tried overriding the default test script as described in:https://docs.travis-ci.com/user/languages/c#Default-Test-Script? Something like: ``` script: ./configure && make ```
I have a memory address integer like this 0x80480ac and i want to assign it a char * like this: ``` char *address="\x08\x04\x80\xac"; ``` How can i do it?
I believe you are looking for: ``` char * address = (char *)0x080480ac; ```
Suppose we have 2 files 1) file1.c ``` int Appples[10]; ``` 2) file2.c ``` extern int *Appples; ``` Is there any prob with this type of declaration except that i will have to handle size independently ?
This is covered inC FAQs 6.1 The type pointer-to-type-T is not the same as array-of-type-T. Use extern char a[]. whilethis answeraddresses the issue more specifically. The final point is: an array isn't a pointer and you shouldn't treat one as such.
For example, I need a char array with contains theNUL '\0'character followed by char '1'. Initializing the char array as: ``` char *str = "foo\01bar"; ``` result in the following equivalent hex representation: ``` <hex values of foo> 0x1 <hex values of bar>` ``` whereas I require: ``` <hex values of foo> 0x0 <hex value of char '1'> <hex values of bar> ``` How to define such char array (in thechar *str = <mycustomarray>;way); I know, that having a modified append routine which also appends the NUL character will do the trick, but I'm not interested in that.
From the C++ Standard: octal-escape-sequence:\ octal-digit\ octal-digit octal-digit\ octal-digit octal-digit octal-digit You can use: ``` char *str = "foo\0001bar"; ``` or ``` char *str = "foo\0" "1bar"; ```
I found that a single-linelanguage: c.travis.yml file basically does all I need, with the exception that I don't wantmake testto happen. Is there a way I could make Travis just run./configure && make?
Have you tried overriding the default test script as described in:https://docs.travis-ci.com/user/languages/c#Default-Test-Script? Something like: ``` script: ./configure && make ```
I have a memory address integer like this 0x80480ac and i want to assign it a char * like this: ``` char *address="\x08\x04\x80\xac"; ``` How can i do it?
I believe you are looking for: ``` char * address = (char *)0x080480ac; ```
I want a method, that fix umlauts (äöü) for a german console application ``` #define oe (unsigned char)148 [...] char* fixUmlauts(char string[]) { for(int i = 0; i < strlen(string); i++) { switch(string[i]) { [...] case 'ö': string[i] = oe; break; [...] } } return string; } ``` But I get an error while I run this: ``` printf(fixUmlauts("Hallöle\n")); ``` Access Violation when writing at position 0x01276BE4. What is wrong?
You can't modify a string literalHallöle\n. You should copy it into achararray and then modify that: ``` char string[] = "Hallöle\n"; fixUmlauts(string); ```
Can someone explain mecmpfuncwhich is used in theqsortfunction? What areaandbin this function and what are they pointing to? ``` int cmpfunc(const void *a, const void *b) { return(*(int*)a - *(int*)b); } ```
aandbincmpfuncare pointers toconst voidtype.cmpfunccan accept pointer to elements of array of any data type.void *pointer can't be dereferenced, therefore a castint *is needed before dereferencing.
I am reading multiple floating numbers from a single scanf output. ``` #include<stdio.h> #include<math.h> int main() { float a,b,c; float d,rot1,rot2; scanf("%f%f%f ", &a, &b, &c); d = sqrt(b*b - 4*a*c); rot1 = (-b-d)/(2*a); rot2 = (-b+d)/(2*a); printf("%f %f", rot1, rot2); return 0; } ``` It takes 4 inputs; however, I want to take only 3 inputs for the addresses of variables a, b and c. I don't know which variable it takes the extra input from. When I wrote code for taking input for 2 variable, then it takes 3 inputs.
``` scanf("%f%f%f ", &a, &b, &c); ^ ``` Remove this extra space after%f. Note- You should make sure that expression insqrtdoes not evaluate to negative number. You probably want to avoid that condition.
I'm using NetBeans IDE 8.0.2. When I set up a project I choose the option for c/c++ application. However, when I compile my code it appears to be running a c++ compiler ``` (g++ -c -g -std=c++11 -MMD -MP -MF) ``` instead of a c compiler. When I go to "Project Properties" under "Build" I see I can set options for a "c compiler" "c++ compiler" and "FORTRAN Compiler". However I don't see how I am supposed to select among these as to switch the code from compiling in c++ to compiling in c (with the settings specified on the "c compiler" tab") instead of c++.
From what I could gather online, Netbeans selects the compiler by file type, not project. So you need to remove yourmain.cppand add amain.cinstead (cfAdding New Filesfrom the tutorial).
``` #define sblock(sb, wf) ((sb)->sb_flags & SB_LOCK ? \ (((wf) == M_WAITOK) ? sb_lock(sb) : EWOULDBLOCK) : \ ((sb)->sb_flags |= SB_LOCK), 0) ``` I can't understand the last element "((sb)->sb_flags |= SB_LOCK), 0)". The "0" seems unnecessary to me.
As it seems, the idea here is to return0as the expression result once the side-effects of the statement((sb)->sb_flags |= SB_LOCK)were executed. TheC comma operatoris evaluating it's left side discarding the result, and returning the right side.
I want to create a cross platform (windows, mac, linux) C application that is capable of spawning a subprocess and capturing the stdin, stdout and stderr simultaneously. I know it's possible to do something like this withpopenin unix,StackOverflow and in windows with the WinAPI,MSDN I also understand that it is possible to redirect the outputs to files and read from there, but redirecting the standard pipes does seem like a very basic standard library feature. Did I miss a basic function and/or is there any lightweight crossplatform library that I can use to achieve this goal without significant complexity?
The glib library provides what you want. Here is the documentation of its process API:https://developer.gnome.org/glib/stable/glib-Spawning-Processes.html
I have a BASE64 encode string: ``` static const unsigned char base64_test_enc[] = "VGVzdCBzdHJpbmcgZm9yIGEgc3RhY2tvdmVyZmxvdy5jb20gcXVlc3Rpb24="; ``` It does not have CRLF-per-72 characters. How to calculate a decoded message length?
Well, base64 represents 3 bytes in 4 characters... so to start with you just need to divide by 4 and multiply by 3. You then need to account forpadding: If the text ends with"=="you need to subtract 2 bytes (as the last group of 4 characters only represents 1 byte)If the text ends with just"="you need to subtract 1 byte (as the last group of 4 characters represents 2 bytes)If the text doesn't end with padding at all, you don't need to subtract anything (as the last group of 4 characters represents 3 bytes as normal)
I am writing a project that I have to write only a part of it, the problem is that under an if condition I want to call a function that someone else writes. I have the prototype of that function but I don't have its body. so the linker gives me an error. Is it possible to compile the code without commenting the function call? Here is the code i am trying to compile, any help is appreciated. ``` #include <stdio.h> void foo(void); int main(void) { char c = getchar(); if (c=='a'){ foo(); } return 0; } ```
Is it possible to compile the code without commenting the function call? Yes. You just need to compile it without linking it. For example, using gcc's-coption: ``` gcc -c foo.c -o foo ```
I have a program which does a lot of work. I want to log all the console prints into a file. So i used a tee with my executable. I implemented a tee which reads from stdin and writes to stdout and a file. exec run.sh | tee loglink But what i could see is, time to get the login for my program, which used to be 3 mins now is taking 6 mins. What is the reason for this delay? I commented file operation part of my tee, still seeing the same delay. Is it the pipeline that is causing this issue? Adding code, ``` char ch; fd = open(file_name, O_WRONLY | O_APPEND, 0664); while(read(STDIN_FILENO, &ch, 1) > 0) { write(STDOUT_FILENO, &ch, 1); //write to console fflush(stdout); write(fd, &ch, 1); //write to the file } ```
``` read(STDIN_FILENO, &ch, 1) ``` You only read 1 byte per read call. it is very very slow, please increase the buffer, and read as more as you can per read call
I had code below gives error ``` #define ONE_SAMPLE 6 #define DATA_BUFF 100 int main() { unsigned int total; for (ONE_SAMPLE=0;ONE_SAMPLE<DATA_BUFF;ONE_SAMPLE++) { total=ONE_SAMPLE*DATA_BUFF; i2cread(read function of sensor); } } ``` for loop saying expression must be a modifiable value.
You are definingONE_SAMPLEto be6 ``` #define ONE_SAMPLE 6 ``` and then using incrementing that in the loop When the preprocessor has done its job, the loop will look like this ``` for (6=0;6<100;6++) { total=6*100; i2cread(read function of sensor); } ``` The expressions6=0does not make any sense. It is trying to assign0to a constant6. Constants are notassignable l-value. That is why you are getting this error.
This question already has answers here:Removing trailing newline character from fgets() input(15 answers)Closed7 years ago. I want to trim newline character from fgets output. ``` while(fgets(buff,1024,fp) ){ printf("start%send",buff ); ``` If there is a line "C is cool", in the file . Then the above code prints. ``` startC is cool end ``` But I want it to print like ``` startC is coolend ``` How to do that
Clean approach ``` #include <string.h> //... buff [ strcspn(buff, "\r\n") ] = 0; ``` This will work safely for any flavour of line endings, even if there is none present, and even if the string is empty.
``` #define sblock(sb, wf) ((sb)->sb_flags & SB_LOCK ? \ (((wf) == M_WAITOK) ? sb_lock(sb) : EWOULDBLOCK) : \ ((sb)->sb_flags |= SB_LOCK), 0) ``` I can't understand the last element "((sb)->sb_flags |= SB_LOCK), 0)". The "0" seems unnecessary to me.
As it seems, the idea here is to return0as the expression result once the side-effects of the statement((sb)->sb_flags |= SB_LOCK)were executed. TheC comma operatoris evaluating it's left side discarding the result, and returning the right side.
I want to create a cross platform (windows, mac, linux) C application that is capable of spawning a subprocess and capturing the stdin, stdout and stderr simultaneously. I know it's possible to do something like this withpopenin unix,StackOverflow and in windows with the WinAPI,MSDN I also understand that it is possible to redirect the outputs to files and read from there, but redirecting the standard pipes does seem like a very basic standard library feature. Did I miss a basic function and/or is there any lightweight crossplatform library that I can use to achieve this goal without significant complexity?
The glib library provides what you want. Here is the documentation of its process API:https://developer.gnome.org/glib/stable/glib-Spawning-Processes.html
I have a BASE64 encode string: ``` static const unsigned char base64_test_enc[] = "VGVzdCBzdHJpbmcgZm9yIGEgc3RhY2tvdmVyZmxvdy5jb20gcXVlc3Rpb24="; ``` It does not have CRLF-per-72 characters. How to calculate a decoded message length?
Well, base64 represents 3 bytes in 4 characters... so to start with you just need to divide by 4 and multiply by 3. You then need to account forpadding: If the text ends with"=="you need to subtract 2 bytes (as the last group of 4 characters only represents 1 byte)If the text ends with just"="you need to subtract 1 byte (as the last group of 4 characters represents 2 bytes)If the text doesn't end with padding at all, you don't need to subtract anything (as the last group of 4 characters represents 3 bytes as normal)
I am writing a project that I have to write only a part of it, the problem is that under an if condition I want to call a function that someone else writes. I have the prototype of that function but I don't have its body. so the linker gives me an error. Is it possible to compile the code without commenting the function call? Here is the code i am trying to compile, any help is appreciated. ``` #include <stdio.h> void foo(void); int main(void) { char c = getchar(); if (c=='a'){ foo(); } return 0; } ```
Is it possible to compile the code without commenting the function call? Yes. You just need to compile it without linking it. For example, using gcc's-coption: ``` gcc -c foo.c -o foo ```
I typed in this code: ``` char *a; char b = 'd'; a = b; printf("%c", a); ``` Output - 'd'. My query is that sinceais pointer variable, it is supposed to store address. Why in this case is it storing character value?
sinceais pointer variable, it is supposed to store address A pointer variable can store numeric values, too. On most systems a pointer variable could store anint, although there is no explicit guarantee of this. However, a pointer variable is capable of storing a value of typecharon all systems. then why in this case is it storing character value? Because you told it to do so. Storing a value in a pointer does not make that value an address. Note:your code has undefined behavior. The reason the code produces the output that you expect is that a pointer representation on your system happens to be compatible with that of anint, which is what%cexpects.
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.Closed7 years ago.Improve this question I want to extract only strings between<AAA> and </AAA>how can i extract those? please helpExample :<AAA>hello world</AAA>this is a text<AAA>this is another text</AAA>Result :hello world this is another text
Follow these steps: Read the whole file into achararray, reallocating this array if needed, null terminate the array.Usestrstr()to find an occurrence of"<AAA>". save position if found, done if not.From that position, usestrstrto find"</AAA>".output the text in between and restart.
In the legacy Mongo C driver there was a a functionmongo_find_one, which was used to find a single document in a MongoDB server. ``` MONGO_EXPORT int mongo_find_one( mongo *conn, const char *ns, const bson *query,const bson *fields, bson *out ); ``` Is there a similar function in the new Mongo driver. I have been using the following documentation but was not able to find anything that is equivalent. http://api.mongodb.org/c/1.2.0/
This is likely an unsatisfying answer, but it does not appear there is a direct equivalent of themongo_find_onefunction in version 1.2.0. It should not however be particularly difficult to build a function with similar semantics using a cursor and taking only a single element from it and discarding the rest.
Prior to version 1.0.16 of libusb, libusb_get_device_descriptor() would return 0 for success or a negative integer to indicate failure. With version 1.0.16 and later, this function always returns 0. How do I detect and figure out why I fail to get a descriptor now that that convenient means of figuring it out is gone?
Documentation explicitly states that Note since libusb-1.0.16, LIBUSB_API_VERSION >= 0x01000102, this function always succeeds. This means you should never fail to get descriptor.
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.Closed7 years ago.Improve this question So I have a simple set of code: ``` #include <stdio.h> int main() { char x[3] = "ABC"; // (*) puts(x); return 0; } ``` It returns a strange output: ``` ABC¬ a ``` Using the top answer fromthis question, I found that when I changex[3]tox[4]everything runs fine. But why? Why do I get a strange output onx[3], and why isx[4]fine?
There is no space for the terminating\0. In fact I would expect compilation to fail in such case. Try ``` char x[4] = "ABC"; ``` Or, as@Zetasuggested, just ``` char x[] = "ABC"; ```
i am tryaing to create an array of structures from an input i get like if the user enter 5 so i need to bulid 5 structures and initializing them this is my sturct in a header file ``` typedef struct abc { pnt* head; int number; int number2; float sum; }abc; ``` and in my main file i put ``` abc *t; printf_s("How many strucures?:\n"); scanf_s("%d", &stru); for (i = 0; i < stru; i++) { t[i].head = NULL; t[i].number = 0; t[i].number2 = i; t[i].sum = 0; } ``` and i get "uninitialized local variable 't' used"
``` abc *t; ``` heretis a pointer and it is not initialized. To initialize it: ``` scanf("%d", &stru); t = malloc(stru * sizeof *t) ```
I'm trying to make a C program which accepts two character consecutively and then print them, but I'm getting some anomaly in the output. The program ``` #include<stdio.h> int main() { char c1, c2; printf("\n Enter two characters : "); scanf("%c%c", &c1, &c2); printf("\n The the characters are %c and %c ", c1, c2); return 0; } ``` The output Enter two characters : aThe the characters are a and In the output without asking for the second character it is directly going to the nextprintf()statement. Why is this happening?
Use the following: ``` scanf(" %c %c", &c1, &c2); /* ^ ^ */ ``` When you hit return key after first character,'\n'is read inb. Using space before%cinstructs to ignore any white-space(space, tab, newline etc). Further read:What does space in scanf mean
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.Closed7 years ago.Improve this question I'm trying to use strcat 2 time in a row.when I compile first 2 lines it's works, but when I added the third line I get:"Error LNK2019 unresolved external symbol _srtcat referenced in function _StartUpFunc " ``` strcpy(msg2sent, "Hello"); strcat(msg2sent, temp_username); srtcat(msg2sent, ", welcome to the session."); ``` what can be the reason? Im using VS15
The third time, you spelled itsrtcat. Correct tostrcat.
This question already has answers here:unexpected output in C (recursion)(3 answers)Closed7 years ago. ``` #include <stdio.h> int main() { static int i = 5; if(--i){ main(); printf("%d,", i); } return 0; } ``` I'm unable to find why the value ofiis becoming 0 every time.
There is arecursive calltomain()in your code, tillif(--i)is not down to 0. The print statement does not get a chance to execute. Onceibecomes zero, the control returns, and the value ofi, is, well, 0, then. [I don't have a photo editor handy right now, sorry], Try to have a look at the rough graphics to get an idea. FWIW,iis havingstaticstorage, so itholdsthe valueacrossfunction calls. (I assumed the last part is already understood, just adding for sake of clarity.)
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed7 years ago.Improve this question I'm just start to study C programming language. I was recommended to use Visual Studio 2015 as modern editor and compiler. Can it work for just C?
The answer to your question isyesit can. Seeherefor more details, and other languages that are supported. However, many start programming in C without an IDE. Although, it can help you troubleshoot syntactical errors, you'll find that its most likely going to get in the way. If you're new to programming; C is a great language to start with. I would recommend watchingCS50. Happy programming.
I typed in this code: ``` char *a; char b = 'd'; a = b; printf("%c", a); ``` Output - 'd'. My query is that sinceais pointer variable, it is supposed to store address. Why in this case is it storing character value?
sinceais pointer variable, it is supposed to store address A pointer variable can store numeric values, too. On most systems a pointer variable could store anint, although there is no explicit guarantee of this. However, a pointer variable is capable of storing a value of typecharon all systems. then why in this case is it storing character value? Because you told it to do so. Storing a value in a pointer does not make that value an address. Note:your code has undefined behavior. The reason the code produces the output that you expect is that a pointer representation on your system happens to be compatible with that of anint, which is what%cexpects.
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed7 years ago.Improve this question I've been trying to get an output as -- ``` ***** **** *** ** * ``` in separate lines, but instead Xcode is showing 5 stars in every line. How to get a decremented value of function j ? ``` #include <stdio.h> int main() { int i,j; for(i=1;i<=5;i++) { for(j=5;j>=1;j--) { printf("*"); } printf("\n"); } return 0; } ```
Change ``` for(j = 5;j >= 1; j--) ``` to ``` for(j = 5;j >= i; j--) ``` See theDemo
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question What standards document(s) specify the behavior of the C and/or C++ pre-processors? Wikipedia suggestshttp://www.open-std.org/JTC1/SC22/WG14/www/standardsis valid for C99. Is it? What about C++ flavours?
The C language standard (ISO/IEC 9899) specifies how the preprocessor behaves in C. The C++ standard (ISO/IEC 14882) specifies how the preprocessor behaves in C++.
in the K&R book the following is given as initial (and correct) function to copy a string ``` void strcpy (char *s, char *t) { while ( (*s++ = *t++) != '\0') ; } ``` Then it's said that an equivalent function would be ``` void strcpy (char *s, char *t) { while (*s++ = *t++) ; } ``` I don't understand how the while loop can stop in the second case. Thanks
The simple assignment expression has two effects: 1) stores the value to the lvalue on the left hand side (this is known as a 'side-effect') 2) the expression itself evaluates to a value - the value of what assigned to that lvalue Awhileloop will repeat until its condition evaluates to 0. So the loop in the second example runs until the value 0 is assigned to the destination string.
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.Closed7 years ago.Improve this question I have a C::B project which evaluates a mathematical expression using a stack Linked List, with several source files and header files. I need to export this project to a Dynamically Linked Library. I already know how to create a DLL on C::B, however, I have no idea how to export an existing project as a DLL. How can this be done?
You can change how your project is exported by going to the project properties (project->properties) then going to the tab build targets. Here you will see all build targets of your current project. You'll notice this menu has a field named "type". If you change this field to "Dynamic Library" your project will compile as a .dll on windows, or as a .so on Linux.
i have the following piece of code ``` int nArgs; if (LPWSTR * const szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs)) { PySys_SetArgvEx(nArgs, szArglist, false); LocalFree(szArglist); } ``` I cannot find in Pythondocumentationif memory pointed by szArglist shall be preserved until Python is shutdown or i can free it immediately. Can anybody put some light on this, please? Thank you! Vladimir
The Python C API looks like it is using a new PyList object to fill out the args, and is allocating its own memory for the char* arguments. On strings longer than 1 characters, PySys_SetArgvEx will malloc its own memory for the string. So it's safe to delete any memory allocated that you passed to PySys_SetArgvEx.
I have the following code, is it possible to store theipconfigresult in a file. Please help me with this ``` #include<stdlib.h> int main() { system("C:\\Windows\\System32\\ipconfig"); return 0; } ``` theipconfigresults to be saved to a text file calledip.txtPlease help me with this. THANKS in ADVANCE
try this: ``` system("C:\\Windows\\System32\\ipconfig > myfile.txt"); ``` Edit: If you want bothstdoutandstderrplaced in the file (thanks to and upon comment of @user3629249) : ``` system("C:\\Windows\\System32\\ipconfig 2>&1 myfile.txt"); ``` Edit 2: If you want to know more about redirection, check the microsoft'sredirection operators tutorial.
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed7 years ago.Improve this question hi i have the following code ``` int main() { system("netsh interface ip show addresses"); } ``` and the output in the console to be written to a text file or else to a variable. pleaase help me out with this. THANKS in ADVANCE
if you use Linux, try this: ``` system("netsh interface ip show addresses > /path/to/file 2>&1 "); ```
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed7 years ago.Improve this question I am trying to compile c code in c++ and I get this error! Illegal character(0x1)، Why this error occurred?
May be you have copied the code from the Internet! Try typing it. It will improve your coding ability.
I want to display "string pointer affected" but I get an error. Here is my code: ``` #include<stdio.h> main() { char* *p; char * s="string pointer affected"; *p=s; printf("%s",*p); } ```
pdoesn't point to any known location, so writing to*pis a bad idea. You mean to say: ``` p = &s; ```
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed7 years ago.Improve this question I am trying to compile c code in c++ and I get this error! Illegal character(0x1)، Why this error occurred?
May be you have copied the code from the Internet! Try typing it. It will improve your coding ability.
I want to display "string pointer affected" but I get an error. Here is my code: ``` #include<stdio.h> main() { char* *p; char * s="string pointer affected"; *p=s; printf("%s",*p); } ```
pdoesn't point to any known location, so writing to*pis a bad idea. You mean to say: ``` p = &s; ```
``` root@ubuntu:~/DH$ cat E1-6.c #include<stdio.h> main() { int c; while(c = (getchar() != EOF)) { printf("HI: %d",c); //putchar(c); } } root@ubuntu:~/DH$ cc E1-6.c root@ubuntu:~/DH$ ./a.out 1 HI: 1HI: 1 ``` I gave input as 1 using key board but in output it is displayed twice. Can someone please explain what's happening here?
The error happens because, as the comments noted, the "1" is a key and the "enter" press after the 1 (orCtrl-DforEOF) is another key. As for why both are printing out "1", it is because you are settingcto be the boolean (true/false) value ofgetchar() != EOF. What I think you want is ``` while ((c = getchar()) != EOF) ``` at the top if your loop. That will save the pressed key intocand then check for EOF.
Here's mymain ``` char* name = GetString(); if(name != NULL) { for(int i = 0, j = strlen(name); i < j; i++) { if(!isalpha(name[i-1]) && isalpha(name[i])) printf("%c", toupper(name[i])); } printf("\n"); } ``` The program works pretty good; it passed all the (check50) tests. But I'm worried about a possible bug and that is wheni = 0, could the value stored inname[-1]be an alpha character? Note: theGetString()function returns a string entered by the user.
Fori = 0,name[i-1]is accessing unallocated memory and it will lead to undefined behavior. Change loop counter toi = 1instead ofi = 0. As mentioned in comments you need to check the condition fori =0outside the loop.
``` #include<stdio.h> #include<stdlib.h> struct bt{ struct bt *left; int data; struct bt *right; }; struct bt *root,*p1 = NULL; struct bt* create_bt(struct bt*); main(){ p1 = create_bt(root); printf("Binary tree created\n"); } struct bt* create_bt(struct bt *root){ int a; printf("Enter data:"); scanf("%d",&a); if(a == -1){ root = NULL; } else{ root = (struct bt*)malloc(sizeof(struct bt)); root -> data = a; root -> left = create_bt(root -> left); root -> right = create_bt(root -> right); printf("%d\n",root -> data); p1 = root; } return p1; } ```
The statement:p1 = root;in the else part should be outside of the else statement so that ifa==-1then it returns NULL and the left/right child gets marked as NULL. Apart from that your code seems to be correct in building the binary tree. Hope this helps.
When destroying a widget in GTK3, is it necessary (or good practice) to hide it first? ``` GtkWidget *widgetPointer = gtk_entry_new(); gtk_widget_hide(widgetPointer); /* Is it necessary to call this first? */ gtk_widget_destroy(widgetPointer); ```
It's not necessary, and not customary. That it's not necessary you can find out by just trying it ;-) The explanation behind it is that when a widget is destroyed, it is first removed from its parent container, which effectively hides it first; and widgets generally don't render themselves onto the screen immediately, but wait until your function has finished and control returns to the GTK main loop.
I have 4 numbers (int a, int b, int c, int d) that are equal to rand()%7. How can I discover if the numbers are equal to each other in the shortest way?
To find out if the numbers are equal to each other, you can do: ``` if (a == b && b == c && c == d) ``` The condition above is supported by the transitive property of equality in mathematics in which it states that: If a = b and b = c, then a = c. Given that property, we can state: If a = b, b = c, and c = d, then a = c, a = d, and b = d. Source:Mathwords
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed7 years ago.Improve this question I want to know whether any program which is written using C programming language can be written using R programming language or not. I know that it is possible to call C code from R, but I want to know if I want to write every algorithm in R from scratch whether it is possible or not. I want to know does R has all constructs required to implement all programs written in C lanuage?
Yes, both areTuring complete.
I've been trying to make a program to input two numbers from the user.The XCode application is showing error as Data argument not used by format string How am I supposed to get over this? please help thanks
just type%dinside the("Here is my number %d",Num) You can find more formats here:https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html
I want to know if it is possible to create an array that is composed of 2D arrays. I have a function that modifies the content of a 2D array, in my program this function is called 2035 times. And each time the result is saved in the same 2D array. So of course I can have access to only the 2035 update of the 2D array. Is it possible to have an array of 2D arrays?Is there a way to save each 2D array?
An array of an array is called a "2D array", and it looks like this: ``` int arr[100][500]; ``` i.e. an array containing 100 arrays, each of length 500. An array of a 2D array is called a "3D array", and it looks like this: ``` int arr[2035][100][100] ``` i.e. an array containing 2035 2D arrays, each of dimension 100x100.
Shouldn't the value of i be 0? Since x ``` #include<stdio.h> int main(void) { int x = 10,y=20,z=5,i; i=x<y<z; printf("%d",i); return 0; } ```
In your code, due to theLTR associativityof the relational operators, ``` i=x<y<z; ``` evaluates to ``` i=(x<y)<z; ``` which is ``` i=(10<20)<z; ``` which is ``` i= 1 < 5; ``` which is TRUE (1). That1gets stored ini. That's it.
This is the code I found ``` static_assert(sizeof(struct File) == 256); ``` The definition of the macro is this: ``` #define static_assert(x) switch (x) case 0: case (x): ``` How does this perform assertion?Why not just use the regular assert() function?
This performs anassertby triggering a compile-time error. Consider this code: ``` switch(0) case 0: case 0: ``` The compiler will tell you that you have a duplicatecaselabel, because zero is listed twice. If, on the other hand, you would put any number other than zero in place ofx, you would get ``` switch(1) case 0: case 1: ``` which is perfectly legal, and would not trigger a compile-time error. Unlike the regularassertwhich happens at run time, this assert happens at compile time. In other words, if the regular assertion is false, the program would crash; if this assertion is false, the program would not even compile.
I am trying to read some commands which should be passed to my program from a file. The commands are on different lines, so I guess this means that they are separated by\ncharacter. This is my command reading section: ``` FILE *fop; char command[50]; fopen("mbr.op", "r"); while(!feof(fop)) { fscanf(fop,"%s[^\n]", command); printf("%s\n", command); } fclose(fop); ``` This prints some words that are in the file, but not all, and not in the expected order. How could I change this code to achieve the desired result?
You open your file incorrectly (it returns aFILE pointer which is associated with the opened file),fopenshould be used as this - ``` fop=fopen("mbr.op", "r"); ``` Andwhile(!feof(fop))should not be used. You can write your loop as follows - ``` while(fscanf(fop,"%[^\n]%*c", command)==1) { printf("%s\n", command); } ``` Note- Also check if file was opened successfully.
I admit, if it's possible, it would be open door to bad, very bad code... But in some specific cases... So the question is, is there any equivalent ofcsetjmp/longjmp ? I would like to implement a python-like generator without using threads, just saving the stack and the context, and restore it later.
While not strictly equivalent to the C longjump, the Javaflow library from apache commons gives a way to interrupt a code flow (like Exceptions do, but with capture of the stack), and to restart it later. This is suitable to implements Coroutines. However, it requires bytecode modification. http://commons.apache.org/sandbox/commons-javaflow/index.html
If I have a program in C and I want it to take 100 times an "A" as an argument inargc, then I would put./program $(python -c 'print "A" * 100')in console. Now if I want the C program to read 100 times an "A" from a file (file1, for example), what should I put in for it to read it withfread? (I have tried to put the above python command insidefile1. It does not seem to work.) Also I have tried to use it likepython -c 'print "A" * 100'. It does not seem to work either. It would be really appreciated if the script could be in Python.
Are you looking for ``` python -c 'print "A" * 100' > file1 && ./program file1 ``` or are you looking for a way to execute the python script from C (http://linux.die.net/man/3/system)?
I am trying to read some commands which should be passed to my program from a file. The commands are on different lines, so I guess this means that they are separated by\ncharacter. This is my command reading section: ``` FILE *fop; char command[50]; fopen("mbr.op", "r"); while(!feof(fop)) { fscanf(fop,"%s[^\n]", command); printf("%s\n", command); } fclose(fop); ``` This prints some words that are in the file, but not all, and not in the expected order. How could I change this code to achieve the desired result?
You open your file incorrectly (it returns aFILE pointer which is associated with the opened file),fopenshould be used as this - ``` fop=fopen("mbr.op", "r"); ``` Andwhile(!feof(fop))should not be used. You can write your loop as follows - ``` while(fscanf(fop,"%[^\n]%*c", command)==1) { printf("%s\n", command); } ``` Note- Also check if file was opened successfully.
I admit, if it's possible, it would be open door to bad, very bad code... But in some specific cases... So the question is, is there any equivalent ofcsetjmp/longjmp ? I would like to implement a python-like generator without using threads, just saving the stack and the context, and restore it later.
While not strictly equivalent to the C longjump, the Javaflow library from apache commons gives a way to interrupt a code flow (like Exceptions do, but with capture of the stack), and to restart it later. This is suitable to implements Coroutines. However, it requires bytecode modification. http://commons.apache.org/sandbox/commons-javaflow/index.html
If I have a program in C and I want it to take 100 times an "A" as an argument inargc, then I would put./program $(python -c 'print "A" * 100')in console. Now if I want the C program to read 100 times an "A" from a file (file1, for example), what should I put in for it to read it withfread? (I have tried to put the above python command insidefile1. It does not seem to work.) Also I have tried to use it likepython -c 'print "A" * 100'. It does not seem to work either. It would be really appreciated if the script could be in Python.
Are you looking for ``` python -c 'print "A" * 100' > file1 && ./program file1 ``` or are you looking for a way to execute the python script from C (http://linux.die.net/man/3/system)?
I've been reading other people's code, but the parameters people use to if statements are really confusing to me. I've seen people place pointers and structs as parameters, but I don't understand how it's decided whether the result of the logical statement will be true or false. For example: ``` struct Foo foo; if(foo) doSomething(); char *ch = malloc(sizeof(char)); if(num) doSomethingElse(); ``` If someone were to write and compile this, how would a true of false result be determined from the logical statements in the if statements?
A pointer is usable as a boolean value. A null pointer is considered false, and a non-null pointer is considered true. Numbers are usable as a boolean value. A zero-valued number is considered false, and any other value is considered true. Structs are not usable as boolean values, although a pointer to a struct is.
Fromdifftime()'s man page: double difftime(time_t time1, time_t time0);Thedifftime()function returns the number of seconds elapsed between timetime1and timetime0, represented as adouble. Since 'number of seconds' doesn't require floating-point numbers, why does this function return adouble?
Thisdocumentationis more clear on the point: On POSIX systems, time_t is measured in seconds, and difftime is equivalent to arithmetic subtraction, but C and C++ allow fractional units for time_t. AlthoughPOSIX requirestime_tto be an integer type, for non-POSIX systems it is possible that this can return fractional seconds.
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.Closed7 years ago.Improve this question I learned that C does not have the boolean type. When I read "Ocaml from very beginning", I encountered a question in page12 : Why we cannot just use 0 and 1 to represent the boolean type in camel, like the way C language does?
why some languages have boolean type but others don't? Because some languages have a bettertype systemthan others. In my opinion, for many (but not all) tasks, Ocaml has a better type system than C. (but your question is too broad & matter of opinion) The C type system was closely inspired by the hardware (PDP-11) andinstruction setavailable at the time (early 1970s) C was designed.
This question already has answers here:What is the type of string literals in C and C++?(4 answers)Closed7 years ago. Is the type of a string, like"hello, world"achar *orconst char *, as of C99? I know that in C++ it is the latter, but what about in C?
String literals in C are not pointers, they are arrays ofchars. You can tell this by looking atsizeof("hello, world"),which is 13, because null terminator is included in the size of the literal. C99 allows string literals to be assigned tochar *, which is different from C++, which requiresconst char *.
``` #include <stdio.h> int main() { char string[80]="abcdef"; char buffer[80]; int num; sscanf(string,"%*[^0-9a-fA-F]%n%s",&num,buffer); printf("%d\n",num); puts(buffer); return 0; } ``` Output: ``` -149278720 ``` And what I expect is ``` 0 abcdef ``` I believe that the regex%*[^0-9a-fA-F]discards all characters other than"xdigits", however, when the first character in the string is a"xdigit",sscanfseems to return instantly. How can I fix this?
%*[^0-9a-fA-F]matches anon-emptysequence of characters that aren't in the character set. Since you don't have any non-hexdigits at the beginning of the string, this conversion fails andsscanfreturns immediately. As far as I can tell, there's no way to make this optional insscanf. If you just want to skip over the non-hexdigits, usestrcspn(). ``` num = strcspn(string, "0123456789abcdefABCDEF"); strcpy(buf, string+num); ```
I've been reading other people's code, but the parameters people use to if statements are really confusing to me. I've seen people place pointers and structs as parameters, but I don't understand how it's decided whether the result of the logical statement will be true or false. For example: ``` struct Foo foo; if(foo) doSomething(); char *ch = malloc(sizeof(char)); if(num) doSomethingElse(); ``` If someone were to write and compile this, how would a true of false result be determined from the logical statements in the if statements?
A pointer is usable as a boolean value. A null pointer is considered false, and a non-null pointer is considered true. Numbers are usable as a boolean value. A zero-valued number is considered false, and any other value is considered true. Structs are not usable as boolean values, although a pointer to a struct is.
Fromdifftime()'s man page: double difftime(time_t time1, time_t time0);Thedifftime()function returns the number of seconds elapsed between timetime1and timetime0, represented as adouble. Since 'number of seconds' doesn't require floating-point numbers, why does this function return adouble?
Thisdocumentationis more clear on the point: On POSIX systems, time_t is measured in seconds, and difftime is equivalent to arithmetic subtraction, but C and C++ allow fractional units for time_t. AlthoughPOSIX requirestime_tto be an integer type, for non-POSIX systems it is possible that this can return fractional seconds.
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.Closed7 years ago.Improve this question I learned that C does not have the boolean type. When I read "Ocaml from very beginning", I encountered a question in page12 : Why we cannot just use 0 and 1 to represent the boolean type in camel, like the way C language does?
why some languages have boolean type but others don't? Because some languages have a bettertype systemthan others. In my opinion, for many (but not all) tasks, Ocaml has a better type system than C. (but your question is too broad & matter of opinion) The C type system was closely inspired by the hardware (PDP-11) andinstruction setavailable at the time (early 1970s) C was designed.
This question already has answers here:What is the type of string literals in C and C++?(4 answers)Closed7 years ago. Is the type of a string, like"hello, world"achar *orconst char *, as of C99? I know that in C++ it is the latter, but what about in C?
String literals in C are not pointers, they are arrays ofchars. You can tell this by looking atsizeof("hello, world"),which is 13, because null terminator is included in the size of the literal. C99 allows string literals to be assigned tochar *, which is different from C++, which requiresconst char *.
``` #include <stdio.h> int main() { char string[80]="abcdef"; char buffer[80]; int num; sscanf(string,"%*[^0-9a-fA-F]%n%s",&num,buffer); printf("%d\n",num); puts(buffer); return 0; } ``` Output: ``` -149278720 ``` And what I expect is ``` 0 abcdef ``` I believe that the regex%*[^0-9a-fA-F]discards all characters other than"xdigits", however, when the first character in the string is a"xdigit",sscanfseems to return instantly. How can I fix this?
%*[^0-9a-fA-F]matches anon-emptysequence of characters that aren't in the character set. Since you don't have any non-hexdigits at the beginning of the string, this conversion fails andsscanfreturns immediately. As far as I can tell, there's no way to make this optional insscanf. If you just want to skip over the non-hexdigits, usestrcspn(). ``` num = strcspn(string, "0123456789abcdefABCDEF"); strcpy(buf, string+num); ```
I'm looking at the source code for the venerable Unix gameRogue, and I've noticed that the comments at the head of each file contain a line in this format: ``` @(#)init.c 4.31 (Berkeley) 02/05/99 ``` I've never seen the "@(#)" notation before, and I haven't been able to find an explanation of it anywhere. Could anyone tell me what this signifies?
Naturally, I figured this out immediately after posting my question when I stumbled upon a reference to an old version control system calledSource Code Control System. The mysterious comment is an "sccsid" string. From Wikipedia: After compilation, this string can be found in binary and object files by looking for the pattern "@(#)" and can be used determine which source code files were used during compilation.
I'd like to build a menu in ncurses that has section dividers. My example list looks like this: ``` Aardvark Apple Bee Cat Kitten Kalashnikov Waffle ``` What I want is non-selectable dividers. Something like this: ``` (A) ---- Aardvark Apple (B) ---- Bee (C) ---- Cat (K) ---- Kitten Kalashnikov (W) ---- Waffle ``` Is there a built-in way to do this? More specifically, I'm using this ruby gem:https://github.com/eclubb/ncurses-rubyI'd prefer an answer that was generic, but if it can be solved with Ruby awesomeness, that's cool too.
Assuming you are talking about the ncursesmenulibrary (as "built-in"), you can make a nonselectable item usingset_item_opts.
This question already has answers here:Regular expressions in C: examples?(5 answers)Closed7 years ago. I meant, something that we can use this way: ``` char string1[] = "???, buddy*\0"; char string2[] = "Hey, buddy, hello!\0"; if (like(string1, string2) puts("strings are similar!"); else puts("string are different!"); ```
You want to use a regular expression library. See this question for the ANSI library information:Regular expressions in C: examples?
In a python shell, if I typea = 2nothing is printed. If I typea2 gets printed automatically. Whereas, this doesn't happen if I run a script from idle. I'd like to emulate this shell-like behavior using the python C api, how is it done? For instance, executing this codePyRun_String("a=2 \na", Py_file_input, dic, dic);from C, will not print anything as the output. I'd like to simulate a shell-like behavior so that when I execute the previous command, the value "2" is stored in a string. Is it possible to do this easily, either via python commands or from the C api? Basically, how does the python shell do it?
To compile your code so expression statements invokesys.displayhook, you need to passPy_single_inputas thestartparameter, and you need to provide one statement at a time.
I'm trying to cross-compile an SSH-server to port it on an home-made OS, using newlib (because the OS uses a lib which is based on newlib). I got some troubles with the RedHat Newlib, and I was wondering if I can do my porting with another library (for example uclibc) ? Is there differences between this 3 "libc" interfaces (libc, newlib, and uclibc) ?
GNU libc (glibc) includes ISO C, POSIX, System V, and XPG interfaces. uClibc provides ISO C, POSIX and System V, while Newlib provides only ISO C. While you might be able to port other libraries, they have specific OS dependencies. Unless your OS itself is POSIX compliant, it will probably be an unrealistic prospect. Even with Newlib, it is your responsibility to implement the syscalls appropriately to support devices, file-systems and memory management.
I've been doing abit of reading through the Linux programmer's manual looking up various functions and trying to get a deeper understanding of what they are/how they work. Looking atfgets()I read "A '\0' is stored after the last character in the buffer . I've read throughWhat does \0 stand for?and have a pretty solid understanding of what\0symbolizes (a null character right ?). But what I'm struggling to grasp is its relevance tofgets(), I don't really understand why it "needs" to end with a null character.
As you already said, you are probably aware that\0constitutes the end of all strings in C. As per the C standard, everything that is a string needs to be\0terminated. Sincefgets()makes a string, that string, of course, will be properly null terminated. Do note that for all string functions in C, any string you use or generate with them must be terminated with a\0character.
Hello I try to dump the memory of a process in Android/Linux. Right now I read the memory maps to get a memory region's address space and then I read every single word like this: ``` ptrace(PTRACE_ATTACH, pid, NULL, NULL); wait(NULL); read each word in this memory region: word = ptrace(PTRACE_PEEKDATA, pid, (void *)address, NULL); ptrace(PTRACE_CONT, pid, NULL, NULL); ptrace(PTRACE_DETACH, pid, NULL, NULL); ``` Isn't there a more efficient solution reading directly a whole memory page by specifying the start/end of a memory address space to read?
There are two possible ways to read memory more efficiently from another process. If your kernel supports it (I have no idea about Android kernels) you can useprocess_vm_readv. Another way is to open the/proc/.../memfile of the target process and read from it. gdb uses this method, though I think only becauseprocess_vm_readvis "new" (in gdb's terms).
Can someone explain me the working of scanf. If i am entering s as integer it would work fine but i enter a character it would run continuously till it exits the loop. So it is not removing the character from the buffer and not asking for input. Can you provide more insight on scanf and it's internal implementation ``` #include<stdio.h> int main() { int s,i = 0; while(i < 10) { scanf("%d",&s); i++; printf("%d",s); } while(i < 20) { printf("%d",s); scanf("%c",&s); } } ```
%cspecifier is for characters not forintdata types. Using wrong format specifier for a data type invoke undefined behavior. Also note thatiis not incrementing in the second loop. This will lead to an infinitewhileloop.
I am facing a weird problem retrieving tcp header and trying to print source and destination ports code : ``` src_p = tcp->th_sport; dest_p = tcp->th_dport; output (in hex): 8e08 and 64a2 ``` wireshark shows that the ports are 088e and a264 why is libpcap swapping the bytes? or is there something wrong with my code? PS: I am using structs shown inthis program.
The ports are stored innetwork byte order(big endian) in the TCP header (most protocols send multi-byte numbers over a network using big endian, hence the nickname). Wireshark is merely converting the bytes tohost byte order(big or little endian, depending on your PC's hardware, hence the nickname) when it is translating the bytes into human-readable numbers. In your code, you can use your platform'sntohs()function to do the same thing.
This question already has answers here:In C, why is sizeof(char) 1, when 'a' is an int?(5 answers)Closed7 years ago. ``` char c = 'A'; printf("%d\n",sizeof(c));// output = 1 printf("%d\n",sizeof('A')); // output = 4 ``` Why thesizeofoperator gives different output for same character? Please Help
cis a variable of typechar; its size is 1 byte. 'A'is anintliteral - don't ask me why the standard says that. Its size is 4 bytes on your platform (the same assizeof(1)).
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question What happens to fwrite if it the drive is full? Assuming that it was compiled on a windows machine with visual studio. Thanks!
If a write cannot be performed,fwrite()either returns a short item count (if some items have been written before an error occurred) or0.fwrite()does not block if an error occurs. To differentiate and end-of-file condition from an IO error, use thefeof()andferror()functions.