question
stringlengths
25
894
answer
stringlengths
4
863
``` int overlap(const char *s1, const char *s2){ int i = 0; while (s1[i] && s2[i] && s1[i] == s2[i]) i++; return i; } ``` This returns the length of the substring overlap between the two strings it takes as input. However, if the two strings are: ``` abcdefg 1234efg ``` it returns an overlap of 0 because it can only read overlaps that start at the beginning of the strings, can someone modify or help me to make it so that it can read overlaps no mantter where they are in the strings?
The easy way to do this is to build a suffix-tree for the two strings(this is done usingMcCreght). now just look for the longests common substring with origin in both strings.
Is there any library out there for C, C++, or .NET that implements a "sparse map"? (I don't know a better name for it.) I'm looking for something like run-length encoding, like for allocating files on a disk. The data structure should be able to hold information saying "Clusters 0 to 1000 have been allocated by file 1, clusters 1000 to 9025234 have been allocated by file 2", etc. It needs to be indexable by the cluster number. (It should obviously support around log(n) or better insertion + removal time, otherwise it'd be too slow.)
"sparse map"? You likely meaninterval tree. CGALcontains a robust implementation in C++.
I often see source code using types like uint32, uint64 and I wonder if they should be defined by the programmer in the application code or if they are defined in a standard lib header. What's the best way to have these types on my application source code?
The C99stdint.hdefines these: int8_tint16_tint32_tuint8_tuint16_tuint32_t And, if the architecture supports them: int64_tuint64_t There are various other integer typedefs instdint.has well. If you're stuck without a C99 environment then you should probably supply your own typedefs and use the C99 ones anyway. Theuint32anduint64(i.e. without the_tsuffix) are probably application specific.
I am using Debian 6.0 and net-snmp 5.4.3. I have a question relating to capturing IP address and MAC address for ethernet interfaces exist on the system. In my SNMP agent, I have to figure out how many system ethernet interfaces are exist and update their IP and MAC address in a table. I have looked at pre installed mibs and found that IP-MIB contains a table for system ethernet IP addresses but I couldn't find the source to check how it is implemented. Could you please suggest me how can I implement this functionality or where I can find some further infromation? Thanks, Ravi
Someone may suggest a better way, but if not here's a solution of last resort. You can call out to ifconfig to get the data as text and then parse the results.
Is there a way to communicate with Mac OS X clipboard in language C (without Obj-C/Cocoa) ? Thanks.
The easiest way might be to call the command line programspbcopyandpbpaste.
I have to draw several thousands of pixels per frame for a falling sand animation, up to now I drawed them with Sprite.Draw (and a 1x1 Texture), but this only worked for resolutions 256x256 or lower. So is there an faster alternative to draw individual pixels? (Shaders will not work for my problem, since the logic is applied according to the pixels state)
You could try drawing points. I foundthisbut it is only for DirectX 9.
This question already has an answer here:Closed12 years ago. Possible Duplicate:executing assembly within a function in c++ ``` long getesp() { __asm__("movl %esp,%eax"); } void main() { printf("%08X\n",getesp()+4); } ``` why is the esp printed is before the stack is set up?(before the pushl %ebp, movl %esp,%ebp) thanks in advance
My guess: there is no need for a frame, so none is allocated in getesp. The particulars depend on the compiler and compiler flags you are using.
I am using the UNIXalarmsystem call to deliver a signal to the currently running process on a schedule. The man page describes the argument to this function as being in units of seconds. I would like to have precision in milliseconds. Is there an alternative system call on UNIX (or Linux specifically) that will allow this?
Take a look atsetitimer() or the more modern (and more flexible)timer_setitime() APIs.
I try to convert C lib to C# and got stuck in this code: ``` typedef struct _Symbol { unsigned char value; unsigned char count; unsigned char under; unsigned char left, right; } Symbol; // [...] ``` void function(Symbol * symbol) { ... ``` if (! symbol -> right) break; // So, right is equivalent to bool in C#? symbol += symbol -> right; // I have no idea what this code will do. ``` ... } Please help me out.
In C# there is no->operator. To reference a struct member you use.operator. Also, you can't use any expression withifsentences. Youmustuse a proper boolean expression: ``` if (symbol.right == 0) break; ``` Also, I wouldn't try to convertline-by-linea C program into a C# program. They are based on different paradigms, so you would probably need to learn a little bit of object orientation and how C# manages memory before attempting to translate code.
I have herechar text[60]; Then I do in anif: ``` if(number == 2) text = "awesome"; else text = "you fail"; ``` and it always saidexpression must be a modifiable L-value.
lvaluemeans "left value" -- it should be assignable. You cannot change the value oftextsince it is an array, not a pointer. Either declare it as char pointer (in this case it's better to declare it asconst char*): ``` const char *text; if(number == 2) text = "awesome"; else text = "you fail"; ``` Or use strcpy: ``` char text[60]; if(number == 2) strcpy(text, "awesome"); else strcpy(text, "you fail"); ```
I want to read string from standart input and output it in on console. I use this way: ``` char* cmdline; do{ scanf("%s\n", &cmdline); printf("%s\n", cmdline); }while(cmdline != "quit"); ``` But this doesn't work. I have this errorSegmentation fault (core dumped)
``` char* cmdline ``` is a pointer. You are not allocating space for storing the string. You should do: ``` cmdline = malloc(size_of_string); ``` for allocating dynamic memory for storing the string. Otherwise use an array of char instead of a pointer: ``` char cmdline[size_of_string]; ```
We're using a multi platform application which should run on both Windows and Mac. Our application is based on OpenSSL as the SSL and related stuff supplier. It uses Client Certificate to establish secure connections and to identify the end user. We want to use Windows and Mac native certificate storages to ensure maximum security. Openssl has an engine to interact with Windows' Certificate Store (CAPI engine). However, we didn't manage to find such a solution for Mac's Keychain. Is there an integration between OpenSSL and Apple's Keychain? If not, what are your suggestion ?
I think the "simplest" solution would be to write an OpenSSL engine for CSSM (API for CDSA, thesecurity architecture used by Mac OS X). You should ask on the openssl-dev mailing list if anyone is interested in helping (and might have already started).
How can you use C to spawn an independent child process that goes about its business without thinking about the father? I want to spawn several processes and shortly after they have been created they go to sleep for about 2 minutes before they do their job. However, I don't want the father to wait until the child is finished because in the meantime I want to spawn off more processes. I'm on Linux.
Use fork().The fork() System Call ``` pid_t pid = fork (); if (pid < 0) // Error else if (pid == 0) // Child Process // Sleep 2 min. ?! else // Code for Father ```
I don't remember the standard saying something of the max length for identifiers so in theory they can belong. In real life, those names could be limited by at least the compiler and linker implementations. While this should work on all systems ``` int a; ``` this snippet ``` #!/usr/bin/perl print "int" . "b" x 2**16 . ";"; ``` creates a declarationen that gives undefined reference tostd::somethings withldwhile compiling/linking (using gcc/mingw). So what are the size limits for an identifier on different systems?
Microsoft C++: 2048 charactersIntel C++: 2048 charactersg++: No limit, as answered in this question:is there a length limit on g++ variable names?
The C standard guarantees that anintis able to store every possible array size. At least, that's what I understand from reading §6.5.2.1, subsection 1 (Array subscripting constraints): One of the expressions shall have type ‘‘pointer to object type’’, the other expression shall have integer type, and the result has type ‘‘type’’. Since we shall useints as array subscripts, why are we supposed to usesize_tto determine the size of an array? Why doesstrlen()returnsize_twhenintwould suffice?
The term "integer type" doesn't meanint- for example,char, andshortare integer types. Just because you can use anintto subscript an array doesn't necessarily mean that it can reach all possible array elements. More specifically aboutsize_tvs.int, one example would be platforms whereintmight be a 16-bit type andsize_tmight be a 32-bit type (or the more common 32-bitintvs 64 bitsize_tdifference on today's 64-bit platforms).
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been done so far to solve it.Closed9 years ago.Improve this question Does anyone know if there is a Java/C/C++/C#/PHP to Pascal converter?
H2Pasis a popular tool to convert C headers to Pascal. I don't know of any to actually convert C code to Pascal code though. From a quick google search, I see several that may or may not be good: http://cc.embarcadero.com/item/23991http://c2pas.sourceforge.net/ I am tempted to say you'll have to do a lot of it by hand one way or another.
``` char* foo = (char*) malloc(sizeof(char)*50); foo = "testing"; ``` In C, i can see the first character of that string : ``` printf("%c",foo[0]); ``` But when i try to change that value : ``` foo[0]='f' ``` It gives error in runtime. How can i change this, dynamically allocated, char array's values?
You are setting foo to point to the string literal ("testing") not the memory you allocated. Thus you are trying to change the read only memory of the constant, not the allocated memory. This is the correct code: ``` char* foo = malloc(sizeof(char)*50); strcpy(foo,"testing"); ``` or even better ``` cont int MAXSTRSIZE = 50; char* foo = malloc(sizeof(char)*MAXSTRSIZE); strncpy(foo,"testing",MAXSTRSIZE); ``` to protect against buffer over-run vulnerability.
I want to find the length of this : ``` char *s[]={"s","a","b"}; ``` it should count 4 with the /0 but the strlen or sizeof(s)/sizeof(char) gives me wrong answers.. How can i find it?
You are making an array ofchar*and not ofchar. That's whystrlenwon't work. Use ``` sizeof(s) / sizeof(char*) //should give 3 ``` If you want a single string use ``` char s[] = "sab"; ```
How can I set a digit in a hexadecimal number? I currently have this code: ``` int row = 0x00000000; row |= 0x3 << 8; row |= 0x2 << 4; row |= 0x1 << 0; printf("Row: 0x%08x", row); ``` Which works perfectly fine as long as "row" is just zeros. As soon as I change it to something like this: ``` int row = 0x33333333; row |= 0x3 << 8; row |= 0x2 << 4; row |= 0x1 << 0; printf("Row: 0x%08x", row); ``` I just get this output: Row: 0x33333333
You should delete (make it 0) the digit first. ``` row &= ~(0xf << 4); ``` ~operator reverses the values of all bits in the number. So.0x000000f0becomes0xffffff0f. Your code should look like: ``` row &= ~(0xf << 8); row |= 0x3 << 8; row &= ~(0xf << 4); row |= 0x2 << 4; row &= ~(0xf << 0); row |= 0x1 << 0; ```
I found this in a code I am currently studying, could someone explain it to me. ``` char * string = "Simulated Annealing = 12847369"; char * value = strchr(string, '='); *(value ++ ) = 0; printf("%s ==== %s", value, string); ``` I noticed that string will print in a new line first, why this? ``` char* karmarkar = "Karmarkar 958572"; ``` I want to use strchr to find the first occurrence of "space" in string karmarkar. How do I do that?
Nope, it doesn't put a new linehttp://codepad.org/xhTiV4Qn. Actually on my machine it gives sigsegv because you are trying to write at a read only location inside "Simulated ... ".int pos = strchr(karmarkar, ' ') - karmarkar;.strchr(karmarkar, ' ')returns a pointer to the first occurrence of " " (space).
I installedCUDA from an Ubuntu PPA. Now I want to test the installation. I grabbed asmall sample program from another StackOverflow post. It imports cuda.h and cuda_runtime.h. Does this mean I need to use nvcc to compile the program or should I use gcc? When I try to compile I get the errors below. How do I tell the compiler where to find the necessary libraries? Also, how do I find those libraries myself? I'm not sure where the PPA installation put them or the names of the libraries I should be looking for. ``` detect_cuda.c:(.text+0x2b): undefined reference to `cudaGetDeviceCount' detect_cuda.c:(.text+0x30): undefined reference to `cudaGetLastError' detect_cuda.c:(.text+0x47): undefined reference to `cudaGetErrorString' detect_cuda.c:(.text+0xba): undefined reference to `cudaGetDeviceProperties' ```
Adding -lcudart worked as Anycom suggested in the comments. ``` nvcc -lcudart detect_cuda.cu ```
Hi I want to open a binary file for both reading and writing(without truncating, not appending). I use mode "r+b". I get no compiling errors but when read what I have written I get garbage values. Any idea. But if I open the file for writing(mode as "wb")..write into in..close it and then open the file for reading(mode as "rb") aand read from it ,then it works fine.
When you open a file in read/write modes such as "r+", "w+", you need to make sure your file pointer points to a valid position. fseek() is your friend here. Also, as a good practice, remember to always check returned values from functions. In this case, maybe your fread() have failed without you noticing it.
I'm having issues writing a C function that reads a string from STDIN, and returns the length of said string... Suggestions?
So, simply use strlen from the C standard library: ``` #include <string.h> ``` So the strlen() function is available. You just need to pass a char pointer, and it will return the string length: ``` size_t length = strlen( myStr ); ``` Note that size_t is an integral type. By the way, if you don't know about this function, you should really dig into the C library, and lear about the basic functions it provides.
I'm reading an interesting articleA Guide to Undefined Behavior in C and C++, Part 1on undefined behavior in C and C++. Often I do the following in my code: ``` int i = 10; i = (++i) % 7; ``` Does this produce undefined behavior? On x86? ARM? Perhaps it depends on the compiler?
It's undefined behavior becauseiis modified more than once without an intervening sequence point. It depends on the compiler only in the sense that there are no requirements about what the code will do, so every compiler can do something different. To be clear -just becauseeven though you get results that seem to make sense (sometimes), the code is a bug.
Good day, I was wondering if there is a way to do direct system call capture with C or C++? I know that currently on unix systems you can use SystemTap to do system capture. The problem I'm having is that in order to feed them into another program for analysis I have to pipe them to the other program. I'd like to pass things along programatically as this is easier than "printing" out into the pipe and then reading in with the other program. Is there a way of doing this? How difficult would it be?
stracedoes exactly that. You can take a look at itssource codeto see how its done.
What feature(s) ofstrtokis unsafe (in terms of buffer overflow) that I need to watch out for? What's a little weird to me is thatstrtok_s(which is "safe") in Visual C++ has an extra "context" parameter, but it looks like it's the same in other ways... is it the same, or is it actually different?
According with the strtok_s section ofthis document: 6.7.3.1 The strtok_s function The strtok_s function fixes two problems in the strtok function:A new parameter, s1max, prevents strtok_s from storing outside of the string being tokenized. (The string being divided into tokens is both an input and output of the function since strtok_s stores null characters into the string.)A new parameter, ptr, eliminates the static internal state that prevents strtok from being re-entrant (Subclause 1.1.12). (The ISO/IEC 9899 function wcstok and the ISO/IEC 9945 (POSIX) function strtok_r fix this problem identically.)
It was mentioned that a well written compiler for C should carry out the shift opeators at compile time (i.e. not run-time); for example in this code the shift left - <<. Can anyone attest to the validity of this? Code: ``` constant unsigned int elements = length/8 + (length % y > 0 ? 1 : 0); unsigned char bit_arr[elements]; ``` Psuedo-Code : ``` bit_arr[i] |= (1 << j); // Set bit_arr[i] &= ~(1 << j); // Unset if( bit_arr[i] & (1 << j) ) // Test ```
What are you actually asking? Do you mean "will the compiler do the shift itself"? If that's what you're asking the answer is "it depends" :). If the number being shifted and the size of the shift are both compile-time constants the compiler almost surely will do the shift (though it doesn't have to). Otherwise it will generate the lower-level code that will carry out the shift (which will often be a single machine instruction).
If I have a struct like ``` struct account { int account_number; }; ``` Then what's the difference between doing ``` myAccount.account_number; ``` and ``` myAccount->account_number; ``` or isn't there a difference? If there's no difference, why wouldn't you just use the.notation rather than->?->seems so messy.
-> is a shorthand for(*x).field, wherexis a pointer to a variable of typestruct account, andfieldis a field in the struct, such asaccount_number. If you have a pointer to a struct, then saying ``` accountp->account_number; ``` is much more concise than ``` (*accountp).account_number; ```
The C standard guarantees that anintis able to store every possible array size. At least, that's what I understand from reading §6.5.2.1, subsection 1 (Array subscripting constraints): One of the expressions shall have type ‘‘pointer to object type’’, the other expression shall have integer type, and the result has type ‘‘type’’. Since we shall useints as array subscripts, why are we supposed to usesize_tto determine the size of an array? Why doesstrlen()returnsize_twhenintwould suffice?
The term "integer type" doesn't meanint- for example,char, andshortare integer types. Just because you can use anintto subscript an array doesn't necessarily mean that it can reach all possible array elements. More specifically aboutsize_tvs.int, one example would be platforms whereintmight be a 16-bit type andsize_tmight be a 32-bit type (or the more common 32-bitintvs 64 bitsize_tdifference on today's 64-bit platforms).
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been done so far to solve it.Closed9 years ago.Improve this question Does anyone know if there is a Java/C/C++/C#/PHP to Pascal converter?
H2Pasis a popular tool to convert C headers to Pascal. I don't know of any to actually convert C code to Pascal code though. From a quick google search, I see several that may or may not be good: http://cc.embarcadero.com/item/23991http://c2pas.sourceforge.net/ I am tempted to say you'll have to do a lot of it by hand one way or another.
``` char* foo = (char*) malloc(sizeof(char)*50); foo = "testing"; ``` In C, i can see the first character of that string : ``` printf("%c",foo[0]); ``` But when i try to change that value : ``` foo[0]='f' ``` It gives error in runtime. How can i change this, dynamically allocated, char array's values?
You are setting foo to point to the string literal ("testing") not the memory you allocated. Thus you are trying to change the read only memory of the constant, not the allocated memory. This is the correct code: ``` char* foo = malloc(sizeof(char)*50); strcpy(foo,"testing"); ``` or even better ``` cont int MAXSTRSIZE = 50; char* foo = malloc(sizeof(char)*MAXSTRSIZE); strncpy(foo,"testing",MAXSTRSIZE); ``` to protect against buffer over-run vulnerability.
I want to find the length of this : ``` char *s[]={"s","a","b"}; ``` it should count 4 with the /0 but the strlen or sizeof(s)/sizeof(char) gives me wrong answers.. How can i find it?
You are making an array ofchar*and not ofchar. That's whystrlenwon't work. Use ``` sizeof(s) / sizeof(char*) //should give 3 ``` If you want a single string use ``` char s[] = "sab"; ```
How can I set a digit in a hexadecimal number? I currently have this code: ``` int row = 0x00000000; row |= 0x3 << 8; row |= 0x2 << 4; row |= 0x1 << 0; printf("Row: 0x%08x", row); ``` Which works perfectly fine as long as "row" is just zeros. As soon as I change it to something like this: ``` int row = 0x33333333; row |= 0x3 << 8; row |= 0x2 << 4; row |= 0x1 << 0; printf("Row: 0x%08x", row); ``` I just get this output: Row: 0x33333333
You should delete (make it 0) the digit first. ``` row &= ~(0xf << 4); ``` ~operator reverses the values of all bits in the number. So.0x000000f0becomes0xffffff0f. Your code should look like: ``` row &= ~(0xf << 8); row |= 0x3 << 8; row &= ~(0xf << 4); row |= 0x2 << 4; row &= ~(0xf << 0); row |= 0x1 << 0; ```
I found this in a code I am currently studying, could someone explain it to me. ``` char * string = "Simulated Annealing = 12847369"; char * value = strchr(string, '='); *(value ++ ) = 0; printf("%s ==== %s", value, string); ``` I noticed that string will print in a new line first, why this? ``` char* karmarkar = "Karmarkar 958572"; ``` I want to use strchr to find the first occurrence of "space" in string karmarkar. How do I do that?
Nope, it doesn't put a new linehttp://codepad.org/xhTiV4Qn. Actually on my machine it gives sigsegv because you are trying to write at a read only location inside "Simulated ... ".int pos = strchr(karmarkar, ' ') - karmarkar;.strchr(karmarkar, ' ')returns a pointer to the first occurrence of " " (space).
I installedCUDA from an Ubuntu PPA. Now I want to test the installation. I grabbed asmall sample program from another StackOverflow post. It imports cuda.h and cuda_runtime.h. Does this mean I need to use nvcc to compile the program or should I use gcc? When I try to compile I get the errors below. How do I tell the compiler where to find the necessary libraries? Also, how do I find those libraries myself? I'm not sure where the PPA installation put them or the names of the libraries I should be looking for. ``` detect_cuda.c:(.text+0x2b): undefined reference to `cudaGetDeviceCount' detect_cuda.c:(.text+0x30): undefined reference to `cudaGetLastError' detect_cuda.c:(.text+0x47): undefined reference to `cudaGetErrorString' detect_cuda.c:(.text+0xba): undefined reference to `cudaGetDeviceProperties' ```
Adding -lcudart worked as Anycom suggested in the comments. ``` nvcc -lcudart detect_cuda.cu ```
Hi I want to open a binary file for both reading and writing(without truncating, not appending). I use mode "r+b". I get no compiling errors but when read what I have written I get garbage values. Any idea. But if I open the file for writing(mode as "wb")..write into in..close it and then open the file for reading(mode as "rb") aand read from it ,then it works fine.
When you open a file in read/write modes such as "r+", "w+", you need to make sure your file pointer points to a valid position. fseek() is your friend here. Also, as a good practice, remember to always check returned values from functions. In this case, maybe your fread() have failed without you noticing it.
I'm having issues writing a C function that reads a string from STDIN, and returns the length of said string... Suggestions?
So, simply use strlen from the C standard library: ``` #include <string.h> ``` So the strlen() function is available. You just need to pass a char pointer, and it will return the string length: ``` size_t length = strlen( myStr ); ``` Note that size_t is an integral type. By the way, if you don't know about this function, you should really dig into the C library, and lear about the basic functions it provides.
I'm reading an interesting articleA Guide to Undefined Behavior in C and C++, Part 1on undefined behavior in C and C++. Often I do the following in my code: ``` int i = 10; i = (++i) % 7; ``` Does this produce undefined behavior? On x86? ARM? Perhaps it depends on the compiler?
It's undefined behavior becauseiis modified more than once without an intervening sequence point. It depends on the compiler only in the sense that there are no requirements about what the code will do, so every compiler can do something different. To be clear -just becauseeven though you get results that seem to make sense (sometimes), the code is a bug.
Good day, I was wondering if there is a way to do direct system call capture with C or C++? I know that currently on unix systems you can use SystemTap to do system capture. The problem I'm having is that in order to feed them into another program for analysis I have to pipe them to the other program. I'd like to pass things along programatically as this is easier than "printing" out into the pipe and then reading in with the other program. Is there a way of doing this? How difficult would it be?
stracedoes exactly that. You can take a look at itssource codeto see how its done.
What feature(s) ofstrtokis unsafe (in terms of buffer overflow) that I need to watch out for? What's a little weird to me is thatstrtok_s(which is "safe") in Visual C++ has an extra "context" parameter, but it looks like it's the same in other ways... is it the same, or is it actually different?
According with the strtok_s section ofthis document: 6.7.3.1 The strtok_s function The strtok_s function fixes two problems in the strtok function:A new parameter, s1max, prevents strtok_s from storing outside of the string being tokenized. (The string being divided into tokens is both an input and output of the function since strtok_s stores null characters into the string.)A new parameter, ptr, eliminates the static internal state that prevents strtok from being re-entrant (Subclause 1.1.12). (The ISO/IEC 9899 function wcstok and the ISO/IEC 9945 (POSIX) function strtok_r fix this problem identically.)
``` char* foo = (char*) malloc(sizeof(char)*50); foo = "testing"; ``` In C, i can see the first character of that string : ``` printf("%c",foo[0]); ``` But when i try to change that value : ``` foo[0]='f' ``` It gives error in runtime. How can i change this, dynamically allocated, char array's values?
You are setting foo to point to the string literal ("testing") not the memory you allocated. Thus you are trying to change the read only memory of the constant, not the allocated memory. This is the correct code: ``` char* foo = malloc(sizeof(char)*50); strcpy(foo,"testing"); ``` or even better ``` cont int MAXSTRSIZE = 50; char* foo = malloc(sizeof(char)*MAXSTRSIZE); strncpy(foo,"testing",MAXSTRSIZE); ``` to protect against buffer over-run vulnerability.
I want to find the length of this : ``` char *s[]={"s","a","b"}; ``` it should count 4 with the /0 but the strlen or sizeof(s)/sizeof(char) gives me wrong answers.. How can i find it?
You are making an array ofchar*and not ofchar. That's whystrlenwon't work. Use ``` sizeof(s) / sizeof(char*) //should give 3 ``` If you want a single string use ``` char s[] = "sab"; ```
How can I set a digit in a hexadecimal number? I currently have this code: ``` int row = 0x00000000; row |= 0x3 << 8; row |= 0x2 << 4; row |= 0x1 << 0; printf("Row: 0x%08x", row); ``` Which works perfectly fine as long as "row" is just zeros. As soon as I change it to something like this: ``` int row = 0x33333333; row |= 0x3 << 8; row |= 0x2 << 4; row |= 0x1 << 0; printf("Row: 0x%08x", row); ``` I just get this output: Row: 0x33333333
You should delete (make it 0) the digit first. ``` row &= ~(0xf << 4); ``` ~operator reverses the values of all bits in the number. So.0x000000f0becomes0xffffff0f. Your code should look like: ``` row &= ~(0xf << 8); row |= 0x3 << 8; row &= ~(0xf << 4); row |= 0x2 << 4; row &= ~(0xf << 0); row |= 0x1 << 0; ```
I found this in a code I am currently studying, could someone explain it to me. ``` char * string = "Simulated Annealing = 12847369"; char * value = strchr(string, '='); *(value ++ ) = 0; printf("%s ==== %s", value, string); ``` I noticed that string will print in a new line first, why this? ``` char* karmarkar = "Karmarkar 958572"; ``` I want to use strchr to find the first occurrence of "space" in string karmarkar. How do I do that?
Nope, it doesn't put a new linehttp://codepad.org/xhTiV4Qn. Actually on my machine it gives sigsegv because you are trying to write at a read only location inside "Simulated ... ".int pos = strchr(karmarkar, ' ') - karmarkar;.strchr(karmarkar, ' ')returns a pointer to the first occurrence of " " (space).
I installedCUDA from an Ubuntu PPA. Now I want to test the installation. I grabbed asmall sample program from another StackOverflow post. It imports cuda.h and cuda_runtime.h. Does this mean I need to use nvcc to compile the program or should I use gcc? When I try to compile I get the errors below. How do I tell the compiler where to find the necessary libraries? Also, how do I find those libraries myself? I'm not sure where the PPA installation put them or the names of the libraries I should be looking for. ``` detect_cuda.c:(.text+0x2b): undefined reference to `cudaGetDeviceCount' detect_cuda.c:(.text+0x30): undefined reference to `cudaGetLastError' detect_cuda.c:(.text+0x47): undefined reference to `cudaGetErrorString' detect_cuda.c:(.text+0xba): undefined reference to `cudaGetDeviceProperties' ```
Adding -lcudart worked as Anycom suggested in the comments. ``` nvcc -lcudart detect_cuda.cu ```
Hi I want to open a binary file for both reading and writing(without truncating, not appending). I use mode "r+b". I get no compiling errors but when read what I have written I get garbage values. Any idea. But if I open the file for writing(mode as "wb")..write into in..close it and then open the file for reading(mode as "rb") aand read from it ,then it works fine.
When you open a file in read/write modes such as "r+", "w+", you need to make sure your file pointer points to a valid position. fseek() is your friend here. Also, as a good practice, remember to always check returned values from functions. In this case, maybe your fread() have failed without you noticing it.
I'm having issues writing a C function that reads a string from STDIN, and returns the length of said string... Suggestions?
So, simply use strlen from the C standard library: ``` #include <string.h> ``` So the strlen() function is available. You just need to pass a char pointer, and it will return the string length: ``` size_t length = strlen( myStr ); ``` Note that size_t is an integral type. By the way, if you don't know about this function, you should really dig into the C library, and lear about the basic functions it provides.
I'm reading an interesting articleA Guide to Undefined Behavior in C and C++, Part 1on undefined behavior in C and C++. Often I do the following in my code: ``` int i = 10; i = (++i) % 7; ``` Does this produce undefined behavior? On x86? ARM? Perhaps it depends on the compiler?
It's undefined behavior becauseiis modified more than once without an intervening sequence point. It depends on the compiler only in the sense that there are no requirements about what the code will do, so every compiler can do something different. To be clear -just becauseeven though you get results that seem to make sense (sometimes), the code is a bug.
Good day, I was wondering if there is a way to do direct system call capture with C or C++? I know that currently on unix systems you can use SystemTap to do system capture. The problem I'm having is that in order to feed them into another program for analysis I have to pipe them to the other program. I'd like to pass things along programatically as this is easier than "printing" out into the pipe and then reading in with the other program. Is there a way of doing this? How difficult would it be?
stracedoes exactly that. You can take a look at itssource codeto see how its done.
What feature(s) ofstrtokis unsafe (in terms of buffer overflow) that I need to watch out for? What's a little weird to me is thatstrtok_s(which is "safe") in Visual C++ has an extra "context" parameter, but it looks like it's the same in other ways... is it the same, or is it actually different?
According with the strtok_s section ofthis document: 6.7.3.1 The strtok_s function The strtok_s function fixes two problems in the strtok function:A new parameter, s1max, prevents strtok_s from storing outside of the string being tokenized. (The string being divided into tokens is both an input and output of the function since strtok_s stores null characters into the string.)A new parameter, ptr, eliminates the static internal state that prevents strtok from being re-entrant (Subclause 1.1.12). (The ISO/IEC 9899 function wcstok and the ISO/IEC 9945 (POSIX) function strtok_r fix this problem identically.)
It was mentioned that a well written compiler for C should carry out the shift opeators at compile time (i.e. not run-time); for example in this code the shift left - <<. Can anyone attest to the validity of this? Code: ``` constant unsigned int elements = length/8 + (length % y > 0 ? 1 : 0); unsigned char bit_arr[elements]; ``` Psuedo-Code : ``` bit_arr[i] |= (1 << j); // Set bit_arr[i] &= ~(1 << j); // Unset if( bit_arr[i] & (1 << j) ) // Test ```
What are you actually asking? Do you mean "will the compiler do the shift itself"? If that's what you're asking the answer is "it depends" :). If the number being shifted and the size of the shift are both compile-time constants the compiler almost surely will do the shift (though it doesn't have to). Otherwise it will generate the lower-level code that will carry out the shift (which will often be a single machine instruction).
If I have a struct like ``` struct account { int account_number; }; ``` Then what's the difference between doing ``` myAccount.account_number; ``` and ``` myAccount->account_number; ``` or isn't there a difference? If there's no difference, why wouldn't you just use the.notation rather than->?->seems so messy.
-> is a shorthand for(*x).field, wherexis a pointer to a variable of typestruct account, andfieldis a field in the struct, such asaccount_number. If you have a pointer to a struct, then saying ``` accountp->account_number; ``` is much more concise than ``` (*accountp).account_number; ```
Current direction: Start with and unsigned char which is 1 Byte on my system using sizeof. Range is 0-255. If length is the number of bits I need then elements is the number of elements (bytes) I need in my array. ``` constant unsigned int elements = length/8 + (length % y > 0 ? 1 : 0); unsigned char bit_arr[elements]; ``` Now I add basic functionality such as set, unset, and test. Where j is the bit per byte index, i is the byte index and h = bit index. We have i = h / 8 and j = i % 8. Psuedo-Code : ``` bit_arr[i] |= (1 << j); // Set bit_arr[i] &= ~(1 << j); // Unset if( bit_arr[i] & (1 << j) ) // Test ```
Looks like you have a very good idea of what needs to be done. Though instead ofpow(2, j), use1 << j. You also need to change yourtestcode. You don't want the test to do an assignment to the array.
in any dictionary data structure there is an add_to_ds function which receives the data needed to insert as a parameter. the question is this:should the add_to_ds get the object it self (type T) and do the memory allocation,or should the add_to_ds get a pointer to object and just insert the pointer (type T*,whoever uses the DS does the memory allocation). what is the right way do do it,and why ?
There isn't any generally right / wrong way to do it. If you trust the caller not to modify the memory, you're fine storing a pointer. If, however you don't specify this in your interface, you'll have to duplicate the memory. If you let them enter pointers, they will be responsible with freeing memory, not touching it etcIf youdon'ttrust them, you'll have to free memory, you'll have to return copies to stored items (otherwise if you return your pointer they might free it / alter it)
I am working on a C program that I did not write and integrating it with my C++ code. This C program has a character array and usage putc function to print the content of it. Like this: ``` printf("%c\n","01"[b[i]]); ``` This is a bit array and can have either ASCII 0 or ASCII 1 (NOT ASCII 48 and 49 PLEASE NOTE). This command prints "0" and "1" perfectly. However, I did not understand the use of "01" in the putc command. I can also print the contents like this: ``` printf("%d\n",b[i]); ``` Hence I was just curious. Thanks. Newbie
The"01"is a string literal, which for all intents and purposes is an array. It's a bit weird-looking... you could write: ``` char *characters = "01"; printf("%c\n", characters[b[i]]); ``` or maybe even better: ``` char *characters = "01"; int bit = b[i]; printf("%c\n", characters[bit]); ``` And it would be a little easier to understand at first glance.
My list item: ``` typdef struct sNode { struct sNode* next; myData data; } tNode; ``` I wish to implement the following API: ``` bool removeNode(tNode* node) { ... // need to fix list and free node } ``` The problem is that I do not have the previous element to modify. Is there some kind of magic to solve it?
No. You would have to traverse from the beginning of the list to find the previous node, which is pretty inefficient. This is the problem with singly-linked lists. If you need this to be fast, use a doubly-linked list (each node has anextand apreviouspointer).
I'm on Ubuntu 11.04. Everything works PHP, PHPMYADMIN, manual login to MySQL etc. I have written a C application that uses MySQL. Now, when I start this application I receive the above error. I tried to prevent that from happening by linking the original file into the /tmp/ folder (ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock), however, after a while I start getting this error again - because my link has been removed, which is frustating. What do I need to do to make this work?
The MySQL libraries are compiled with a default of/tmp/mysql.sock. The server is started up with/var/run/mysqld/mysql.sockand your$HOME/.my.cnfdoes not reflect this value in the[client]section. If this is run without a valid $HOME you may need to usemysql_optionswith MYSQL_READ_DEFAULT_FILE.
I am working on Program(in c) which require sorting. One of the requirement of sorting is : Digits Sorting. Digit sorting shall be completed from least significant digit (i.e. the rightmost digit) and to the most significant digit (i.e. the leftmost digit) such that the numbers 21, 2, and 11 are sorted as follows: 2, 11, 21. The given string is in UTF-8 and may contains Special Characters,Digits,Latin letters ,Cyrillic letters ,Hiragana/Katakana etc. It give following sorting Order : 1 1a 1b 2 11 110 110a Henry7 Henry24
You might want to consider using theICU library(International Components for Unicode), which includes acollation (sorting) API.
I am creating a file as follows ``` int fd = creat(file_path.c_str() ,S_IRWXU|S_IRWXG|S_IRWXO); ``` Though i am providing all permissions to all three entities, it creates the files with the below permission. ``` -rwxr-xr-x ``` The directory i am creating this in has permissions set as ``` drwxrwxrwx ``` Umask ``` 0022 ``` Can you guys please suggest what could be wrong? Edit : I can chmod the file to give it the permissions i plan to. I am curious why the above is failing.
You said it yourself, you have a umask of 022, so the write permission is omitted; From the creat man page: The effective permissions are modified by the process's umask in the usual way: The permissions of the created file are (mode & ~umask).
I see that there are several ways to distort an image. like...Circle, Diffuse, Marble, Ripple, Twirl, Water, ... I have come across some ipl functions like, iplRotateCenter(), iplWarpAffine(), iplShear() etc. does OpenCV have any such functions? if i need to use the ipl library in opencv, how to do it?
Open CV has such functions. Old openCV (C inreface), methods like cvWarpPerspective(), cvRemap(), cvLogPolar() New openCV (C++ inreface), methods like warpPerspective(), remap(),...
I have a variable , Float64 min; I want to display it only upto 1 place of decimal. Right now, I get 6 places if I use %f. How do I get only upto 1 place?
Use: ``` printf("%.1f", min); ``` See any reference such asthisfor details.
I'm wondering if C has anything similar to the python pickle module that can dump some structured data on disk and then load it back later. I know that I can write my structure byte by byte to a file on disk and then read it back later, but with this approach there's still quite some work to do. For example, if I have a single link list structure, I can traverse the list from head to tail and write each node's data on disk. When I read the list back from the on-disk file, I have to reconstruct all links between each pair of nodes. Please advise if there's an easier way. Thanks heaps!
An emphatic NO on that one, I'm afraid. C has basic file I/O. Any structuring of data is up to you. Make up a format, dump it out, read it in. There may be libraries which can do this, but by itself no C doesn't do this.
As a C programmer, I don't have much experience with exceptions. I'm rather used toerrnoas a means of communicating errors across several function calls. That having said, I don't see the distinguishing feature of exceptions, so... What is the fundamental difference between exceptions and usingerrno?
There are so many differences here it's hard to say where to start. First of all,errnoas used in C is a global variable; this means every routine that calls anerrno-setting subroutine must checkerrnobefore performing any other work, if it cares about correctness. Luckily enough,errno is threadsafe. C++ exceptions automatically unwind up the call stack until they find a function prepared to handle the fault. This means that in most cases users don't have to explicitly check every call for an error; instead they can collect error returns in one place. C++ exceptions can contain values other than integers, unlike errno.
Consider the following char* example: ``` char* s = "\n"; ``` How can this be converted into a single char that represents the new line character like so: ``` char c = '\n'; ``` In addition to processing newlines I also need to be able to convert any character with an escape character preceeding it into a char. How is this possible?
char c = *s;works. The'\n'inside the string is only two characters in source form: after compiling it is a single character; the same for all other escape character. The string"fo\111\tar", after compiling, has 7 characters (the 6 visible in the source code ('f','o','\111','\t','a', and'r') and a null terminator).
I am usingsscanfin a simple little project. However, I can't see any obvious way to find where in the input string thatsscanfdecided it found all of its data and stopped processing. Is there a way to do this?
I think %n is what you are looking for. Example: ``` sscanf("123", "%d%n", &i, &count); ``` This will store 3 in `count'.
``` int _cdecl f (int x) { return 0; } int _stdcall f (int y) { return 0; } ``` After name mangling will be: ``` _f _f@4 ``` Which doesn't conflict, is this allowed in c ,if not, why?
The keywords_cdecland_stdcallare not part of the C language. These are Microsoft extensions which were preceded by similar Borland extensions. In the standard C language, you can't declare a calling convention. Every function declared is, obviously, equivalent to what the MS compiler refers to as the "_cdecl" convention. It would be possible to use in-line assembly to distinguish the two functions when you call them. Because you're using a platform-specific vendor extension of C, you might consider using in-line assembly.
This question already has answers here:Closed12 years ago. Possible Duplicate:Is there an interpreter for C? Is there a "C implementation" which acts the same as the "C abstract machine" when executing a C program? That is, a simpleinterpreterfor C as it is described in a C standard such as C99. There are many implementations of the C programming language that are compilers (Clang, GCC, MSVC). I'm looking for an open source implementation of a C interpreter.
CINT -http://root.cern.ch/drupal/content/cintBut it is not C99 AFAIK.
I have an iPad app that outputs a PDF file that needs to be uploaded to a remote server. What are my options here? Is there a sFTP or FTP implementation for iOS that would help me achieve this? Can it be done using other protocol? Thanks!
FTP Client Wrapper in Objective-C for iPhone ConnectionKit(might not be iOS compatible)
I want to detect if mouse moved in 5 seconds, if yes time elapsed is showed. Here is my code, it seems ok but doesn't work correctly. ``` void timer() { if (ismouseclick(WM_MOUSEMOVE)) { movetime=clock(); clearmouseclick(WM_MOUSEMOVE); } if ((clock()-movetime)<6) { sprintf(time_str,"%d",clock(); outtextxy(275,483,"Time: "); outtextxy(340,483,time_str); } else { setfillstyle(1,0); bar(275,483,370,500); } } ```
Its about clock() function. You need to divide it to CLK_TCK (a constant) if you want seconds. ``` (clock()/CLK_TCK) ```
Makes a while since I've done some C and I have to refresh my understanding of pointers. Here is a function that modifies the content of a pointer. The question is if this code is correct. Is it enough if I only free the pointer or do I have to free the content of by the pointer ``` void foo(char **str) { // str has been allocated enough bytes for the following text *str = "allocate some text"; } int main(int arc, char *argv[]) { char *someString; foo(&someString); free(someString); // is this the correct place to free } ``` Thank you.
No, you don't want to callfree(), because you nevermalloc()-ed the data. More specifically, callingfree()on a pointer to a string literal results inundefined behaviour.
I've got two C strings that I want to append and result should be assigned to an lhs variable. I saw a static initialization code like: char* out = "May God" "Bless You";. The output was really"May GodBless You"on printing out. I understand this result can be output of some undefined behaviour. The code was actually in production and never gave wrong results. And it was not like we had such statements only at one place. It could be seen at multiple places of very much stable code and were used to form sql queries. Does C standard allow such concatenation?
Yes, it is guaranteed. Extract fromhttp://en.wikipedia.org/wiki/C_syntax#String_literal_concatenation: Adjacent string literals are concatenated at compile time; this allows long strings to be split over multiple lines, and also allows string literals resulting from C preprocessor defines and macros to be appended to strings at compile time
``` void TestPrint(char* format, ...) { va_list argList; va_start(argList, format); printf(format, argList); va_end(argList); } int main() { TestPrint("Test print %s %d\n", "string", 55); return 0; } ``` I need to get: ``` Test print string 55 ``` Actually, I get garbage output. What is wrong in this code?
Usevprintf()instead.
How does one copy the data that is pointed to by another pointer? I have the following ``` void *startgpswatchdog(void *ptr) { GPSLocation *destination; *destination = (GPSLocation *) ptr; ``` Will this do this correctly? I free the data that is passed into thread after passing it, so I need to copy the data.
If you want to copy data you should allocate new memory viamalloc, then copy your memory viamemcpy. ``` void *startgpswatchdog(void *ptr) { GPSLocation *destination = malloc(sizeof(GPSLocation)); memcpy(destination, ptr, sizeof(GPSLocation)); } ```
How do I change the log path of syslog daemon during runtime? My goal is to rotate log file every filesize or date, but I don't have logrotate in QNX/POSIX. Do I just do an edit and hope that the syslogd checks the .conf file everytime, or is there any other workaround? Thanks. Clarification: It has to be done in C or C++, not in script and console command line, for portabality issues.
Find the pid of syslogd. Let's say it's 123. Then, after you've finished your edit, on the command line, type one of these: ``` kill -HUP 123 kill -1 123 ```
I need C code for rounding up a double value to the next greatest integer value. For example, if I have: 1.0 (double)it must be1 (int)1.01 (double)it must be2 (int)5.67 (double)it must be6 (int)76.43 (double)it must be77 (int) Is there a solution?
Use theceil()function from<math.h>: ``` #include <math.h> double x = 1.01; // x = 1.01 double y = ceil(x); // y = 2.0 int i = (int)y; // i = 2 ``` or more concisely, if you just want the int result: ``` int i = (int)ceil(x); ```
In K&R it says that declaring a function prototype such asvoid foo();with an empty parameter list turns off function parameter type checking. Is this only forfooor for all functions?
That only applies to the function in question, not globally.
I have a set of C files to compile using gcc and make. The build process works fine. I want to know if I can obtain - during compilation - one C file containing all the source code without any preprocessor macro.
One simple was would be to make a file that included all the other source files. ``` $cat *.c > metafile.c ``` This would construct such a file, depending on how you set you 'pragma once' and ifndef's this file would probably not be able to compile on its own. On the other hand, if what you want in a file where all the preprocessor macro's have been unfolded and evaluated, then the answer is to add the following to gcc: -save-temps then the file .ii will contain the unfolded and evaluated macros
I have tested this fact on Turbo C++ 3.0, VC++ 2008 express and Borland C++ 6. If I add a C program with *.C extension to the project, I am able to compile and run the program without including header files. But in this case, some functions (like sqrt(), etc..) are returning erroneous values. If I add a C program with *.CPP extension to the project, I am not able to compile and run the program without including header files. Why?
In C, when the compiler does not find the definition of a function, it assumes it's an external function returning an integer. So the code compiles, and if the linker then finds a function with corresponding name it will run as well. But possibly with unexpected results.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been done so far to solve it.Closed9 years ago.Improve this question I'm not sure how to look for these. I am trying to find general unit testing libraries for linux file systems (FS structure is treated as anon). Thanks!
I found unit tests at these locations http://lwn.net/Articles/276617/ http://www.tuxera.com/community/posix-test-suite/ and this answer talking about performance tests:https://serverfault.com/questions/19487/how-to-do-filesystem-testing
I have a string array like{"myname","yourname","hisname"}and I am trying to send this array toCwith usingJNI. I could not find any clear solution for this. I have tried to take this string as achararraybut no success. Is there a way to do this?
You can write a simple function that takes ajobjectArrayobject, cast each one to jstring and then callGetStringUTFCharson it. Like this: ``` void MyJNIFunction(JNIEnv *env, jobject object, jobjectArray stringArray) { int stringCount = env->GetArrayLength(stringArray); for (int i=0; i<stringCount; i++) { jstring string = (jstring) (env->GetObjectArrayElement(stringArray, i)); const char *rawString = env->GetStringUTFChars(string, 0); // Don't forget to call `ReleaseStringUTFChars` when you're done. } } ```
I have a structure : ``` struct vertex { double a; double b; } struct polygon { int numofVertex; vertex v[10]; } ``` How to send this nested structure in MPI using MPI_Send?
Since your structure does not contain any pointers, it's easily possible. ``` MPI_Send(ptr_to_your_struct, sizeof(struct polygon), MPI_BYTES, ...); ```
Say If i want an input to be ``` [Name] [Name] ``` How would I detect ``` [Name] [Name] [Name] ``` and return error? Here is what I have so far, ``` char in[20]; char out[20]; scanf(" %s %s", out, in); ```
scanfreturns the number of validly converted arguments. So in your first case, the return value would be 2, in the latter case 3. To check the right amount of parameters, this might help: ``` char in[20]; char out[20]; char error[20]; int check; check = scanf(" %s %s %s", out, in, error); if(check != 2) { // TODO: error handling } ``` EDIT: now it should be working, see comments below. Of course, as stated by other posters: scanf is not considered a quite safe function since buffer overflows can occur, and you should avoid using it. It is better to read the inputs to a buffer withfgets()and the try to parse the arguments you want.
I have the following code: ``` int main() { const gchar *wew = gtk_entry_get_text(GTK_ENTRY(gtkentrywidget)); return 0; } ``` gtk_entry_get_text()returns aconst gchar*, so doeswewneed to be deallocated or not, and why?
Agcharis just a typedef for the C typechar. Youmust notdeallocate this specific pointer. Per thedocumentation: Returns : a pointer to the contents of the widget as a string. This string points to internally allocated storage in the widget and must not be freed, modified or stored.
I have a Cocos 2D game under development which also implements Box 2d and integration required me to change my .m classes to .mm Now I am trying to use a code that draws Fruit Ninja style swiping effect using the code athttps://github.com/hiepnd/CCBlade When Compiling I get error at the line #include < list > (CCBlade.h:14:0 CCBlade.h:14:15: error: list: No such file or directory) It works fine when integrated with a .m file, but the error is when trying to use it with .mm Any solutions for this ?
(after reading description in the comments) the problem is likely that some translation that isnotc++ or objc++ is including<list>via inclusion ofCCBlade.h check your build transcript for the failed file:-x objective-chere, the flag-xspecifies the language. if it is not c++ or objc++, you'll get the error you presented.
Does theSO_RCVTIMEOoption affectaccept(causing it to returnEAGAINorEWOULDBLOCKif the timeout expires)? Is there any behavior specified by the standard? I can't find it in the documentation foracceptor use of options: http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_10_16
While on POSIX SO_RCVTIMEO is defined for "an input function", and SO_SNDTIMEO is defined for "an output function", I can'r find any definition for "input function" or "output function", so I'll just say they are read/receive and write/send at least. In the specific case of Linux, SO_RCVTIMEO affectsaccept(), as can be seen by looking atinet_csk_accept(), and SO_SND_TIMEO affectsconnect(), as can be seen by looking attcp_sendmsg().
I google it, which says it's line printer. I don't think it make any sense...
Thelis for list and thepis for path. Check out all the othervariants, e.g. execl, execlp, execle, execv, execvp.
I wrote a simple c program. saved it with "c" suffix. Went to the terminal (in Linux Mint), typed in ``` gcc -o outputfile inputfile.c ``` In the directory containing inputfile.c a file called outputfile appeared, as I expected. I want to run the program, but clicking on the file does nothing. What am I doing wrong?
The program is running, but you're not seeing its output because the terminal isn't open. Open up your terminal and run it with ./outputfile If your program opened a window, you would see it by clicking on the file.
I have this code in C: ``` int tab[10] = {3, 10, 5, 7, 9, 4, 9, 4, 6, 8, 0}; printf("(int*)&tab[0]=%p (int*)&tab[1]=%p (int*)&tab[1]-(int*)&tab[0]=%d\n", (int*)&tab[0], (int*)&tab[1], ((int*)&tab[1]) - ((int*)&tab[0])); ``` And it returns: ``` (int*)&tab[0]=0xbf9775c0 (int*)&tab[1]=0xbf9775c4 (int*)&tab[1]-(int*)&tab[0]=1 ``` What I do not understand is that why the difference returned is 1 instead of 4 at the end. Could anyone tell me a way to print them (addresses and their difference) in a coherent way for (int *)?
Because you're doing pointer arithmetic. And pointer arithmetic is always done in units of whatever the pointer is pointing to (which in this case is 4, becausesizeof(int) == 4on your system). If you want to know the difference in raw addresses, then either multiply the result of the subtraction bysizeof(int), or cast the pointers tochar *before doing the subtraction.
How can I install the C library in MinGW? I always get some error like when I want to run some scripts: Cannot find <clang-c/Index.h>Please ensure libClang is installed How do I fix this problem?
That library is available from theLLVMproject.clangis a "a C language family frontend for LLVM." I don't believe they make binary releases yet. So, you would need to check out the code usingSubversion (SVN), and then build the library yourself under minGW. Please refer to the "Getting Started: Building and Running Clang" page for detailed instructions.
I have chosen an algorithm to encrypt a file. i may encrypt text or image files. How can I write a generic type of encryption method that works with both text and image files? I'm working with Objective-C.
What ever you are encrypting you might be using the data or specifically NSData, then converting it to char array and then applying the algorithm. So make a method that takes NSData as an argument, and return encrypted NSData.e.g. ``` -(NSData*)encrypt:(NSData*)data{ ///your algorithm return enCryptedData; } ``` Convert yourImageorFileintoNSDataand pass it to the method.
``` struct addrinfo *myAddrinfo, *curMyAddrinfo, hint; memset(&hint, 0, sizeof(struct addrinfo)); hint.ai_family = AF_INET; hint.ai_protocol = AI_PASSIVE; hint.ai_socktype = SOCK_STREAM; const int code = getaddrinfo(NULL, SERVER_PORT, &hint, &myAddrinfo); if ((code) != 0) { printf("getaddrinfo error occours: %s ", gai_strerror(code)); return 1; } ``` this gives the error: "ai_socktype not supported" if i comment out thehint.ai_protocol = AI_PASSIVE;it will get through, but i am wondering why it happens? thanks for your time
It's worth just adding here, as this is the top result when searching for "ai_socktype not supported" an alternative reason for it could be that hints is not zeroed on the stack; for that you need ``` memset(&hints, 0, sizeof hints); ``` Nissan's code of course did have that already
This is my a.c code : ``` #include <stdio.h> #include <socket.h> int main(void) { int count[4] = {[2] = 3 }, i; for (i = 0; i < 4; i++) printf("count[%d]=%d\n", i, count[i]); return 0; } ``` When I compile it, it shows: ``` a.c:2: fatal error: socket.h: No such file or directory compilation terminated. ``` So how do I include it / where can download it?
It should be: ``` #include <sys/socket.h> ``` Paths are given relatively to the /usr/include path. So e.g. the socket.h file is under /usr/include/sys/socket.h. You can search for it if you don't know: ``` find /usr/include/ -name SEARCHED_HEADER.h ```
Does C supports an equivalent of the triple-slash,XML Documentation Commentsthat Visual Studio uses to provide helpful tooltips for my code in C#, or am U just spoiled by being able to use them in C#? If it's not supported in C, are there other options?
C does not have any equivalent of XML documentation comments or JavaDoc. Trydoxygen.
I want to create a function which will a number and the position of the digit that I want to retrieve, ``` int getDigit(int value, int positionFromLeft) ``` Say, getDigit(534, 2) will return 3. What could be the easiest / efficient way to write this function?
First, it'll be aloteasier if you're willing to work for the right instead of the left (i.e., from the least significant digit). Given an input N,N%10will give the least significant digit. X/10 will shift X one digit to the right, x/100 will shift it two digits to the right, etc. If you really need to start from the left,log10should get you the total number of digits.
What happens when casting between these two in relation to the termination character? In C99 Objective-C.
I assume that a char is 8 bits on your system in this answer. If your architecture usesunsigned charaschartype then absolutely nothing will happen. If your architecture usessigned charaschartype then negative values of char will wrap around causing possibly unexpected results. This however will never happen to the termination null character. Please note, by "casting" nothing really happens, you just tell the compiler to interpret a certain location in the memory differently. This difference in interpretation would create the actual (side)effects of the cast.
I get an addres of string from assembler into C, and I need to get content of this address. How to do it? Google gives C++ examples with reinterpret_cast, but it not working in C (I suppose). I will appreciate if you will note needed libs too, tenx ``` #include <stdio.h> #include <stdlib.h> unsigned long const1(void); int main() { printf("Const: %d\n", const1()); return 0; } ```
If you've already got the address and you know it's a null terminated string, then all you need to do is treat it like a string. ``` printf("%s", (char*)alleged_string_address); ```
What's the most efficient/safest way to check if a string in C is made up only of spaces? Do I need to write a function myself to check or is there one in string.h that I can use?
Well, writing your own is trivial: ``` int IsSpaces( char * s ) { while ( * s ) { if ( ! isspace( * s ) ) { return 0; } s++; } return 1; } ``` Anything you use from the standard library is not likely to be much more efficient.
hi there i can compare people birthday in format YYYY-MM-DD with string (strcmp) functions. but i need compare todays date with person's birthday to display if his/her birthday is in 7 days or not_?. i searched "time.h" library but couldn't managed it. i appreciated if you can help.
I would usedifftimeon thetime_tvalues and compare against the number of seconds in a week...
Does anyone know of a free (non-GPL), decently performing compression library that supports packet oriented compression in C/C++? With packet oriented, I mean the kind of featureQuickLZ(GPL) has, where multiple packets of a stream can be compressed and decompressed individually while a history is being maintained across packets to achieve sensible compression. I'd favor compression ratio over CPU usage as long as the CPU usage isn't ridiculous, but I've had a hard time finding this feature at all, so anything is of interest.
zlib's maindeflate()function takes aflushparameter, which allows various different flushing modes. If you pass Z_SYNC_FLUSH at the end of each packet, that should produce the desired effect. The details are explained in thezLib manual. bzip2 has flushing functionality as well, which might let you do this kind of thing. Seehttp://www.bzip.org/1.0.5/bzip2-manual-1.0.5.html#bzCompress
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.Closed12 years ago. I want to adapt my old C codebases, that were written for IPv4, to work with IPv6. What do I need to change so that my C code works with both IPv4 and IPv6?
Find all code that usesinet_aton,inet_ntoa,gethostbyname,gethostbyaddr,htonl,htons,ntohl,ntohs, and any directsockaddr_inmanipulation and replace it with simple calls togetaddrinfoorgetnameinfo. This will make your code much simpler and more maintainable and IPv6 will automatically work with no additional effort.