question
stringlengths
25
894
answer
stringlengths
4
863
How is it possible to extract the function interpretation of an array in Z3 using the C API? When I query Rise4Fun with, say, the following instance: ``` (declare-fun arr () (Array Int Int)) (assert (= 5 (select arr 3))) (check-sat) (get-model) (exit) ``` , I get: ``` sat (model (define-fun arr () (Array Int ...
Yes, this is possible. A very similar question has been asked recently and the answer with examples can be found here:Read func interp of a z3 array from the z3 model
Consider the output of toy program below: ``` void fun(int arr[][3]) { cout<<sizeof arr; } int main() { int arr[5][3]; cout<< sizeof arr<<" "; func(arr); } ``` As pointer decay happens only once in 2D array, I was expecting the output to be 60 12 as 5*3*4 and 3*4. But the output is 60 4 Could any...
in fun() ``` arr[][3] ``` arr is a pointer to array of 3 integers. so the output is sizeof pointer.
Is it for ipv6? If ipv4 is s_addr just the dotted quad reinterpreted as a 32 bit integer?
unsgined longguarantees that the size of the variable is at least 4 bytes, thus holding the entire ip. An unsigned int can be smaller.
I want to write a function which would redirect the standard output to a file where the name of the file is "name".log where "name" is the argument to the function ``` void redirect(char *name) { ``` I don't know where to begin.
You can usefreopen() ``` // code copied from the link #include <stdio.h> ... FILE *fp; ... fp = freopen ("/tmp/logfile", "a+", stdout); ... ```
``` struct Error { MACRO(1, Connect); MACRO(2, Timeout); }; ``` I need to define MACRO() in such way that the above code will generate the following code. ``` struct Error { static const int Connect = 1; static const int Timeout = 2; const char * const name[] = {"Connect", "Timeout"}; }; ``` Is thi...
You can't do this directly, but you can if you move the macros to a separate location (such as a separate file): macros.hpp ``` MACRO(1, Connect) MACRO(2, Timeout) #undef MACRO ``` the other file ``` struct Error { #define MACRO(a, b) static const int b = a; #include "macros.hpp" const char * const name []...
What is the best way (fast and relatively simple to implement) to sendgmpof typempf_tusingMPI(in c)? a simple code will be helpful. thank you
mpf_t uses several pointers, so you should serialize mpf_t (and other GMP types) before sending via MPI. There were some letters about MPI in GMP mailing list:https://gmplib.org/list-archives/gmp-discuss/2008-March/003091.html There is article about MPI wrapper library for GMP (MPIGMP + MPIBNCpack):http://na-inet.jp...
This question already has answers here:Why does a function with no parameters (compared to the actual function definition) compile?(11 answers)Closed9 years ago. In the following C code, functionprintrcalled only with one parameter, But all compiled with no warning on GCC and VS.I am confused why this is OK? Thanks! ...
Gccdoeswarn you: ``` $ gcc -Wextra y.c y.c: In function ‘printr’: y.c:4: warning: type of ‘i’ defaults to ‘int’ y.c:4: warning: type of ‘j’ defaults to ‘int’ ``` And once you've fixed those it will warn ``` y.c: In function ‘main’: y.c:11: error: too few arguments to function ‘printr’ ```
I have 2 arrays: ``` unsigned short* array1; int* array2; ``` Is there a quick way to get all the data in array1 into array2 such that the values ofarray2[0]=array1[0], array2[1] = array1[1]...etc. My question mentions casting but I think that's wishful thinking! Obviously I can do this element by element using a f...
How do I cast array of unsigned short to an array of int? You don't. If you do, and you use the result, you'll have some nice undefined behavior at hand. Is there a quick way to get all the data in array1 into array2 Yes, copy the array elements. It will be fast on any decent modern computer.
I have 3 files: in file1.h I declared: ``` #ifdef SYMBOLE extern int const my_var; #else extern int my_var; #endif ``` in file file2.c I defined: ``` int my_var; ``` and in file3.c I initialized my_var: ``` my_var = 4; ``` My question is, if I declaredmy_varlike this way thenmy_varwill be considered constant or...
Line in file2.c is not definition, it is a declaration. (unless you initialize it) So if SYMBOLE is defined, your variable will be conisdered constant and cause a compilation error in file2.c because of conflicting type declaration for variable my_var.
Consider the output of toy program below: ``` void fun(int arr[][3]) { cout<<sizeof arr; } int main() { int arr[5][3]; cout<< sizeof arr<<" "; func(arr); } ``` As pointer decay happens only once in 2D array, I was expecting the output to be 60 12 as 5*3*4 and 3*4. But the output is 60 4 Could any...
in fun() ``` arr[][3] ``` arr is a pointer to array of 3 integers. so the output is sizeof pointer.
Is it for ipv6? If ipv4 is s_addr just the dotted quad reinterpreted as a 32 bit integer?
unsgined longguarantees that the size of the variable is at least 4 bytes, thus holding the entire ip. An unsigned int can be smaller.
I want to write a function which would redirect the standard output to a file where the name of the file is "name".log where "name" is the argument to the function ``` void redirect(char *name) { ``` I don't know where to begin.
You can usefreopen() ``` // code copied from the link #include <stdio.h> ... FILE *fp; ... fp = freopen ("/tmp/logfile", "a+", stdout); ... ```
``` struct Error { MACRO(1, Connect); MACRO(2, Timeout); }; ``` I need to define MACRO() in such way that the above code will generate the following code. ``` struct Error { static const int Connect = 1; static const int Timeout = 2; const char * const name[] = {"Connect", "Timeout"}; }; ``` Is thi...
You can't do this directly, but you can if you move the macros to a separate location (such as a separate file): macros.hpp ``` MACRO(1, Connect) MACRO(2, Timeout) #undef MACRO ``` the other file ``` struct Error { #define MACRO(a, b) static const int b = a; #include "macros.hpp" const char * const name []...
What is the best way (fast and relatively simple to implement) to sendgmpof typempf_tusingMPI(in c)? a simple code will be helpful. thank you
mpf_t uses several pointers, so you should serialize mpf_t (and other GMP types) before sending via MPI. There were some letters about MPI in GMP mailing list:https://gmplib.org/list-archives/gmp-discuss/2008-March/003091.html There is article about MPI wrapper library for GMP (MPIGMP + MPIBNCpack):http://na-inet.jp...
This question already has answers here:Why does a function with no parameters (compared to the actual function definition) compile?(11 answers)Closed9 years ago. In the following C code, functionprintrcalled only with one parameter, But all compiled with no warning on GCC and VS.I am confused why this is OK? Thanks! ...
Gccdoeswarn you: ``` $ gcc -Wextra y.c y.c: In function ‘printr’: y.c:4: warning: type of ‘i’ defaults to ‘int’ y.c:4: warning: type of ‘j’ defaults to ‘int’ ``` And once you've fixed those it will warn ``` y.c: In function ‘main’: y.c:11: error: too few arguments to function ‘printr’ ```
I have 2 arrays: ``` unsigned short* array1; int* array2; ``` Is there a quick way to get all the data in array1 into array2 such that the values ofarray2[0]=array1[0], array2[1] = array1[1]...etc. My question mentions casting but I think that's wishful thinking! Obviously I can do this element by element using a f...
How do I cast array of unsigned short to an array of int? You don't. If you do, and you use the result, you'll have some nice undefined behavior at hand. Is there a quick way to get all the data in array1 into array2 Yes, copy the array elements. It will be fast on any decent modern computer.
I have 3 files: in file1.h I declared: ``` #ifdef SYMBOLE extern int const my_var; #else extern int my_var; #endif ``` in file file2.c I defined: ``` int my_var; ``` and in file3.c I initialized my_var: ``` my_var = 4; ``` My question is, if I declaredmy_varlike this way thenmy_varwill be considered constant or...
Line in file2.c is not definition, it is a declaration. (unless you initialize it) So if SYMBOLE is defined, your variable will be conisdered constant and cause a compilation error in file2.c because of conflicting type declaration for variable my_var.
``` struct Error { MACRO(1, Connect); MACRO(2, Timeout); }; ``` I need to define MACRO() in such way that the above code will generate the following code. ``` struct Error { static const int Connect = 1; static const int Timeout = 2; const char * const name[] = {"Connect", "Timeout"}; }; ``` Is thi...
You can't do this directly, but you can if you move the macros to a separate location (such as a separate file): macros.hpp ``` MACRO(1, Connect) MACRO(2, Timeout) #undef MACRO ``` the other file ``` struct Error { #define MACRO(a, b) static const int b = a; #include "macros.hpp" const char * const name []...
What is the best way (fast and relatively simple to implement) to sendgmpof typempf_tusingMPI(in c)? a simple code will be helpful. thank you
mpf_t uses several pointers, so you should serialize mpf_t (and other GMP types) before sending via MPI. There were some letters about MPI in GMP mailing list:https://gmplib.org/list-archives/gmp-discuss/2008-March/003091.html There is article about MPI wrapper library for GMP (MPIGMP + MPIBNCpack):http://na-inet.jp...
This question already has answers here:Why does a function with no parameters (compared to the actual function definition) compile?(11 answers)Closed9 years ago. In the following C code, functionprintrcalled only with one parameter, But all compiled with no warning on GCC and VS.I am confused why this is OK? Thanks! ...
Gccdoeswarn you: ``` $ gcc -Wextra y.c y.c: In function ‘printr’: y.c:4: warning: type of ‘i’ defaults to ‘int’ y.c:4: warning: type of ‘j’ defaults to ‘int’ ``` And once you've fixed those it will warn ``` y.c: In function ‘main’: y.c:11: error: too few arguments to function ‘printr’ ```
I have 2 arrays: ``` unsigned short* array1; int* array2; ``` Is there a quick way to get all the data in array1 into array2 such that the values ofarray2[0]=array1[0], array2[1] = array1[1]...etc. My question mentions casting but I think that's wishful thinking! Obviously I can do this element by element using a f...
How do I cast array of unsigned short to an array of int? You don't. If you do, and you use the result, you'll have some nice undefined behavior at hand. Is there a quick way to get all the data in array1 into array2 Yes, copy the array elements. It will be fast on any decent modern computer.
I have 3 files: in file1.h I declared: ``` #ifdef SYMBOLE extern int const my_var; #else extern int my_var; #endif ``` in file file2.c I defined: ``` int my_var; ``` and in file3.c I initialized my_var: ``` my_var = 4; ``` My question is, if I declaredmy_varlike this way thenmy_varwill be considered constant or...
Line in file2.c is not definition, it is a declaration. (unless you initialize it) So if SYMBOLE is defined, your variable will be conisdered constant and cause a compilation error in file2.c because of conflicting type declaration for variable my_var.
I want to know how to use gettext in C with dynamic message id in the argument. For example, ``` char *var = fun(); //where fun returns char * type. char *val = gettext(var); ```
Your code is fine, but you will of course also need to make sure thatfun()returns a static string, that's going to stick around. Alsovalshould beconst char *, you cannot change the strings owned by gettext.
I read many answers about this questions, and I can't see the problem here. In dish.h I have: ``` typedef struct Dish_t* Dish; ``` and in dish.c: ``` struct Dish_t { DishKind kind; Taste taste; }; ``` but when I write in dish.c: ``` Dish newDish = malloc(sizeof(*newDish)); ``` I get the dereferencing error. W...
You say: When I change Dish_t to Dish, it works! Why? But your code actually usesDish. It won't work with plainDish_t, since that's not a valid type name. It must be eitherstruct Dish_torDish. I would recommend against including the asterisk in thetypedefsince it adds even more chances of confusion.
Here's my lex code: ``` %{ %} %% [ \t]* {printf("tab");} .+ { printf("%s", yytext);} .|\n { ECHO; } %% int main() { yylex(); return 0; } ``` Here's my input data: ``` #include<stdio.h> int main(){ for(int i = 0 ; i < 10 ; i ++){ for(int j = 0 ; j < i ; j ++){ printf("*"); } printf("\n"); } }...
The generated lexical analyzer will always choose the longest token. For your ``` printf("*"); ``` rule.+will give a longer token than[ \t]*, so the former will be chosen. By the way, you could try this example: ``` %{ %} %% [ \t]* {printf("| |");} \n {printf("newline\n");} [^ \n]+ {printf("%s", yytext);...
Suppose I have this situation: I redirected standard error of some program to the file output.err and standard output to the file output.out. When the program is run but killed before it is allowed to complete normally, I notice that the output.err file contains the expected output, but that output.out is empty even t...
This is because STDERR is never buffered. That means the data is written instantly no matter what. To flush the buffered data in STDOUT you can use this function: ``` some_write_operation_on_stdout(); fflush(stdout); ``` This call results in the data getting flushed from the buffer and written as if it were unbuffer...
I see the term 'construct' come up very often in programming readings. The current book I am reading, "Programming in C" by Stephen Koching has used it a few times throughout the book. One example is in the chapter on looping, which says: "When developing programs, it sometimes becomes desirable to have the test ma...
In this case you can replace the wordconstructwithsyntax. does the word 'construct' have an relation to an object 'constructor' in other languages? No. These two terms are different. There is nothing like constructor in C
I'm looking for instructions about documenting exit codes in my C file. As example, I have the following: ``` if( !(new_std = (student*) malloc(sizeof(student))) ) exit(1); //+1 is for the \0, strlen does not give us that one! if( !(new_std->name=(char*) malloc(1+sizeof(char)*strlen(name)))){ free(new_std);...
There is no "correct answer", but I would imagine most everyone would suggest using constants: Put these in a common header file that any C file can include. exit_codes.h ``` #define EXIT_SUCCESS 0 #define EXIT_GENERAL_FAILURE 1 #define EXIT_OUT_OF_MEM 2 ``` whatever.c ``` #include "exit_codes.h...
I want to make a program that open a text file present in thestartupfolder.Write something to it and close it. Can i use%APPDATA%in my path because user name is changed at every pc I used as below but its not working. ``` FILE *fptr fptr = fopen("%APPDATA%\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\myfile.tx...
The regular way to get environment variables is to usegetenv ``` char * appdata = getenv("APPDATA"); if (!appdata) { /* error */ } char buffer[0x400]; snprintf(buffer, sizeof(buffer) , "%s\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\myfile.txt", appdata); fptr = fopen(buffer,"w"); ``` Please keep in mind...
I learnt to program using Java in eclipse. Recently I've wanted to learn C and C++ so I installed the C/C++ version of eclipse. I still have some Java programming to do though and the option to create a new Java project has disappeared. Is there an easy way to have both C++ and Java projects accessible on eclipse or ...
Eclipse is a platform, you can most certainly use it for C/C++ and Java at the same time. The development tools for each language are actually just plugins. That said, many people prefer to use separate installations for each language, so as to keep their workspaces clean. If you want to install the Java tools in you...
I've seen some guide on generating random numbers with C: two things got me wondering: it is said that in addition to stdlib.h and time.h libraries I have to include the math.h library for it to work, why? (afaik the srand and rand functions are in stdlib)?in the example the srand function is written the following wa...
The functiontimereturns atime_tvalue, whilesrandexpect anunsigned intargument. Without the cast, the compiler may produce a warning and depending on the compiler flags this may cause the compilation to fail. In general it is good practice to avoid warnings. Nothing in the line you show requires the inclusion ofmath.h...
I'm trying to change the scheduling scheme of running threads in freeBSD. The default thread scheduling of freeBSD is based on the thread's priority but I want to change it to another condition. I was wondering which of the following functions are responsible for this scheduling,tdq_runq_add()in sched_ule.c orrunq_cho...
Selecting the tread that will be run next is done inchoosethread()in/usr/src/sys/kern/kern_switch.c. This in turn callssched_choose(). Depending on which scheduler you're using, this is in/usr/src/sys/kern/sched_4bsd.c(for the old scheduler) or/usr/src/sys/kern/sched_ule.c(the ULE scheduler, which is the default now)....
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.Closed9 years ago.Improve this question Imagine we've got anint number = 1040orint number = 105in a C program, and we want to kno...
I would divide by 10 and check the remainder. If remainder is 0, then last position of the number is 0. Then repeat the same step until number is less than 10 ``` #include<iostream> int main(void) { long int k = 6050404; int iter = 0; while (k > 10) { long int r = k % 10; if( r == 0) { std::cout <...
Do we need to call wordfree upon wordexp failure? Calling wordfree seems to segfault in some cases (eg when wordfree returns error code with string is "foo 'bar"). This isn't clear from man page, and I've seen wordfree used in some error cases.
According to theGNU's manual example, it should be called on error only ifWRDE_NOSPACEwas returned: ``` switch (wordexp (program, &result, 0)) { case 0: /* Successful. */ break; case WRDE_NOSPACE: /* If the error was WRDE_NOSPACE, then perhaps part of the result was allocated. */ wordfree (&resul...
I created a program where a signal call installs a new signal handler 'signum' and basically display a message whenever a terminal special char is pressed, such as CRTL-C. I was wondering what if I wanted to keep track how many times CRTL-C was pressed? How can I go about implementing that? Thank you. ``` #include ...
Use a static variable: ``` void f(int signum) { static int cnt = 0; printf('Hahah, you clicked me %d time(s)!', ++cnt); } ``` If you want that count available elsewhere, then use a global variable instead.
What is the fastest way to make the last 2 bits of a byte zero? ``` x = x >> 2 << 2; ``` OR ``` x &= 252; ``` Is there a better way?
Depends on many factors, including the compiler, the machine architecture (ie processor). My experience is that ``` x &= 252; // or... x &= ~3; ``` are more efficient (and faster) than x = x >> 2 << 2;
When i run the following code ``` /*Program to find the greatest common divisor of two nonnegative integer values*/ #include <stdio.h> int main(void){ printf(" n | n^2\n"); printf("-----------------\n"); for(int n = 1; n<11; n++){ int nSquared = n^2; printf("%i %i\n",n,nS...
Usepowfunction frommath.h. ^is the bitwise exclusive OR operator and has to nothing to do with a power function.
Suppose I have this situation: I redirected standard error of some program to the file output.err and standard output to the file output.out. When the program is run but killed before it is allowed to complete normally, I notice that the output.err file contains the expected output, but that output.out is empty even t...
This is because STDERR is never buffered. That means the data is written instantly no matter what. To flush the buffered data in STDOUT you can use this function: ``` some_write_operation_on_stdout(); fflush(stdout); ``` This call results in the data getting flushed from the buffer and written as if it were unbuffer...
I see the term 'construct' come up very often in programming readings. The current book I am reading, "Programming in C" by Stephen Koching has used it a few times throughout the book. One example is in the chapter on looping, which says: "When developing programs, it sometimes becomes desirable to have the test ma...
In this case you can replace the wordconstructwithsyntax. does the word 'construct' have an relation to an object 'constructor' in other languages? No. These two terms are different. There is nothing like constructor in C
I'm looking for instructions about documenting exit codes in my C file. As example, I have the following: ``` if( !(new_std = (student*) malloc(sizeof(student))) ) exit(1); //+1 is for the \0, strlen does not give us that one! if( !(new_std->name=(char*) malloc(1+sizeof(char)*strlen(name)))){ free(new_std);...
There is no "correct answer", but I would imagine most everyone would suggest using constants: Put these in a common header file that any C file can include. exit_codes.h ``` #define EXIT_SUCCESS 0 #define EXIT_GENERAL_FAILURE 1 #define EXIT_OUT_OF_MEM 2 ``` whatever.c ``` #include "exit_codes.h...
I want to make a program that open a text file present in thestartupfolder.Write something to it and close it. Can i use%APPDATA%in my path because user name is changed at every pc I used as below but its not working. ``` FILE *fptr fptr = fopen("%APPDATA%\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\myfile.tx...
The regular way to get environment variables is to usegetenv ``` char * appdata = getenv("APPDATA"); if (!appdata) { /* error */ } char buffer[0x400]; snprintf(buffer, sizeof(buffer) , "%s\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\myfile.txt", appdata); fptr = fopen(buffer,"w"); ``` Please keep in mind...
I learnt to program using Java in eclipse. Recently I've wanted to learn C and C++ so I installed the C/C++ version of eclipse. I still have some Java programming to do though and the option to create a new Java project has disappeared. Is there an easy way to have both C++ and Java projects accessible on eclipse or ...
Eclipse is a platform, you can most certainly use it for C/C++ and Java at the same time. The development tools for each language are actually just plugins. That said, many people prefer to use separate installations for each language, so as to keep their workspaces clean. If you want to install the Java tools in you...
I've seen some guide on generating random numbers with C: two things got me wondering: it is said that in addition to stdlib.h and time.h libraries I have to include the math.h library for it to work, why? (afaik the srand and rand functions are in stdlib)?in the example the srand function is written the following wa...
The functiontimereturns atime_tvalue, whilesrandexpect anunsigned intargument. Without the cast, the compiler may produce a warning and depending on the compiler flags this may cause the compilation to fail. In general it is good practice to avoid warnings. Nothing in the line you show requires the inclusion ofmath.h...
I'm trying to change the scheduling scheme of running threads in freeBSD. The default thread scheduling of freeBSD is based on the thread's priority but I want to change it to another condition. I was wondering which of the following functions are responsible for this scheduling,tdq_runq_add()in sched_ule.c orrunq_cho...
Selecting the tread that will be run next is done inchoosethread()in/usr/src/sys/kern/kern_switch.c. This in turn callssched_choose(). Depending on which scheduler you're using, this is in/usr/src/sys/kern/sched_4bsd.c(for the old scheduler) or/usr/src/sys/kern/sched_ule.c(the ULE scheduler, which is the default now)....
i have to filter out the "IRC request" packet form the list of capture packet in wireshark the filter expression is "irc.request",but i am not able to write the same filter expression for lipcap so please provide me the filter expression for libpcap Thank you
The libpcap filter syntax is documented at:http://www.tcpdump.org/manpages/pcap-filter.7.html Unfortunately, it does not directly recognize the IRC protocol. However, Wireshark determines whether an IRC message is a request or response by looking at the tcp port (is the message to or from port 6667) and we can do tha...
I've never seen this kind of cast: ``` (CGRect){.origin = CGPointZero, .size = contentSize} (CGPoint){0,1} ``` Can someone explain the logic? Is this a C language feature? Or only in Objective-C? Thanks.
It's called adesignated initializerand it's a feature of the C language. The cast in front is a convenient way to initialize structures on a single line or give as an argument to a function, e.g. Structure initializing: ``` struct a test; test.member1 = 3; test.member2 = 5; // equals struct a test = (struct a){ ....
``` struct list{ int a,b,c; struct list *next, *previous; } ``` Now I need to know the difference in memory allocated in the two scenarios: ``` 1) struct list *ptr = (struct list*)malloc(sizeof(struct list*)); ``` and ``` 2) struct list *ptr = (struct list*)malloc(sizeof(struct list)); ```
You have typed the same line twice. Both are same. ``` struct list *ptr = (struct list*)malloc(sizeof(struct list*)); ``` Here you have allocated the memory whose size issizeof(struct list*) Here struct list * is a pointer to type struct list. so size of any pointer on 32 bit machine is 4 byte and on 64 bit machine...
``` #include <stdio.h> #include <stdlib.h> #include "imageio.h" #include "imageio.c" int main() { int i,j; IMAGE image = loadImage("test.bmp"); printf("Enter the number of pixels in the x axis: "); scanf("%d", &image.width); printf("Enter the number of pixels in the y axis: "); scanf("%d", &im...
``` for (i=0;i<image.width; i++) for (j=0;i<image.height; j++){ // i ??? ``` Do you meanj < image.height?
What is the difference betweenwait(null)andwait(&status)in c system programming? And what is the content of the pointer status ?
If you callwait(NULL)(wait(2)), you only wait for any child to terminate. Withwait(&status)you wait for a child to terminate but you want to know some information about it's termination. You can know if the child terminate normally withWIFEXITED(status)for example. statuscontains information about processes that you...
I want to generate a random number between multiple ranges in C. Also I want to take the input from user for the number of ranges. I do have a function for generating random number within one range, can I use that function to generate such multiple ranges? Please Help.
Define a range equal in length to the sum of your ranges, generate a random number in that range, then see in which part it falls. Eg. for ranges (2,5) and (100,200) generatexin (0,103), then if it is less than 3, return2+xelse return100+x-3.
Is it possible under VS 2008 C/C++ compiler, compiling the following code in/as a .c file ? ``` int f(int bounds) { int sum = 0; for( int i = 0; i < bounds ; i++ ) { .... } return sum; } ``` GCC seem to be ok with that C syntax, but it looks like VS'2008 is more expecting something like: ``` int f(int ...
Is it possible under VS 2008 C/C++ compiler, compiling the following code in/as a .c file ? No. This is a C99 feature and MSVC doesn't support C99. You must have to declareibeforeforloop.
I was trying get solution tothisquestion. I tried this code with gcc as the compiler and the output was not as expected. ``` #include <stdio.h> int main(void) { char s1[10],s2[10],s3[10]; scanf("%s,%s,%s ",s1,s2,s3); printf("%s\n",s1); } ``` Input ``` abc,def,ghi ``` Output ``` abc,def,ghi ``` I...
No,scanf()doesn't know that it should stop the first string conversion at the comma, since a string can contain the comma. You can do this using the%[]conversion specifier, use%[^,]to include all characters except the comma.
I'm studying C and TCP/UDP. As the title... Is there any difference between inet_aton() and gethostbyname() in C? From what I know, both convert an IP address from a string to a number.
gethostbyname() is obsolete. You should usegetaddrinfo(). inet_aton() only works for IPv4. Also,inet_aton() only convert a IPv4 notion (0.0.0.0) to int,getaddrinfodoes DNS resolution.
This question already has answers here:const usage with pointers in C(6 answers)Closed9 years ago. This should be a pretty straightforward question. I'm brushing up on my C and want to make sure I'm understanding const pointers correctly. Say I have a functionstatic void penv(const char * const * envp); I think this...
The rule says thatconstshould apply to what comes before it, but there's a syntactic sugar: ``` const char ``` is equivalent to ``` char const ``` thus the reading is: "penv takes a pointer to a constant pointer to a constant char" Thus you're correct :)
I would like to know how it's possible to do this : I am actually doing some basic program, and the user has to enter something like this (via a scanf of course) : word1,word2,word3 BUT I would like to geteach word in one variable, that means without,. (But the user has to enter the ,). So I want to get : $word1, ...
If there will always be only three words in the input, then yes can most definitely usescanf, because it actually does simple pattern matching: ``` if (scanf("%[^ ,] , %[^ ,] , %[^ \n]", string1, string2, string3) == 3) { /* Read three words */ } ``` If you can have a variable number of words, then read aboutstr...
Suppose I have the following code: ``` struct client { char buf[MAXLINE]; int curp; }; struct client *c; ``` I want to know what is the type of each of the following variables and why? ``` x1 = c->buf; x2 = *c->buf; x3 = &c->buf[c->curp]; x4 = *c; ``` I know that c is a pointer to struct client. Thus x4 ...
The possible types as, x1 = c->buf; x1 is pointer to a character since buf is the base pointer. x2 = *c->buf; x2 is a character since base pointer is dereferenced to get the first character x3 = &c->buf[c->curp]; x3 is a pointer to a character since c->buf[c->curp] gives a character and&gives its address x4 = *...
I have made a successful call web request with a socket and printed out the result. This is done with the send and recv method. Now I would like to be able to give a ruff indication of how many bytes are received and how many bytes needs to be downloaded. But I have simply no clue how to achieve this in C. Code for r...
The socket is limited to packets, it has no clue about what you are downloading. If you are downloading a file from a web server using HTTP, you can however use the HTTP response header to get the desired information "Content-Length" See:http://en.wikipedia.org/wiki/List_of_HTTP_header_fields Thus read the first pac...
I have included: ``` #include "stdio.h" #include <readline/readline.h> #include <readline/history.h> ``` and my compiler includes the flag ``` -lreadline ``` but I am still receiving the error message: ``` fatal error: 'readline/readline.h' file not found ``` I am trying to use the function, readline(); Def...
You reference a Linux distribution, so you need to install the readline development libraries On Debian based platforms, like Ubuntu, you can run: ``` sudo apt-get install libreadline-dev ``` and that should install the correct headers in the correct places,. If you use a platform withyum, like SUSE, then the comm...
I am confused about the words: Pre-processor directive. ``` #include <stdio.h> int main(void) { puts("It's me, your first program."); return 0; } ``` When the preprocessor meets that directive, it replaces the directive with the content of the file whose name is listed in the directive (in our case, this is th...
There are other preprocessor directives, for example: ``` #define MAXLEN 256 ``` The word "directive" here means the source code line is directing the C preprocessor to do something. And, as for understanding the Byzantine layers of jargon complexity in a widely adopted language that's well over a generation old, w...
After quite a bit of searching, I have been unable to find a good way to dynamically generate query strings and x-www-form-urlencoded post data. I am writing a library that will do this quite frequently. If need be, I can write a utility to build these strings, but I would really like to avoid re-invinting the wheel. ...
This took a little bit of Google-fu (c encode query string -C# -objective), but I ended up with: libccgi-C CGI Library 1.1 Specifically, its functionCGI_encode_query()
I need to calculate the value of e^x. The loop is infinity and should stop when i get the precision 0.001, but i do not know how to get this precision. ``` float exp(float x){ float ex=1,precision=0.000,powX=1.0,fat=1.0; int partInt; int i,j; for(i=1; precision!= 0.001; i++){ for(j=1; j<=i; ...
You could use adouble prevto keep track of the result produced by the previous iteration. Stop whenabs(prev - ex) < precision.
What is the version of C used in GCC? C99, C11 or C90? I thought was the GCC use C99 but I was mistaken: ``` for(int i = 0; i < 100; i++){ ... } ``` error: ‘for’ loop initial declarations are only allowed in C99 mode.
According to2 Language Standards Supported by GCC: The default, if no C language dialect options are given, is-std=gnu90; this is intended to change to-std=gnu11in some future release.
here is the code: ``` #include <stdio.h> int main(){ char asd[10]; gets(asd); printf("\nEnter => "); scanf("%[^\n]s",asd); char *token; char delim[5] = " "; token = strtok(asd, delim); int total = 0; while(token != NULL){ printf( " %s \n", token); int val = a...
You need the proper include: ``` #include <string.h> ```
memcpycopies n bytes from the source to the destination. (linux man page) and a simpleassignmentis doing the same, right? So where are the differences, and what would be a real use case ofmemcpy?
Yes and no. Simple assignment will copy values, as you say, so assigning a standard variable, be it a standard data type or a struct, will work fine. The issue typically comes when using arrays. Take the following example: ``` int p,q; struct myStruct s1, s2; char str1[50]; char str2[50]; // ... // Assign stuff to al...
I am browsing though the XCB sources and I found this weird struct member: ``` void (*return_socket)(void *closure); ``` What does that mean? What's another way to write this?
That is afunction pointer. It points to a function that returnsvoidand receives avoid *as parameter. For example, you could use that as: ``` void myFunction(void *closure) { printf("myFunction called with closure=%p", closure); } void (*return_socket)(void *closure) = myFunction; ```
My task is to find fibonacci series elements not larger than given in input. The problem is that I get one extra result (larger then number from input). for example: when I enter 15 as a max, I get 1,1,2,3,5,8,13,21 which is incorrect. My code: ``` #include <stdio.h> int main() { int n, first = 0, second = 1,...
You should check the new element for being to big, not the last found element for being smaller.I won't go into more detail, because you said it's homework and probably don't need more.
What is the difference betweenwait(null)andwait(&status)in c system programming? And what is the content of the pointer status ?
If you callwait(NULL)(wait(2)), you only wait for any child to terminate. Withwait(&status)you wait for a child to terminate but you want to know some information about it's termination. You can know if the child terminate normally withWIFEXITED(status)for example. statuscontains information about processes that you...
Is there a pattern for, or a standard way to permute bits according to apermutation tablethat specifies for each bit position of the result - which position is taken from the source. I.e. table0322would create result0011from0010 My current strategy has been to read each entry of the table - create a bitmask and then...
It's really expensive to use thepowfunction for this. The repetitive and home-brewed parts are unavoidable. A better way ``` result = 0; for ( i = 0; i < table_size; i++ ) { result <<= 1; if ( source & (1 << table[i]) ) result |= 1; } ```
Been working on an essay of mine and i stumble upon this weird thing. For some reason the following snippet is responsible for the failing of my programm. ``` for(i=0; i< DOC; i++){ for(j=0;j<MAXWORDS;i++){ average[list[i]][j]+=array[i][j]; } } for(i=0; i< k; i++){ for(j=...
not sure what you are going for but on ``` for(j=0;j<MAXWORDS;i++){ ``` you are incrementing i not j so it seems as though you have an infinite loop.
I need to know if I can store private data for a thread in the following way. ``` pthread_create(&threads[i], NULL, student, (void *) i); void *student(void *arg) { int mybooks[3]; int mybooks_index = 0; ....... } ``` Is this possible or is the only way of doing is sending a pointer to a struct as an a...
Each thread has its own stack.mybooksandmybooks_indexare automatic variables and thus allocated on the stack (i.e. per thread). They are only deallocated whenstudentexits. So yes, this will work. If you had made themstatic, they would be shared between threads rather than be private to the thread.
In my current program I am having an issue where, when I divide a number by a larger number I am just given 0. For example if I divide -272 by 400 I receive 0. ``` y=x/400; printf("%f\n", y); ``` This is the only piece of code causing issues. x is a negative integer 1-500 and y is initialized as a float. Where am I...
Write something like this y = x/400.0f or y = (float)x / 400
I'm trying to write a piece of code that will take 6 inputs and return smallest and largest number when its done. Problem I'm having is, during 6th loop no matter what number I input, it overwrites my _max variable ignoring condition in IF statement. ``` #include <stdio.h> int main() { int i; int _min...
this is what you want... loop over all of them. ``` for(i=0;i<6;i++) ```
I'm having trouble with this line: ut_slot = malloc(tab_size * sizeof ut_slot_t); These are the variables which are defined in the header file: typedef struct _ut_slot { ... ... } ut_slot_t, *ut_slot; error is written in title, any help?
Ifut_slot_tis a type then you have to put it in parentheses: ``` ut_slot = malloc(tab_size * sizeof(ut_slot_t)); ``` Edit:The above is correct (I think!), but only one part of the problem. The other answer solves it completely.
Is it necessary to have in the clientbind, if I want to receive data from a server? I've seen a schema (look at the image below), and it seems that it's not necessary. But from what I know, bind is necessary to give an address to a socket. If I don't "bind" the socket, how can I send data to it?
A call tobind()only binds a socket to a port. Hence, in this case, it is required for aserverto bind to a port. A client, on the other hand, just needs to send to or receive data from a specific port (server); hence, it justconnect()s and then does arecvfrom()andsendto(). Read last paragraph of section 5.3:http://be...
Somewhere I read that if I never return frommain()loop, I can spare~66Bytes with some compiler switch inavr-gcc, but I couldn't find the site anymore. This is for embedded: ``` main() { while(1) { // do stuff } } ```
Forgccyou can use a special attribute to indicate that your function does not return: ``` int main() __attribute__ ((noreturn)) { for (;;) { // do stuff } __builtin_unreachable (); } ``` Optionally you can add__builtin_unreachable ();to indicate that some part of the code can never be reached. ...
In C I am reading binary data from a file into a vardatalike this: ``` unsigned char *data; data = malloc(size); int read_size = fread(data, 1, size, fp); ``` I want to prepend the vardatawith<filename><size>of the file. How can I achieve this?It's not a legal C string because it's binary data with null bytes potent...
Allocate enough memory todata.Copy the prefix into it.Get a reference to just behind what had been copied in 2..Pass this reference tofread().
I have the following C code. ``` #include <stdio.h> #include <stdlib.h> int main() { while (1) { int *test = malloc(sizeof(*test)); test = 500; free(test); } return 0; } ``` The free function does not seem to work as the allocated memory grows to 2GB within a few seconds. What is...
You can onlyfreea pointer that is a return ofmalloc. In writingtest = 500, you've changed the memory location pointed to bytest. Trying to free that isundefined behaviour. To assign a value to your allocated integer,derefenceit:*test = 500;
What could go wrong if the reader of a pipe forgets to close fd[1] or if the writer of a pipe forgets to close fd[0]?
You'll have a file handle leak (as long as the process that has the file descriptor open is running). Worst thing that can happen is that you run out of file descriptor handles if you havelotof pipes. There's usually a soft and a hard limit (seeulimit) per user, and also a system wide limit (although you're unlikely ...
I need to know if I can store private data for a thread in the following way. ``` pthread_create(&threads[i], NULL, student, (void *) i); void *student(void *arg) { int mybooks[3]; int mybooks_index = 0; ....... } ``` Is this possible or is the only way of doing is sending a pointer to a struct as an a...
Each thread has its own stack.mybooksandmybooks_indexare automatic variables and thus allocated on the stack (i.e. per thread). They are only deallocated whenstudentexits. So yes, this will work. If you had made themstatic, they would be shared between threads rather than be private to the thread.
In my current program I am having an issue where, when I divide a number by a larger number I am just given 0. For example if I divide -272 by 400 I receive 0. ``` y=x/400; printf("%f\n", y); ``` This is the only piece of code causing issues. x is a negative integer 1-500 and y is initialized as a float. Where am I...
Write something like this y = x/400.0f or y = (float)x / 400
I'm trying to write a piece of code that will take 6 inputs and return smallest and largest number when its done. Problem I'm having is, during 6th loop no matter what number I input, it overwrites my _max variable ignoring condition in IF statement. ``` #include <stdio.h> int main() { int i; int _min...
this is what you want... loop over all of them. ``` for(i=0;i<6;i++) ```
I'm having trouble with this line: ut_slot = malloc(tab_size * sizeof ut_slot_t); These are the variables which are defined in the header file: typedef struct _ut_slot { ... ... } ut_slot_t, *ut_slot; error is written in title, any help?
Ifut_slot_tis a type then you have to put it in parentheses: ``` ut_slot = malloc(tab_size * sizeof(ut_slot_t)); ``` Edit:The above is correct (I think!), but only one part of the problem. The other answer solves it completely.
Is it necessary to have in the clientbind, if I want to receive data from a server? I've seen a schema (look at the image below), and it seems that it's not necessary. But from what I know, bind is necessary to give an address to a socket. If I don't "bind" the socket, how can I send data to it?
A call tobind()only binds a socket to a port. Hence, in this case, it is required for aserverto bind to a port. A client, on the other hand, just needs to send to or receive data from a specific port (server); hence, it justconnect()s and then does arecvfrom()andsendto(). Read last paragraph of section 5.3:http://be...
Somewhere I read that if I never return frommain()loop, I can spare~66Bytes with some compiler switch inavr-gcc, but I couldn't find the site anymore. This is for embedded: ``` main() { while(1) { // do stuff } } ```
Forgccyou can use a special attribute to indicate that your function does not return: ``` int main() __attribute__ ((noreturn)) { for (;;) { // do stuff } __builtin_unreachable (); } ``` Optionally you can add__builtin_unreachable ();to indicate that some part of the code can never be reached. ...
I am trying to learn MPI. How would I find out the processwith the highest rankwithinMPI_COMM_WORLDin mpi 3? ``` MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); MPI_Comm_size(MPI_COMM_WORLD, &p); //More code here MPI_Finalize(); ``` I know thatMPI_Comm_rank(MPI_COMM_WORLD, ...
To get the highest ranking process, you can just useMPI_Comm_size(MPI_COMM_WORLD, …)to determine the total number of process on theMPI_COMM_WORLDcommunicator. Since every process is part of that communicator, and process are enumerated from 0, to get the rank of the highest ranking process just subtract 1 from MPI_COM...
Good day. What is proper way initializing COM interface reference count ? I see many examples, where reference count is initilialized to the1, but also see examples where is0set. What is diffirence ?
You have to set it such way that when the lastRelease()is called the object takes care of itself. This most often means that when you create the object it must have reference count of 1 right before you handle the object pointer to the caller who asked for the object. Whether you initialize the reference counter to ze...
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.Closed9 years ago.Improve this question I am getting characters from UART for example "\n43\n" or "\n912\n". I intend to make this an integer in or...
you can do following safely as character ASCII is less than256. ``` int combine(char a, char b, char c) { return (a << 20) | (b << 10) | c; } ``` This works when value of a,b,c is less than around1000, as2^10 = 1024. To get them back : ``` a = combined >> 20; b = (combined >> 10) & 0x3ff; c = combined & 0x3ff...
I try to read some data from one fd, but failed with error message"Invalid argument!". ``` struct inotify_event eventHdr; int head_read_len = (int)read(ctx->fd, (void *)&eventHdr, sizeof(inotify_event)); if(head_read_len == -1){ _debug("read eventHdr failed!!!!\n"); perror("read eventHdr!"); //Print...
The reason is that: The fd of inotify system call can not be partially read.Otherwise, it will return "Invalid argument"! Use a buffer with large enough bytes!
I think i may be losing it but can anyone double check my sanity? This is the only code i wrote in a new file to see my project file is not messed up. Error: This declaration has no storage class or type specifier Error: Expected a ";"
On a global level you can only have declarations and definitions, not statements (likeg.a = 1;is) or expressions.
The code: ``` #include <stdio.h> int main(int argc, char *argv[]) { //what happens? 10*10; //what happens? printf("%d", 10*10); return 0; } ``` What happens in memory/compilation in this two lines. Does it is stored? (10*10)
The statement ``` 10*10; ``` has no effect. The compiler may choose to not generate any code at all for this statement. On the other hand, ``` printf("%d", 10*10); ``` passes the result of10*10to theprintffunction, which prints the result (100) to the standard output.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question appears to be off-topic becauseit lacks sufficient information to diagnose the problem.Describe your problem in more detail orinclude a minimal examplein the question itself.Closed9 years ago.Improve this q...
Useabsfunction to find absolute value and then rearrange the array elements. You will need to search your array.
When reading process quits, how do i determine it from writing process before write call blocks ? Normally when read side closes, write call on the write side should return an error right? client ``` while(!timeout) { read(fd, message, BUFFER_SIZE); } ``` server ``` while(1) { length = write(fd, message, s...
Read carefullyfifo(7): When a process tries to write to a FIFO that is not opened for read on the other side, the process is sent a SIGPIPE signal. You could -and probably should- usepoll(2)to test dynamic readability or writability of a fifo or pipe or socket file descriptor (seethis answerabout a simplist...
Considering the following code ``` #include <stdio.h> int main() { while(1) { sleep(1); printf("X"); } return 0; } ``` The output is nothing, until the buffer gets overflowed and subsequently flushed automatically by the system. Why does it then not get buffered in this situation?:...
The output is still buffered, but the overflowing of the buffer (and thereby the flushing) happens so often in the second example that it's impossible to notice it. If you run this on a system much slower than todays modern gigahertz PC's, you will definitely notice a difference.
I am writing a program which use the library openssl. My program is functionnal, but when i try to execute it with valgrind, I have a segmentation fault. When I try to juste execute it (on the os), there is no problem, even when I use gdb. I red my code many times and I don't see where the error is. Is it possible t...
Can valgrind report a segmentation fault + coredump when there isn't? Not likely. The problem is probably in you coder, and the additional instrumentation provided by Valgrind exposes the bug. Valgrind should be telling you where the problem is. With OpenSSL, the trick is differentiating the "benign findings" from ...
I am using POSIX IPC and according to the documentation -http://man7.org/linux/man-pages/man3/mq_send.3.html mq_send() method only sends char* data and mq_recv() recieves only character data. However, I want to send a custom struct to my msg queue and on the receiving end, I want to get the struct. sample struct: `...
You just need to pass the address of the struct and cast it to the appropriate pointer type: const char * formq_sendand char * formq_receive. ``` typedef struct Req { pid_t pid; char data[4096]; } Req; Req buf; n = mq_receive(mqdes0, (char *) &buf, sizeof(buf), NULL); mq_send(mqdes1, (const char *) &buf, sizeo...
Code: ``` const char* const* const* foo(int bar); ``` I've seen double consts before which prevent the modification of the pointer too. First time i've seen triple const in my life. Wondering what its use is.
In your example all but the top level of indirection allconstqualified. ``` const char /* const qualified base level */ *const /* const qualified level 1 */ *const /* const qualified level 2 */ * /* regular level 3 */ foo(int bar); ``` foois a function...
I am going to offload some computation to Xeon Phi but would like to test different APIs and different apporached to the parallel programming first. Is there a simulator / emulator for Xeon Phi (either Windows or Linux) ?
In the event that future internet users see this question and wonder about Knights Landing simulation, the Intel SDE (https://software.intel.com/en-us/articles/intel-software-development-emulator) emulates AVX-512. For the uninitiated, Knights Landing is the official code name for the next-generation of Intel Xeon Ph...
I'm trying to write an extension for php using swig. I need to know the absolute path of the current php file in my extension code. I used __ FILE __ in my C code but it returns current c file name.
finally i found the solution. to access __ FILE __ in your php extension, you can use like this: ``` char *file_name = zend_get_executed_filename(); ```
I was writing a code that involves handling a 2D array of dimensions [101]X[101] in C. However I am constrained in terms of memory being used at a given point of time. ``` void manipulate(int grid_recv[101][101]) { //Something } void main() { int grid[101][101]; manipulate(grid); } ``` So lets say I crea...
No. In C, arrays cannot be passed as parameters to functions. What you actually do is creating a pointer pointing the array. So the extra memory you use it only the size of that pointer created.
I am getting this error when trying to compile my program the code part I am getting this error is: ``` matrixType MatrixADT::add(matrixType M1, matrixType M2){ matrixType M; for(int i=0;i<M1.matDimension;i++){ for(int j=0;j<M2.matDimension;j++){ M.matDimension[i][j] = M1.matDimension[i][j...
Based on the definition ofmatrixType: ``` struct matrixType{ int matDimension; int matValues[10][10]; }; ``` You need to change ``` M.matDimension[i][j] = M1.matDimension[i][j] + M2.matDimension[i][j]; ``` to ``` M.matValues[i][j] = M1.matValues[i][j] + M2.matValues[i][j]; ```