question
stringlengths
25
894
answer
stringlengths
4
863
``` int main(void){ float f=0,ff=0; if (scanf("%f %f",&f,&ff) == 2){ printf("True\n%f %f",f,ff);fflush(stdout); } else{ printf("False\n%f %f",f,ff);fflush(stdout); } getchar(); return 0; } ``` If my input is "6.81 7.kj" it returns true!!
7.is a valid float. The fact that there's more input left is irrelevant to the success of the call.
I'm not sure what would be the right approach in this situation. I need to map Windows drive letter to a custom Web DAV connected server. Or in other words, when a user goes to My Computer, then, say, goes to drive Z: they should see files and folders from that Web DAV server. My preferred programming language is C/C...
No. What you are asking for can be accomplished by creating aShell Namespace Extensioninstead.
I have many functions like: ``` void write(char* param, int len) { // } ``` And I notice that I almost never use the&operator for arguments. When I pass an array: ``` char in[20]; write(in, 20); ``` I dont need it, but when I pass a single value: ``` write(5, 1); ``` I don't seem to need it, and when I pass ...
Are you sure about your second case? It doesn't compile for me and should be ``` char in = 5; write(&in, 1); ```
``` typedef struct _name name; struct _name { char name[256]; }; // ... name Name; char *buf = (char*)malloc( 256*sizeof(char) ); // ... // if I do not want to write strcpy (Name.name,buf); // and write: list_name_insert (&List,0,&Name); // if just write: list_name_insert (&List,0 /* index */,(name*)buf /*...
The answer to these two questions rolled into one is no and no. Astructwith one member has astructtype; it does not have the same type as its single member. Also, arrays and pointers are not the same thing. An array can decay to a pointer as in ``` char buf[256]; char *p = buf; ``` but not the other way around.
I looked at couple of instances wherein I see something likechar fl[1]in the following code snippet. I am not able to guess what might possibly be the use of such construct. ``` struct test { int i; double j; char fl[1]; }; int main(int argc, char *argv[]) { struct test a,b; a.i=1; a.j=12; ...
It's called "the struct hack", and you can read about it at theC FAQ. The general idea is that you allocate more memory then necessary for the structure as listed, and then use the array at the end as if it had length greater than 1. There's no need to use this hack anymore though, since it's been replaced by C99+fl...
I'm not sure what would be the right approach in this situation. I need to map Windows drive letter to a custom Web DAV connected server. Or in other words, when a user goes to My Computer, then, say, goes to drive Z: they should see files and folders from that Web DAV server. My preferred programming language is C/C...
No. What you are asking for can be accomplished by creating aShell Namespace Extensioninstead.
I have many functions like: ``` void write(char* param, int len) { // } ``` And I notice that I almost never use the&operator for arguments. When I pass an array: ``` char in[20]; write(in, 20); ``` I dont need it, but when I pass a single value: ``` write(5, 1); ``` I don't seem to need it, and when I pass ...
Are you sure about your second case? It doesn't compile for me and should be ``` char in = 5; write(&in, 1); ```
``` typedef struct _name name; struct _name { char name[256]; }; // ... name Name; char *buf = (char*)malloc( 256*sizeof(char) ); // ... // if I do not want to write strcpy (Name.name,buf); // and write: list_name_insert (&List,0,&Name); // if just write: list_name_insert (&List,0 /* index */,(name*)buf /*...
The answer to these two questions rolled into one is no and no. Astructwith one member has astructtype; it does not have the same type as its single member. Also, arrays and pointers are not the same thing. An array can decay to a pointer as in ``` char buf[256]; char *p = buf; ``` but not the other way around.
I looked at couple of instances wherein I see something likechar fl[1]in the following code snippet. I am not able to guess what might possibly be the use of such construct. ``` struct test { int i; double j; char fl[1]; }; int main(int argc, char *argv[]) { struct test a,b; a.i=1; a.j=12; ...
It's called "the struct hack", and you can read about it at theC FAQ. The general idea is that you allocate more memory then necessary for the structure as listed, and then use the array at the end as if it had length greater than 1. There's no need to use this hack anymore though, since it's been replaced by C99+fl...
If I start a matlab engine using the api function engOpen, and then set the engine's visibilty to TRUE, do I have any way of being notified if the user shuts the engine down (as they can do )? More generally, after opening an instance and making it visible, do I have any way of knowing if the engine pointer I hold is...
Just an idea, why can you useengGetVariablewhich returns pointer to a newly allocated mxArray structure, or NULL if the attempt fails. So when starting the engine, initiate also a dummy variable and then ifengGetVariablefails it means the named dummy variable does not exist, which should imply the engine down... Of c...
I wanted to know like where does the stderr dumps its content. I have a question like whether it dumps to syslog? Please explain.
stderris just another output stream, just likestdout. Where it's hooked up depends on how the application is called. For example if I runfoo.exe 2> errors.txtthenstderrwill write to the specified file.
``` typedef int (*http_data_cb) (http_parser*, const char *at, size_t length); ``` As far as I know,typedefassigns new name to types in standard library.In this situation an instance of*http_data_cbis an int, but how about(http_parser*, const char *at, size_t length)? Here is the link of thewhole code Thanks,
It is a way do typedef a type that is a pointer to function. Typically in such typedefs you would not name the arguments to the function, but only indicate their type. So a variable of the typehttp_data_cbwill be a pointer to a function returning int result and taking three arguments of typehttp_parser*,const charand...
This might sound like a retarded question but I am just learning C and all the websites I looked at this showed you the command to do it (project < somefile.txt) but not where to do it. Does it go in my project somewhere or command prompt? And if it is command prompt how do I get to where I need to enter it?
It goes on your command prompt. You first need to cd into location where your compiled binaries are. That command basically says "run project and feed contents of somefile.txt into it" If you're on Windows hit Win+R and run cmd. On UNIX you should findterminalapp somewhere in your menu.
In C pseudo-code: ``` while (1) { fifo = open("fifo", O_RDONLY | O_NONBLOCK); fd_set read; FD_SET(fifo, &read); select(nfds, &read, NULL, NULL, NULL); } ``` The process sleeps as triggered byselect()until another process writes intofifo. Afterwards it will always findfifoas a readable file descriptor...
You opened that FIFO as read only (O_RDONLY), whenever there is no writer to the FIFO, the read end will receive anEOF. Select system call will return onEOFand for everyEOFyou handle there will be a newEOF. This is the reason for the observed behavior. To avoid this open that FIFO for both reading and writing (O_RDW...
``` #include <stdio.h> #include <string.h> #define NAMELENGTH 20 #define MAXPEOPLE 10 struct people{ char name[NAMELENGTH]; int ratings[MAXPEOPLE]; }; int main(void) { struct people *men[MAXPEOPLE]; strcpy(men[2]->name,"pie"); return 0; } ``` It crashes upon trying to assign any value to men[...
You have only created an array of pointers, not an array ofstruct people: ``` struct people *men[MAXPEOPLE]; ``` This only creates an array of pointers, but the pointers don't yet point to anything because you haven't allocated any space for them. This means that you are copying into anamethat doesn't actually exis...
do we need a read lock for reading an integer other than if the variable is less than memalign and during some caching situation ?
The analyser assumes that because the address off1()has been taken, it could be called through that function pointer from any context. If, for example, you have one thread updatingx: ``` lock xlock; update x; unlock xlock; ``` and another thread callsf1()simultaneously through the function pointer, the access tof1(...
I need to make this user space buffer to zero before copying the string c into the buf How to initialize the buffer to zero. ``` static ssize_t myread(struct file *file,char __user *buf,size_t len, loff_t *fops) { printk(KERN_INFO"My read with length %d \n",len); len = strlen(c); if(copy_to_user(buf,c,l...
use memset See the manpages for usage, it will set a constant byte to a range of consecutive buf addrs
I am trying to compute the average color of a region of a RGB image. The interested region of the image is represented by a mask. I usedcvAvgfunction in opencv, but somehow I am not able to do it right. I used the following code: ``` //Prepare the mask CvMat*regionMask = cvCreateMat(inImage->height, inImage->width, C...
I figured it out. I replaced the statementmaskData[(p.y)*inImage->width + p.x] = 1;withmaskData[(p.y)*maskData->step + p.x] = 1;and it works fine now. Thanks.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. What is to be included in the start...
You can downloadDS-5which claims to contain Cortex R5 bare-metal startup code (I didn't check that myself). From DS-5'schangelog Examples: bare-metal start-up code added for the Cortex-R5(F) processor, including vector table, exception handlers, MPU, caches, TCM and VFP initialization, based on the Versatile Express...
This is one of the conditions in my program: ``` if(Debug)fprintf(stdout,"Direction dir %d quot %d rem %0.2f %s\n",direction,quotient, remain, cardinal[quotient]); ``` I have defined everything and have usedstdlib.hbut it keeps returning ``` expected expression before ')' token ``` I use minGW compiler in ECLIPSE...
probably you have: ``` #define Debug ``` With is good for conditional compilation: ``` #ifdef Debug ... #endif ``` But the if need an expression inside the (). Use, for example: ``` #define Debug 1 ``` if you want to print, and0if you dont want. (but now use#if Debugfor conditional compilation)
I need a C/C++ function likeos.path.isdir(path)inPython. I found a very similarquestionbut i'm using Linux.
The POSIX solution isstat(): These functions return information about a file. Basically, you hand it an instance of thestruct stat, and if the call succeeds (check this first!) you get various fields filled in that describe the file. You can then use theS_ISDIR()macro on thest_modefield to figure out if it's a dire...
I have this equation its output using a sci calc is : 0.017... but when i run it in c its output is :0.84.. The input is 1 Equation is: sin(x) - x^4 + 1 ``` float sinp(float p1) { float fop; float ppowers; printf("%f",p1); ppowers = pow(p1,4); fop = sin(p1)-ppowers+1; return (fop); } ``` is...
In mathemtics and in all computer languages trigonometric functions work in radians. If you want to work in degrees you should make the conversion (or define your own sin_degrees function) like: ``` double sin_degrees(double degrees) { return sin(degrees * (M_PI/180.0); } ```
This question already has answers here:Closed10 years ago. Possible Duplicate:returning a pointer to a literal (or constant) character array (string)? Is the code below correct? ``` const char* state2Str(enum State state) { switch (state) { case stateStopped: return "START"; case stateRunning: ret...
The code is fine. You're returning a pointer to a string literal which will be valid for the duration of your program. From the C89 standard: 3.1.4 String literalsA character string literal has static storage duration and type ``array of char ,'' and is initialized with the given characters.
I need to get file type without using file extensions on linux. There is "file" utility, which can do this. How can I do the same using C/C++? Not 'system(const char *)', of course... Thanks)
AFAIKfileis implemented overlibmagic. For more reference see: filesourcesand maybe this link:http://linux.die.net/man/3/libmagic.
Issetjmpandlongjmpavailable in kernel space? I want to jump between functions. Is it possible to run gclib headers from kernel modules? If yes, then how to use them in kernel modules?
Regarding glibc, the answer is no. When programming in kernel space standard c library is not available, however, the kernel itself implements some of the functionality of libc. You can find relevant headers under linux/include. Regarding setjmp, I don't remember, but you can use lxr(linux cross reference) to search ...
i'm trying to compile a project on VS2010 for 64 bits wrote in C and use CUDA 5.0 and GLib. I already had a working profile for 32 bits and everything goes ok. On configuration manager i created a new context for 64 bits with settings copied from the 32 bits one. Then, i updated Glib paths for 64 bits version and had...
It's probably a missing library. Recent versions of Windows just give that generic message instead of a detailed message about which libraries were not found. There's also a difference in which information is provided when starting the app from the command line and starting it from Explorer. Dependency Walkerwill te...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. I want to convert an integer number...
'sprintf' will work fine, if your first argument is a pointer to a character (a pointer to a character is an array in 'c'), you'll have to make sure you have enough space for all the digits and a terminating '\0'. For example, If an integer uses 32 bits, it has up to 10 decimal digits. So your code should look like: ...
I am current working on an Android project. Since the android apk file is essentially a zip file with a different file extension, is it possible to use zlib to file the directory structure of the asset folder? The goal is to write some interfaces like opendir() and readdir() so that I can do something like: ``` DIR...
You can uselibzip(which itself useszlib) to work with zip files. It doesall you want and more.
Why would one use void *enif_alloc(size_t size) as opposed to void *malloc(size_t size); when trying to allocate memory from an Erlang C NIF? Reference does not specify much as to why. http://www.erlang.org/doc/man/erl_nif.html#enif_alloc I have seen NIF examples were malloc is used and I never see the enif_alloc...
enif_allocuses the internal erlang memory allocators, which means that if the memory already is available in the internal VM cache it can use that memory instead of doing a system call to get the memory. This can lead to faster memory allocation in some cases, you will have to measure with your code to figure out if i...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. How does GCC ensure that The Stack ...
It doesn't. If you recurse deep enough, youwilloverflow, and there's nothing the compiler can do about it. edit: I should point out that at the time I answered this question, the question simply read:"How does GCC ensure that The Stack doesn't overflow?"
I need to compute all possible combinations of n things selected r at a time where 0<=r<=n, One method to do so is generating the numbers up to 0 to 2^n-1. But I need to generate these numbers such that the numbers should be sorted on the basis of the number of bits set in that number. for n=3: ``` 0 // numbe...
Implement regular algorithm to generate the combinations, but also hold an additional array where you store the numbers sorted accoding to the 1-bits set. Then for each combination generated replace the numbers with the numbers sitting in the corresponding position minus one in the array sorted as I described.
I am not able to understand the below code with respect to the comment provided. What does this code does, and what would be the equivalent code for8-aligned? ``` /* segment size must be 4-aligned */ attr->options.ssize &= ~3; ``` Here,ssizeis ofunsigned inttype.
Since 4 in binary is 100, any value aligned to 4-byte boundaries (i.e. a multiple of 4) will have the last two bits set to zero. 3 in binary is 11, and ~3 is the bitwise negation of those bits, i.e., ...1111100. Performing a bitwise AND with that value will keep every bit the same, except the last two which will be c...
Hi I made a simple hello world C program and I am compiling it like this : gcc -c hello.cld hello.o -lc -o out I get a warning from ld :ld : _start not found defaulting to .... I do anobjdump -D hello.oand I cannot find the_startroutine in the output.What am I missing here ?
You're missing thecrt*stuff which you will see if you link withgcc -v:crt1.o,crtend.o,crtn.o. Look at howgccinvokescollect2(it's visible withgcc -v) and use the same options forld. mainfunction is not the executable entry point: some initialization for standard library is done beforemain(because it's either impossibl...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. Original page:http://acm.whu.edu.cn...
double is not enough for the precision you should use high-precision to solve it
I have a project for school and I need some help. I'm working in C and I have a server and a client. In server I make a new process for each client with fork. My question is: if I close the server with CTRL+C, how do I kill all the remaining processes ? Thanks
You can store their pids after they are created and then, when quitting, signalsigtermorsigkillto them. You can do it through shell -killallis what you are searching for under linux. You could use threads instead of processes (could you? what do the project details say?) and communicate through variables.
i'm trying to compile a project on VS2010 for 64 bits wrote in C and use CUDA 5.0 and GLib. I already had a working profile for 32 bits and everything goes ok. On configuration manager i created a new context for 64 bits with settings copied from the 32 bits one. Then, i updated Glib paths for 64 bits version and had...
It's probably a missing library. Recent versions of Windows just give that generic message instead of a detailed message about which libraries were not found. There's also a difference in which information is provided when starting the app from the command line and starting it from Explorer. Dependency Walkerwill te...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. I want to convert an integer number...
'sprintf' will work fine, if your first argument is a pointer to a character (a pointer to a character is an array in 'c'), you'll have to make sure you have enough space for all the digits and a terminating '\0'. For example, If an integer uses 32 bits, it has up to 10 decimal digits. So your code should look like: ...
I am current working on an Android project. Since the android apk file is essentially a zip file with a different file extension, is it possible to use zlib to file the directory structure of the asset folder? The goal is to write some interfaces like opendir() and readdir() so that I can do something like: ``` DIR...
You can uselibzip(which itself useszlib) to work with zip files. It doesall you want and more.
Why would one use void *enif_alloc(size_t size) as opposed to void *malloc(size_t size); when trying to allocate memory from an Erlang C NIF? Reference does not specify much as to why. http://www.erlang.org/doc/man/erl_nif.html#enif_alloc I have seen NIF examples were malloc is used and I never see the enif_alloc...
enif_allocuses the internal erlang memory allocators, which means that if the memory already is available in the internal VM cache it can use that memory instead of doing a system call to get the memory. This can lead to faster memory allocation in some cases, you will have to measure with your code to figure out if i...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. How does GCC ensure that The Stack ...
It doesn't. If you recurse deep enough, youwilloverflow, and there's nothing the compiler can do about it. edit: I should point out that at the time I answered this question, the question simply read:"How does GCC ensure that The Stack doesn't overflow?"
I need to compute all possible combinations of n things selected r at a time where 0<=r<=n, One method to do so is generating the numbers up to 0 to 2^n-1. But I need to generate these numbers such that the numbers should be sorted on the basis of the number of bits set in that number. for n=3: ``` 0 // numbe...
Implement regular algorithm to generate the combinations, but also hold an additional array where you store the numbers sorted accoding to the 1-bits set. Then for each combination generated replace the numbers with the numbers sitting in the corresponding position minus one in the array sorted as I described.
I am not able to understand the below code with respect to the comment provided. What does this code does, and what would be the equivalent code for8-aligned? ``` /* segment size must be 4-aligned */ attr->options.ssize &= ~3; ``` Here,ssizeis ofunsigned inttype.
Since 4 in binary is 100, any value aligned to 4-byte boundaries (i.e. a multiple of 4) will have the last two bits set to zero. 3 in binary is 11, and ~3 is the bitwise negation of those bits, i.e., ...1111100. Performing a bitwise AND with that value will keep every bit the same, except the last two which will be c...
Hi I made a simple hello world C program and I am compiling it like this : gcc -c hello.cld hello.o -lc -o out I get a warning from ld :ld : _start not found defaulting to .... I do anobjdump -D hello.oand I cannot find the_startroutine in the output.What am I missing here ?
You're missing thecrt*stuff which you will see if you link withgcc -v:crt1.o,crtend.o,crtn.o. Look at howgccinvokescollect2(it's visible withgcc -v) and use the same options forld. mainfunction is not the executable entry point: some initialization for standard library is done beforemain(because it's either impossibl...
I am current working on an Android project. Since the android apk file is essentially a zip file with a different file extension, is it possible to use zlib to file the directory structure of the asset folder? The goal is to write some interfaces like opendir() and readdir() so that I can do something like: ``` DIR...
You can uselibzip(which itself useszlib) to work with zip files. It doesall you want and more.
Why would one use void *enif_alloc(size_t size) as opposed to void *malloc(size_t size); when trying to allocate memory from an Erlang C NIF? Reference does not specify much as to why. http://www.erlang.org/doc/man/erl_nif.html#enif_alloc I have seen NIF examples were malloc is used and I never see the enif_alloc...
enif_allocuses the internal erlang memory allocators, which means that if the memory already is available in the internal VM cache it can use that memory instead of doing a system call to get the memory. This can lead to faster memory allocation in some cases, you will have to measure with your code to figure out if i...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. How does GCC ensure that The Stack ...
It doesn't. If you recurse deep enough, youwilloverflow, and there's nothing the compiler can do about it. edit: I should point out that at the time I answered this question, the question simply read:"How does GCC ensure that The Stack doesn't overflow?"
I need to compute all possible combinations of n things selected r at a time where 0<=r<=n, One method to do so is generating the numbers up to 0 to 2^n-1. But I need to generate these numbers such that the numbers should be sorted on the basis of the number of bits set in that number. for n=3: ``` 0 // numbe...
Implement regular algorithm to generate the combinations, but also hold an additional array where you store the numbers sorted accoding to the 1-bits set. Then for each combination generated replace the numbers with the numbers sitting in the corresponding position minus one in the array sorted as I described.
I am not able to understand the below code with respect to the comment provided. What does this code does, and what would be the equivalent code for8-aligned? ``` /* segment size must be 4-aligned */ attr->options.ssize &= ~3; ``` Here,ssizeis ofunsigned inttype.
Since 4 in binary is 100, any value aligned to 4-byte boundaries (i.e. a multiple of 4) will have the last two bits set to zero. 3 in binary is 11, and ~3 is the bitwise negation of those bits, i.e., ...1111100. Performing a bitwise AND with that value will keep every bit the same, except the last two which will be c...
Hi I made a simple hello world C program and I am compiling it like this : gcc -c hello.cld hello.o -lc -o out I get a warning from ld :ld : _start not found defaulting to .... I do anobjdump -D hello.oand I cannot find the_startroutine in the output.What am I missing here ?
You're missing thecrt*stuff which you will see if you link withgcc -v:crt1.o,crtend.o,crtn.o. Look at howgccinvokescollect2(it's visible withgcc -v) and use the same options forld. mainfunction is not the executable entry point: some initialization for standard library is done beforemain(because it's either impossibl...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. Original page:http://acm.whu.edu.cn...
double is not enough for the precision you should use high-precision to solve it
I have a project for school and I need some help. I'm working in C and I have a server and a client. In server I make a new process for each client with fork. My question is: if I close the server with CTRL+C, how do I kill all the remaining processes ? Thanks
You can store their pids after they are created and then, when quitting, signalsigtermorsigkillto them. You can do it through shell -killallis what you are searching for under linux. You could use threads instead of processes (could you? what do the project details say?) and communicate through variables.
I'm trying to match a character constant. I only want single characters and a few escape sequences rather than \ followed by any letter. This is very similar to this question with the added requirement of specific escape characters.Regular expression to match escaped characters (quotes) ``` '(\\\[tvrnafb\\\]|.)' ```...
I feel dumb, I just had to remove the period in the other answer and add another character class. ``` '(\\[tvrnafb\\]|[^\\'])' ```
I bumped into this error when I was trying to access a field in my defined struct: ``` struct linkNode{ struct linkNode *next; char *value; }; ``` In the header file I defined a type called linkNode_t: ``` typedef struct linkNode linkNode_t; ``` When I tried to use this struct in the main of another file, ...
Struct has to be declared in header, before you do typedef. You can combine both: ``` typedef struct linkNode { struct linkNode *next; char *value; } linkNode_t; ```
This question already has answers here:What is the difference between char s[] and char *s?(14 answers)Closed10 years ago. I need to swap two characters by pointers but when I run this code,the program crashes. ``` int main(){ char *s1 = "string1"; swap(st,(st+1)); /* BUT THIS CODE WORKS - Whats the pro...
``` char *s1 = "string1"; ``` Becauses1points to a string literal and modifying invokesundefined behaviourin C. That's why this doesn't work. Whereas in thischar s1[] = "string1"; s1is an array and hence it can be modified.
I know I can usesubstr()to have the firstnnumber of characters from a string. However, i want to remove the last few character. Is it valid to use-2or-3as the end position in C like the way I can do it in Python?
You can simply place a null termination character right where you want the string to end like so: ``` int main() { char s[] = "I am a string"; int len = strlen(s); s[len-3] = '\0'; printf("%s\n",s); } ``` This would give you: "I am a str"
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. Why for loop does not run by other ...
You can use a for loop with integer variables, floating-point variables, even no variables at all. ``` int i; for(i = 0; i < 10; i++) continue; float f; for(f = 0.0; f < 5; f += 0.5) continue; for(;;) break; ``` But seeWhat Every Computer Scientist Should Know About Float-Point Arithmeticfor why you should think t...
I recently wanted to see how isopen()system call implemented in Linux kernel. Looking at the syscall table suggested that the name of the function I'm looking for issys_open(), so I grepped for it. I couldn't find any declaration though, the closest I could get wasdo_sys_openinfs/open.c. Is it somehow translated into ...
No,do_sys_openis not the implementation ofsys_open, it's just a common code ofopenandopenatfactored out. Syscall function names, which are alwayssys_something, are generated by funny preprocessor macros (SYSCALL_DEFINEnwherenis the number of arguments). As you can see (very close todo_sys_open): ``` SYSCALL_DEFINE3...
I have this defined in my header file: ``` typedef struct Code { char *data; unsigned short size; } Code; ``` And these two in my .c file: ``` typedef struct MemBlock { char data[BLOCK_SIZE]; int bytesUsed; struct MemBlock *next; } MemBlock; typedef struct CodeSet { Code *codes; MemBlock *memB...
You should use->to access members in pointers tostruct. Since an array dereferenced isn't a pointer, it should be accessed with.instead of->. Hence the correct syntax would be :mySet->codes[mySet->index].size = 1;sincecodes[]is an array and not a pointer.
I'm trying to read from a file in C and after I'm done reading want to write to the same file. I'm trying to use fread() for this. Does anyone know if fread advances the pointer after it encounters "\0"? I mean after I finish reading do I need to advance the pointer or do I need to straight-away start writing into the...
freadwill advance the file position (not pointer) until it hitsEOF. However, it will not stop reading simply because it encounters'\0'. In fact, evenfgetswill only stop reading when it encounters\n. No standard library function I know of stops reading a file at'\0'.
I am writing a devices handler for my embedded systems class and I am trying to use a macro to check if the ith bit is set. My macro doesn't seem to work correctly but the inline function does. Why is that? ``` #define TEST0 i&0x01 #define CLEAR0 i &= 0x01 inline short test0(short i) { return i&0x01; } int ma...
Syntax error. The macro needs an argument. ``` #define TEST0(i) ((i) & 0x01) ``` Also, use whitespace for readability and parentheses for security.
I'm writing an application in C and i'm using GTK+ for the GUI part. I was reading about the layout part and how I need to organize my into into grids using vertical boxes and horizontal boxes. However I read on some forum that the use of gtk_vbox_new() function is deprecated. What are the best ways to create a grid s...
gtk_vbox_newis deprecated in favor of usinggtk_box_newand passing inGTK_ORIENTATION_VERTICAL. If you need a tabular layout,GtkGridis the way to go (don't use the deprecatedGtkTable). A good way to design your layout is to useGlade. Even if you end up hard-coding the widgets instead of usingGtkBuilder, Glade will allo...
``` int strlength(const char *myStr){ //variable used for str length counter int strlength = 0; //loop through string until end is reached. Each iteration adds one to the string length while (myStr[strlength] != '\0'){ putchar(myStr[strlength]); strlength++; } r...
From a comment on another answer: I am using fgets to read in a string. and i have checked to make sure that the string that was typed was stored correclty In that case, there is a trailing newline stored, so your function computes ``` strlength("hello\n") ``` The code is correct, you just didn't pass it the input...
Input files to test project 2. Intended to be used via redirection. My professor gave us a txt file to use to test if our program works. It reads in ~1000 numbers (so we wouldn't have to manually enter them). But I don't know the linux command on how to use this txt file. ``` ccarri7@ubuntu:~/C$ ls ccarri7lab2 ccar...
``` ./ccarri7lab2 < lab2input.txt ``` will use the text in lab2input.txt as arguments for ccarri7lab2 http://linux.about.com/od/itl_guide/a/gdeitl42t01.htm
I want the current thread to sleep for a given time. However, another thread should be able to interrupt it and wake it up early. In unix this is fairly simple usingsleep+pthread_kill. In windows there isSleepExandSleepConditionVariableCS. SleepEx doesnt seem to actually cause the thread to sleep since it is still pro...
Create a manual reseteventand wait on it withWaitForSingleObject- has a timeout parameter. See MSDN for details.
I'm trying to build a. dll file to extend the postgres server with C functions. I'm using visual studio 2012 to build the dll, and PostgreSQL 9.2. I imported all directories postgres "\include\server*" But I'm having the errors: error C2011: 'timezone': 'struct' type redefinitionerror C2011: 'itimerval': 'struct' typ...
I took a look at this today and found that it's a bug in the PostgreSQL include files. Seethis mailing list post. You can work around it by explicitly defining WIN32 in your project file's preprocessor directives. Seemy blog post on the topic today
I have ``` unsigned char src_mac[6]; ``` that holds values with the %02x format.For example to find the value in src_mac[0] i do: ``` printf("%02x\n",src_mac[0]); ``` I want to know how to put values in src_mac(I need to put a mac adress saved as a string into src_mac and then put the mac adress into a ether_arp s...
Editing my answer... i misread it Anyway, try thissscanfwithhhxas parameters... it means it will read an hex value and will store it as a char (unlikely the default that store the value as int) ``` sscanf(string_mac, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &src_mac[5], &src_mac[4], &src_mac[3], ...
Suppose i have two functions in x86 assembly language defined as : ``` .globl func_name1; .type func_name1, @function; .align 2; func_name1: //Some assembly instructions here. ``` and similarly second function: ``` .globl func_name2; .type func_name2, @function; .align 2; func_name2: //Some assembly...
Those .long's define pointers to functions.var_templooks like an array of 2 pointers to functions.
When a line of code shown below is compiled(X86), corresponding assembly instruction is generated. 895 is an -ve number and is stored in 2's complement form at the memory location pointed by %esp. ``` int a = -895 --> compiler ---> movl $-895, 24(%esp) ``` My doubt is, does assembler directly converts -895 to 2'...
Of course it happens at compile (assembly) time, otherwisemovlwould have to generate not justmovl.
I want to have a typedef that is 1-bit integer, so I though of thistypedef int:1 FLAG;but I'm getting errors with it, is there a way I can do so? Thanks
No. The smallest addressable "thing" in a C Program is abyteorchar.Acharis at least 8 bits long.So you cannot have a type (or objects of any type) with less than 8 bits. What you can do is have a type for which objects occupy at least as many bits as acharand ignore most of the bits ``` #include <limits.h> #include...
I have a C application called Test. Test takes in a single int parameter. I want to run Test with many different parameters, so I made the following bash script: ``` #!/bin/bash for i in {0..5} do ./Test "$i" done ``` However, this executes./Test "$i"and not./Test 0, ./Test 1etc. Changing it to./Test $isimply e...
Try ``` #!/bin/bash for i in `seq 0 5` do ./Test $i done ``` To create sequences in bash you can useseq, which has an advantage of working in any bourne-compatible shell (that is,seqworkseverywherebecause it's an external program, it's theforloop that becomes more portable). Yes, it makes no difference with re...
I recently wanted to see how isopen()system call implemented in Linux kernel. Looking at the syscall table suggested that the name of the function I'm looking for issys_open(), so I grepped for it. I couldn't find any declaration though, the closest I could get wasdo_sys_openinfs/open.c. Is it somehow translated into ...
No,do_sys_openis not the implementation ofsys_open, it's just a common code ofopenandopenatfactored out. Syscall function names, which are alwayssys_something, are generated by funny preprocessor macros (SYSCALL_DEFINEnwherenis the number of arguments). As you can see (very close todo_sys_open): ``` SYSCALL_DEFINE3...
I have this defined in my header file: ``` typedef struct Code { char *data; unsigned short size; } Code; ``` And these two in my .c file: ``` typedef struct MemBlock { char data[BLOCK_SIZE]; int bytesUsed; struct MemBlock *next; } MemBlock; typedef struct CodeSet { Code *codes; MemBlock *memB...
You should use->to access members in pointers tostruct. Since an array dereferenced isn't a pointer, it should be accessed with.instead of->. Hence the correct syntax would be :mySet->codes[mySet->index].size = 1;sincecodes[]is an array and not a pointer.
I'm trying to read from a file in C and after I'm done reading want to write to the same file. I'm trying to use fread() for this. Does anyone know if fread advances the pointer after it encounters "\0"? I mean after I finish reading do I need to advance the pointer or do I need to straight-away start writing into the...
freadwill advance the file position (not pointer) until it hitsEOF. However, it will not stop reading simply because it encounters'\0'. In fact, evenfgetswill only stop reading when it encounters\n. No standard library function I know of stops reading a file at'\0'.
I am writing a devices handler for my embedded systems class and I am trying to use a macro to check if the ith bit is set. My macro doesn't seem to work correctly but the inline function does. Why is that? ``` #define TEST0 i&0x01 #define CLEAR0 i &= 0x01 inline short test0(short i) { return i&0x01; } int ma...
Syntax error. The macro needs an argument. ``` #define TEST0(i) ((i) & 0x01) ``` Also, use whitespace for readability and parentheses for security.
I'm writing an application in C and i'm using GTK+ for the GUI part. I was reading about the layout part and how I need to organize my into into grids using vertical boxes and horizontal boxes. However I read on some forum that the use of gtk_vbox_new() function is deprecated. What are the best ways to create a grid s...
gtk_vbox_newis deprecated in favor of usinggtk_box_newand passing inGTK_ORIENTATION_VERTICAL. If you need a tabular layout,GtkGridis the way to go (don't use the deprecatedGtkTable). A good way to design your layout is to useGlade. Even if you end up hard-coding the widgets instead of usingGtkBuilder, Glade will allo...
``` int strlength(const char *myStr){ //variable used for str length counter int strlength = 0; //loop through string until end is reached. Each iteration adds one to the string length while (myStr[strlength] != '\0'){ putchar(myStr[strlength]); strlength++; } r...
From a comment on another answer: I am using fgets to read in a string. and i have checked to make sure that the string that was typed was stored correclty In that case, there is a trailing newline stored, so your function computes ``` strlength("hello\n") ``` The code is correct, you just didn't pass it the input...
Input files to test project 2. Intended to be used via redirection. My professor gave us a txt file to use to test if our program works. It reads in ~1000 numbers (so we wouldn't have to manually enter them). But I don't know the linux command on how to use this txt file. ``` ccarri7@ubuntu:~/C$ ls ccarri7lab2 ccar...
``` ./ccarri7lab2 < lab2input.txt ``` will use the text in lab2input.txt as arguments for ccarri7lab2 http://linux.about.com/od/itl_guide/a/gdeitl42t01.htm
I want the current thread to sleep for a given time. However, another thread should be able to interrupt it and wake it up early. In unix this is fairly simple usingsleep+pthread_kill. In windows there isSleepExandSleepConditionVariableCS. SleepEx doesnt seem to actually cause the thread to sleep since it is still pro...
Create a manual reseteventand wait on it withWaitForSingleObject- has a timeout parameter. See MSDN for details.
In C we have a statement like: ``` printf("%6.3f ",floatNumber); ``` which limits the number of digits when printing.How can I achieve the similar behavior inC++? i know ofsetprecisionbut that doesn't help me do the same exact thing.
To get a similar format to that specified by%6.3fusing just the standard iostream manipulators you can do: ``` std::cout << std::fixed << std::setw(6) << std::setprecision(3) << f; ``` Specificallystd::fixedindicates the same basic format asfin the format string so that, for example, 'precision' means the same thing...
In C does the function inet_pton() convert only the ip address from printble to string format or it also converts ip address and port number too? I mean, if I have a string of format A.B.C.D:E where A.B.C.D is the ip and E is the port number, would I be able to use inet_pton for the same?
No, it does not handle port numbers. Theman pagespecifies exactly what it expects for IPv4 addresses: srcpoints to a character string containing an IPv4 network address in dotted-decimal format, "ddd.ddd.ddd.ddd", where ddd is a decimal number of up to three digits in the range 0 to 255. The address is conve...
I'm trying to unpack bytes in python :- ``` import struct c_struct_exp='struct lokesh { int i=5;} lm;' result=struct.unpack('!i',bytes(c_struct_exp,'utf-8')) print(result) ``` error: ``` struct.error: unpack requires a bytes object of length 4 ``` please, help me with format string expression in unpack method...
unpackis for unpackingbinary data, not C source code. To follow your example of single integer member structure: ``` >>> from struct import * >>> pack('i', 134) '\x86\x00\x00\x00' >>> unpack('i', '\x86\x00\x00\x00') (134,) >>> ```
Good day, I set up Eclipse with MinGW and my project compiles fine: However when I try to run it via creating aRun ConfigurationI have the problem that there is noC/C++ Local Applicationlike here: Mine looks like this: What is missed? What do I need to do?
Select Help → Install New SoftwareType this url:http://download.eclipse.org/tools/cdt/releases/indigoTick the CDT Main Features witch includes c++ sdkRestart eclipse done!
What is the reason forstrlcpy.cto copy the arguments into local variables: ``` size_t strlcpy(char *dst, const char *src, size_t siz) { char *d = dst; const char *s = src; size_t n = siz; /* Copy as many bytes as will fit */ if (n != 0) { while (--n != 0) { if ((*d++ = *s++) =...
One very common reason is that the variables are modified in the function, and then used in an expression together with the arguments. For example, the function might modify the variablen, and later do e.g.return siz - n;.
Given: a lot of points each with a unique coordinate (xi,yi) Output: Max number of points on the same line This is my method: ``` for i=1..n for j=i..n get the line determined by point[i] and point[j] for k=1..n check if point[k] is on this line ``` But it seems this method takes to...
iterate each point, calculate the polar angle for each other point, sort the polar angle this cost O(n^2*lgn)
In C we have a statement like: ``` printf("%6.3f ",floatNumber); ``` which limits the number of digits when printing.How can I achieve the similar behavior inC++? i know ofsetprecisionbut that doesn't help me do the same exact thing.
To get a similar format to that specified by%6.3fusing just the standard iostream manipulators you can do: ``` std::cout << std::fixed << std::setw(6) << std::setprecision(3) << f; ``` Specificallystd::fixedindicates the same basic format asfin the format string so that, for example, 'precision' means the same thing...
In C does the function inet_pton() convert only the ip address from printble to string format or it also converts ip address and port number too? I mean, if I have a string of format A.B.C.D:E where A.B.C.D is the ip and E is the port number, would I be able to use inet_pton for the same?
No, it does not handle port numbers. Theman pagespecifies exactly what it expects for IPv4 addresses: srcpoints to a character string containing an IPv4 network address in dotted-decimal format, "ddd.ddd.ddd.ddd", where ddd is a decimal number of up to three digits in the range 0 to 255. The address is conve...
I'm trying to unpack bytes in python :- ``` import struct c_struct_exp='struct lokesh { int i=5;} lm;' result=struct.unpack('!i',bytes(c_struct_exp,'utf-8')) print(result) ``` error: ``` struct.error: unpack requires a bytes object of length 4 ``` please, help me with format string expression in unpack method...
unpackis for unpackingbinary data, not C source code. To follow your example of single integer member structure: ``` >>> from struct import * >>> pack('i', 134) '\x86\x00\x00\x00' >>> unpack('i', '\x86\x00\x00\x00') (134,) >>> ```
Good day, I set up Eclipse with MinGW and my project compiles fine: However when I try to run it via creating aRun ConfigurationI have the problem that there is noC/C++ Local Applicationlike here: Mine looks like this: What is missed? What do I need to do?
Select Help → Install New SoftwareType this url:http://download.eclipse.org/tools/cdt/releases/indigoTick the CDT Main Features witch includes c++ sdkRestart eclipse done!
What is the reason forstrlcpy.cto copy the arguments into local variables: ``` size_t strlcpy(char *dst, const char *src, size_t siz) { char *d = dst; const char *s = src; size_t n = siz; /* Copy as many bytes as will fit */ if (n != 0) { while (--n != 0) { if ((*d++ = *s++) =...
One very common reason is that the variables are modified in the function, and then used in an expression together with the arguments. For example, the function might modify the variablen, and later do e.g.return siz - n;.
Given: a lot of points each with a unique coordinate (xi,yi) Output: Max number of points on the same line This is my method: ``` for i=1..n for j=i..n get the line determined by point[i] and point[j] for k=1..n check if point[k] is on this line ``` But it seems this method takes to...
iterate each point, calculate the polar angle for each other point, sort the polar angle this cost O(n^2*lgn)
We have a legacy library implementation and associated exposed header files. Recently we found that, some of the functions in the exposed header file, don't have corresponding definitions in the library implementation. We want to check if there could be some more such functions. Is there any easier way of doing this ...
You can generate C source from the header (Perl is a way to go!) that calls all the functions and try to compile it. Linker will complain about missing functions.
I would like to be able to tell which pages in the page table belonging to a process are used as data segment. I am using Linux kernel v 3.2 for amd64 here is what I did before and did not work: accessing the data segment usingtask->mm->start_data(task is the task_struct for the target process).searching throughtask...
after some research looks like passing task->mm->start_data to get_user_pages combined with kmap would do the trick.
I am just going through a problem that I haven't before in C/C++, and I have no idea how to solve it. Reflection. I need to call a function or method by astringthat was given by the user. Not just this, I also need to give the function or method some parameters and get its result if any. Imagine the user has typedpri...
Use a structure mapping from strings to pointers to functions or methods (member functions). C++ doesn't provide such a structure; you will have to build it yourself, passing in the name-strings and the pointers. Conversion of parameters and return values to and from strings also needs to be implemented. The language...
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 One function is called from two diffirent files to load some data, in some cases it is loaded from one file...
If you're talking about multiple threads, then you need some kind of mutex around a static variable signifying whether the function has already run or not. If you only have one thread, then you don't need the mutex.
Basically, I have this function. After fgets I want the parent to make the child stop by changing its play variable to 0. How would I do that? ``` void readQuestion(char * question) { int play = 1; char inputline[256]; int s; char * holder; int p = fork(); if (p == 0) { whi...
To do that you want to take one of two approaches... Send a message using a message API likesignal(7)orsocket(7)If you really want to tweak the child's memory you don't wantfork(2)buta thread library.
I am familiar with theinstructioninton x86. Is it possible to inline assemblyint my_unique_numberand userequst_irq(my_unique_number , function);with a function to becalled when the instruction is executed?What about ARM is there any similar way to useSWI immed_8instructionorSVC?Can I do the same trick?
In the Linux kernel it's much simpler to simply implement your own system call in the kernel and use thesyscall(your_number)function to call it rather than doing the assembly code yourself. Doing so is very easyhttp://www.linuxjournal.com/article/3326here's a link to an article that describes how to do so in much les...
I know its probably obvious issue but since in very new to C I had to ask, This is my code: ``` #include <stdio.h> #define ASIZE 8 int main() { int index; long int numbers[ASIZE]; printf("enter 8 integers to be printed in reverse order:\n"); for (index = 0; index < ASIZE; index++) { ...
scanfrequires your inputs to be whitespace-separated. Entering12345678will only go once round the loop.
I am trying hard to find how to print the position of a character inside an char[20]. Can anyone help me? ``` int emfanisi(char a[]) { int i, mikos; char b; printf("Dose xaraktira\n"); scanf("%s", b); mikos = strlen(a); for(i=0; i<mikos; i++) { if(a[i] == b) return i; ...
The problem is that if char doesn't match in first iteration, the loop will break. Changes are made below. On a side note there is already a function to locate a char in a string:strchr(str,char). Code: ``` int emfanisi(char a[]) { int i, mikos; char b; printf("Dose xaraktira\n"); scanf("%c", &b); ...
Isn't the size of a function's address known at compilation type ?
Arithmetic operations on a pointer treats the pointer as an array of objects of a given type. So when you add 3 to anint *, you advance by threeints. Function pointers cannot be interpreted as arrays of anything. Instructions, maybe, or maybe not. Some machines have separate a address space for instructions. Some mac...
this is my code. I wrote this part outside my main ``` typedef struct { int x; } foo; const int bar = 2; foo myFoo = { (int) bar }; ``` However this returns: ``` common.c:6: error: initializer element is not constant common.c:7: error: (near initialization for ‘myFoo.x’) ``` If I copy and paste the code into the m...
you can do usingenumlike: ``` typedef struct { int x; } foo; enum {bar = 2}; foo myFoo = { bar }; ``` or using#define bar 2like ``` #define bar 2 typedef struct { int x; } foo; foo myFoo = { bar }; ``` But both are known at compilation time:why not? ``` typedef struct { int x; } foo; foo myFoo = { 2 }; const ...