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 answer...
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...
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.:S...
``` 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 w...
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 fla...
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...
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); } ...
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...
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 inde...
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**)mal...
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-nam...
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 (f...
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 shou...
``` 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" ...
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, ...
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 "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 = '-'; putch...
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 w...
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...
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...
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 s...
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 i...
``` 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 ...
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 pos...
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 ...
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 funct...
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 min...
``` 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 modifia...
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 ...
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 prin...
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 pos...
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 ...
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 funct...
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 cas...
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 hel...
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 us...
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 gon...
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...
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("Ho...
``` 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...
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...
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...
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 Stud...
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 grea...
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 cas...
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 ...
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...
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 ...
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 ...
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...
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 compil...
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...
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 microso...
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 follow...
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 compi...
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 compi...
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 someo...
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()) != EO...
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'...
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);...
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...
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, 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.Closed7 years ago.Improve this question I want to know whether any program which is written using C programming language can...
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...
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 dimensi...
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 ...
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]"...
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...
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/...
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 a...
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]"...
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...
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/...
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 a...
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(...
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 ...
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",...
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) ...
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-...
%*[^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...
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(...
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 ...
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",...
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) ...
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-...
%*[^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...
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 an...
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 th...
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 ```...
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 d...
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...
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" int...
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...
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 soli...
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 o...
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 *)...
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 becauseproces...
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 `...
%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 c...
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 transla...
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 vis...
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.