question
stringlengths
25
894
answer
stringlengths
4
863
I have two arrays in C , and I want to copy N cells of array1 into array2 . Furthermore , I want to receive the exact number of copied cells . The functionstrncpyis not good enough for that , since it doesn't have a return value (or it does , but not the one that I'm looking for) . Any suggestions would be welcomed...
How about this: ``` size_t copy_n(T * dst, T const * src, size_t n) { // method 1 while (n--) { *dst++ = *src++; } // === OR === // method 2 memcpy(dst, src, n * sizeof(T)); return n; } ``` Usage: ``` T a[10]; T b[25]; copy_n(b + 5, a + 2, 7); // copies a[2]...a[8] into b[5]...b[11] ```...
Following is line of code in c. ``` i++=i++; ``` Output:Error Lvalue required.So what does this error indicate?
The result ofi++is not a lvalue and the standard requires the left operand of the assignment operator to be a lvalue. Even if it was allowed your program would invoke undefined behavior as you are trying to modify the same object twice between two sequence points.
I'm new to OpenCV 2.4.2, and write a simple program to display an image. The image is: And the code is: include "highgui.h" ``` int main(int argc, char** argv) { IplImage* img = cvLoadImage("logo.png"); cvNamedWindow( "Example1", CV_WINDOW_AUTOSIZE); cvShowImage("Example1", img); cvWaitKey(0); ...
That is the smallest window possible since window should occupy 3 buttons at the top. It will be OK if you enlarge the image.
I'm new to c, and this code confuses me: ``` pid_t getpid(void) ``` if what follows the type identifierpid_tis a variable (It's a variable declaration), but instead it's a function callgetpid(), I don't know what why this function call is used.
You're right thatpid_tis a type identifier, but it's not a variable.pid_tis the return type of the functiongetpid(). Every function in C has a return type. Functions are declared like this:returntype functionName(arguments) For example,int main(int argc, const char * argv[])returns anintand takes two arguments.
For example, in a linux-machine there are so many process. Each one is able to use a syscall, but usually few are used. Well, there is a tool or a manner to show when a syscall is used and which is the process associated?
You can use various tools, likestrace,ltraceand many other, although I'm not sure you want to trace all processes at the same time. Normally you'd attach to one process of interest and follow its system calls.
It is possible to convertinteger to stringinCwithoutsprintf?
There's a nonstandard function: ``` char *string = itoa(numberToConvert, 10); // assuming you want a base-10 representation ``` Edit: it seems you want some algorithm to do this. Here's how in base-10: ``` #include <stdio.h> #define STRINGIFY(x) #x #define INTMIN_STR STRINGIFY(INT_MIN) int main() { int anInte...
I have decided to use theGTKlibrary and I have been messing around with it. My problem does not lie within C or GTK itself, it all aboutEclipse. Even though my applications compile and run with no errors, but Eclipse is constantly telling me that there are problems such as: GTK_DIALOG_MODAL, GTK_MESSAGE_INFO, GTK_BU...
I guess Eclipse cannot find GTK's header files. You can tell it where to look for them by adding one or more include directories to the project properties: ``` Project → Properties → C/C++ General → Paths and Symbols → Includes ``` This works for Eclipse Indigo and Juno, at least.
``` #define B 100+B main() { int i= B; } ``` I know it's wrong, but just out of curiosity, when I compile it I get this weird error: "B was not declared in this scope". Why is it so? If this error was because the compiler removes the macro after its substitution then how does the following code worked fine, whe...
Here's the output of the preprocessor: ``` gcc -E x.c # 1 "x.c" # 1 "<built-in>" # 1 "<command-line>" # 1 "x.c" main() { int i= 100+B; } ``` As you can see, it did the substituion. Now comes the compile step which fails because there's noBdeclared. The other code is fine, here's the output: ``` main() { i...
I would like to declare an array in kernel module and to access it within a userspace app. how can I do it? How do I memory map it for using via userspace so it can be used by a user?
You will most likely need to implement a character device. Then in your instance ofstruct file_operationsimplement themmap function.
When definingt_ioctllike this, I get no warning: ``` long t_ioctl(struct file *filep, unsigned int cmd, unsigned long input){ ``` When definingt_ioctllike this: ``` static long t_ioctl(struct file *filep, unsigned int cmd, unsigned long input){ ``` I get the warning: ``` warning: 't_ioctl' defined but not used ``...
Most likely you have a definition like this in the same file: ``` static struct file_operations fileops = { .read = t_read, .write = t_write, /* etc. ... */ }; ``` And you're missing ``` .compat_ioctl = t_ioctl, /* or .ioctl/.unlocked_ioctl, depending on version etc. */ ```
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question I created a library that I want to use in another part of my program, but I don't want to...
http://crasseux.com/books/ctutorial/Building-a-library.html Just googled "building c libraries".
I'm trying to build an implementation of<ctype.h>with a lookup table and bits masks (this method). But I've seen in the C11 standard I need some informations about the current locale : 7.4 Character handling<ctype.h>[...]2 The behavior of these functions is affected by the current locale. So, do I need a<locale.h>im...
A fast simple way to do this for 8-bit characters is to have one bitmask for each defined value of LC_CTYPE. For wide character types you can reduce the size of the tables by some method like a 2-stage lookup. To be efficient, this will need to be designed for each character encoding. Having a dynamic lookup on LC_...
I have two arrays in C , and I want to copy N cells of array1 into array2 . Furthermore , I want to receive the exact number of copied cells . The functionstrncpyis not good enough for that , since it doesn't have a return value (or it does , but not the one that I'm looking for) . Any suggestions would be welcomed...
How about this: ``` size_t copy_n(T * dst, T const * src, size_t n) { // method 1 while (n--) { *dst++ = *src++; } // === OR === // method 2 memcpy(dst, src, n * sizeof(T)); return n; } ``` Usage: ``` T a[10]; T b[25]; copy_n(b + 5, a + 2, 7); // copies a[2]...a[8] into b[5]...b[11] ```...
Following is line of code in c. ``` i++=i++; ``` Output:Error Lvalue required.So what does this error indicate?
The result ofi++is not a lvalue and the standard requires the left operand of the assignment operator to be a lvalue. Even if it was allowed your program would invoke undefined behavior as you are trying to modify the same object twice between two sequence points.
I'm new to OpenCV 2.4.2, and write a simple program to display an image. The image is: And the code is: include "highgui.h" ``` int main(int argc, char** argv) { IplImage* img = cvLoadImage("logo.png"); cvNamedWindow( "Example1", CV_WINDOW_AUTOSIZE); cvShowImage("Example1", img); cvWaitKey(0); ...
That is the smallest window possible since window should occupy 3 buttons at the top. It will be OK if you enlarge the image.
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.Closed11 years ago. i have written this program with a ...
Here is the working code: ``` #include<stdio.h> int fun() { printf("amol singh"); return 0; } main() { int (*ptr)(); ptr=fun; (*ptr)(); } ```
``` float4 PixelShaderFunction(float2 TexCoord: TEXCOORD0) : COLOR0 { float4 color1 = tex2D(inputSampler, TexCoord); float numb = TestFunc( 5 ); float4 color3 = color1 + numb; return color3; } float TestFunc(float numb) { return numb + 1; } ``` I get an error saying error x3004: undeclared identifier 'TestFunc'
Either declareTestFunc()before using it in PixelShaderFunction, or move it entirely before that. I. e.: ``` float TestFunc(float); float PixelShaderFunction() { // ... } float TestFunc(float n) { // ... } ``` or ``` float TestFunc(float n) { // ... } float PixelShaderFunction() { // ... } ```
There is a function which takes a function pointer argument of the formvoid *(*func)(void *)and I am reading some code which calls it with the following argument(void *(*)(void *))(-1). Is this just casting-1to the correct function pointer type or is it something else? I am unsure of what it means.
Yes, that's just a typecast. Without seeing the code in context, it's not really possible to decidewhysomeone might be doing that, though. It's often convenient to usecdeclto answer questions like this one: ``` $ cdecl Type `help' or `?' for help cdecl> explain (void *(*)(void *)) cast unknown_name into pointer to ...
Locked. This question and its answers arelockedbecause the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. I see in one place that Arduino uses 'standard' C, and in another that it uses 'standard' C++, so on and so forth. Which is it?
Arduino sketches are written in C++. Here is a typical construct you'll encounter: ``` LiquidCrystal lcd(12, 11, 5, 4, 3, 2); ... lcd.begin(16, 2); lcd.print("Hello, World!"); ``` That's C++, not C.
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.Closed11 years ago. The following is the code in c. ``...
The static keyword means that a variable may have only and exactly one instance in its scope, and that instance is invisible out of its scope. Neither of these requirements make sense for a function argument: it may be called multiple times, at a different memory address, and as it's meant for communication, it has to...
I need to write something like 64 kB of data atomically in the middle of an existing file. That is all, or nothing should be written. How to achieve that in Linux/C?
I don't think it's possible, or at least there's not any interface that guarantees as part of its contract that the write would be atomic. In other words, if there is a way that's atomic right now, that's an implementation detail, and it's not safe to rely on it remaining that way. You probably need to find another so...
This question already has answers here:Closed11 years ago. Possible Duplicate:Is it possible to have a variadic function in C with no non-variadic parameter? Is it possible to create a C varargs function with no arguments? For example: ``` int foo(...); ``` I want to do something like the following: ``` list* cr...
No. Variadic functions must have one or more named parameters. Try it yourself, you'll see something like: error: ISO C requires a named argument before '...'
I've always seen the C include extension as .h. I am working on a project with include extensions of .r. I believe the extension .r refers to Mac resource forks. I'm wondering if C allows the extension on an include file to be anything? The code compiles without any errors. examples: ``` #include "HostTypes.h" ...
Yes, you can do this without worries. The C preprocessor includes whatever you tell it to include.
I'm working on a project from school, and we were given a .o and a corresponding .h file. We need to use several functions from the .o file in our .c program. Just placing it in the same directory doesn't work. I tried to look for something like this in the project properties, but no good. I keep getting../code_files/...
I found this answer: I tried doing something similar, only I didn't think of the miscellaneous thing
I can seem to only read file into memory if I explicitly declare the buffer size. This works ``` #include <stdio.h> int main(){ FILE *fp = fopen("test.log", "rb"); char buffer[37]; fread(buffer, 1, 36, fp); printf("%s", buffer); } ``` This will add junk to the output ``` #include <stdio.h> int main(){ FIL...
insertbuffer[siz]='\0';beforeprintf("%s", buffer);
There is a way to monitor directories for changes like FileSystemWatcher but in C? NOTE: I (have to) use gcc.
SeeFindFirstChangeNotificationorReadDirectoryChangesW.
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.Closed11 years ago. The following is the code in c. ``...
The static keyword means that a variable may have only and exactly one instance in its scope, and that instance is invisible out of its scope. Neither of these requirements make sense for a function argument: it may be called multiple times, at a different memory address, and as it's meant for communication, it has to...
I need to write something like 64 kB of data atomically in the middle of an existing file. That is all, or nothing should be written. How to achieve that in Linux/C?
I don't think it's possible, or at least there's not any interface that guarantees as part of its contract that the write would be atomic. In other words, if there is a way that's atomic right now, that's an implementation detail, and it's not safe to rely on it remaining that way. You probably need to find another so...
This question already has answers here:Closed11 years ago. Possible Duplicate:Is it possible to have a variadic function in C with no non-variadic parameter? Is it possible to create a C varargs function with no arguments? For example: ``` int foo(...); ``` I want to do something like the following: ``` list* cr...
No. Variadic functions must have one or more named parameters. Try it yourself, you'll see something like: error: ISO C requires a named argument before '...'
I've always seen the C include extension as .h. I am working on a project with include extensions of .r. I believe the extension .r refers to Mac resource forks. I'm wondering if C allows the extension on an include file to be anything? The code compiles without any errors. examples: ``` #include "HostTypes.h" ...
Yes, you can do this without worries. The C preprocessor includes whatever you tell it to include.
I'm working on a project from school, and we were given a .o and a corresponding .h file. We need to use several functions from the .o file in our .c program. Just placing it in the same directory doesn't work. I tried to look for something like this in the project properties, but no good. I keep getting../code_files/...
I found this answer: I tried doing something similar, only I didn't think of the miscellaneous thing
I can seem to only read file into memory if I explicitly declare the buffer size. This works ``` #include <stdio.h> int main(){ FILE *fp = fopen("test.log", "rb"); char buffer[37]; fread(buffer, 1, 36, fp); printf("%s", buffer); } ``` This will add junk to the output ``` #include <stdio.h> int main(){ FIL...
insertbuffer[siz]='\0';beforeprintf("%s", buffer);
There is a way to monitor directories for changes like FileSystemWatcher but in C? NOTE: I (have to) use gcc.
SeeFindFirstChangeNotificationorReadDirectoryChangesW.
I've been using a program, compiled using GCC 4.4.1 (ISO C99) and noticed this quirk today. Although it works on target without any problem neither does compiler emit any warning with -Wall. ``` void mutex_init(mutex_t *mutex) { if(unlikely(mutex->magic == MUTX_MAGIC_CHAR)) return; mutex->owner = NULL; mutex-...
No,magic->owneris equivalent to(*magic).owner. The->operator is meant to work on pointers to structures, while the.operator work on structures directly.
what isalloc.h? some questions on SO likethisandthishave includedalloc.h. but,when i tried to include it gcc gives erroraserror: alloc.h: No such file or directory Has such file ever existed or those questions have included it just by mistake?
It's for dynamic memory allocation, but it isn't a ANSI C standard library. If you are using gcc then use stdlib for dynamic memory allocation: ``` #include <stdlib.h> ``` For some more information, have a lookhere. If you read carefully the question you have linked, actually the problem was exactly trying to compi...
In my makefile I would like to print a process message (something like "Build $(PROJ_NAME) project...") before building the dependencies of a target. For example my target look like this one below: ``` $(PROJ_NAME): $(OBJS) echo "Build $(PROJ_NAME) project..." $(LD) $(LDFLAGS) --gc-sections "-T$(MISC_DIR)/$(P...
You could add another dependency before the object files, that is always made. Something like this: ``` $(PROJ_NAME): pre_build $(OBJS) $(LD) $(LDFLAGS) --gc-sections "-T$(MISC_DIR)/$(PROJ_NAME).ld" ... .PHONY: pre_build pre_build: @echo "Build $(PROJ_NAME) project..." ``` Thispre_buildtarget will (in most ...
I've read inthis postregarding named and unnamed semaphore , which states that a named semaphore is used for 2 unrelated processes , and unnamed semaphore is used for 2 related processes . If my program works with both related and unrelated processes , can I use a named semaphore for both cases ? Thanks
Yes you can, a named semaphorealwaysworks. As stated in the post you linked an unnamed semaphore is easier to handle (because the OS does take care of a lot of stuff automatically) but requires some shared structures between the involved processes.
I would like to create a group in Windows, and I've found the next reference but I don't know if I'm on the right path: http://msdn.microsoft.com/en-us/library/aa374177.aspx
No. The right way is using aNet* functions family.In your case to create a new windows user group you have to use aNetGroupAddfunction.
This question already has answers here:Closed11 years ago. Possible Duplicate:How do I set the working directory of the parent process? Is possible to make the change of directory persist after program exit? Since it resets to original directory when program exits.
A child process cannot affect its parent's current directory, any more than it can really affect its parent'senvironment. If the child removes the parent's current directory, it makes it so that the parent doesn't have a named current directory, but that's about all.
I read some codes as below: ``` void mcachefs_file_start_thread() { pthread_attr_t attrs; pthread_attr_init(&attrs); pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_JOINABLE); pthread_create(&mcachefs_file_threadid, &attrs, mcachefs_file_thread, NULL); } ``` Here, what is the usage of settingattrsasPTHREA...
Yes,PTHREAD_CREATE_JOINABLEis the default attribute. The purpose is that it allows you to callpthread_joinon the thread, which is a function that waits until the thread finishes, and gives you return value if its main routine. Sometimes, when you're creating a thread to do some background work, it might be a good ide...
I have two arrays: char line[128]which is populated using: ``` fgets(line,sizeof line, file) ``` and ``` char* array; array=(char*) malloc(j*sizeof(char)); ``` where j is some integer. I'd like to assign an element of "line" to the corresponding element of "array". Thanks in advance for any help!
As these are char arrays you could just use strcpy ``` strcpy(array,line); ``` taking care that your dynamic array is large enough to accomodate the line array. This would copy the whole array, or for just an individual element, ``` array[i] = line[i]; ``` taking care that i is within limits of the arrays.
Can someone please explain why I should use strstr or string find() ? Which one is faster, at where ?
In C++ you should use std::string::find(), in C you should use strstr(). The difference in performance should not be significant.
I am investigating into if I can use a library likeGHMMwith my python web service in which runs on AppEngine.
Short answer: no https://developers.google.com/appengine/kb/commontasks What third party libraries can I use in my application? You can use any pure Python third party libraries in your Google App Engine application. In order to use a third party library, simply include the files in your application's directory, an...
The Xcode project I am working on contains a.cfile which I sourced fromthis tutorialI want to open the serial port and listen for data coming in, so I created a method in a.mfile which I namedaddRFID. How would I go about opening the port and listen for data coming in on the RX line within the.mfile?
c files can be included in your project in exactly the same way as .m files. My suggestion is to create a header file for that .c (i.e. make a .h in which you declare all of the functions and variables, constants, etc), and import that in your .m, then use the functions as you see fit, calling them directly from insid...
I have an array and am able to print the portion of it that I want. But what I would like to do is write that portion to a new array. Does anyone know how to do this? Thanks in advance! ``` char line[128]; char *line1; char *pch,*pch1; char key[]="REMARK 290 "; char key1[]="X"; int start=24; int l...
Pipes are used to communicate between processes. You can'tpipefrom one array to another. If theprintf()at the end of your code does what you want, then you simply want to usesprintf()to put the result of the "print" in an array instead of sending it tostdout.
I was wondering what is the difference betweenuint32_tanduint32, and when I looked in the header files it had this: ``` types.h: /** @brief 32-bit unsigned integer. */ typedef unsigned int uint32; stdint.h: typedef unsigned uint32_t; ``` This only leads to more questions: What is the difference betwe...
unsignedandunsigned intare synonymous, much likeunsigned short [int]andunsigned long [int]. uint32_tis a type that's (optionally) defined by the C standard.uint32is just a name you made up, although it happens to be defined as the same thing.
I would like to find out if a process is running. I DO NOT want to use any system("") commands. Is there any C based function that lets you know if a process is running? I would like to provide the process name and want to know if it's running. Thanks,
Sure, usekill(2): ``` #include <sys/types.h> #include <signal.h> int kill(pid_t pid, int sig); ``` If sig is 0, then no signal is sent, but error checking is still performed; this can be used to check for the existence of a process ID or process group ID. So just callkill(pid, 0)on the process ID of the p...
Why is this a common practice to haveassertmacro do something useful only in debug configuration? If it exists to test invariants and detect coding bugs, then would not it be easier to go ahead and do the same big boom in production software? I have some S60 background and there exist__ASSERT_ALWAYSand__ASSERT_DEBUG,...
Asserts are made for stuff that shouldnever happen, i.e. if it does then there is a bug in your code that you need to fix. Releases are builds that are "supposed" to be bug free, and killing application with the assert for the user is as bad as any other faulty behavior.
I´m currently having a hard time with the autoformatter in eclipse... aiming on my own template for the formatter I´m getting troubles with the line wrapping and it seems that I´m missing any property thread. The basic configuration works for me but I´m stuck at this, maybe anyone has got a clue where I can find the ...
Go toWindows->Preferences->java->code style->formatter Here, you can import other formatter, export yours , edit any formatter. Select Edit on current formatter and chooseLine Wrappingtab. EDIT:Your problem seems to be related withMaximum line size.
``` #include<stdio.h> int main() { int i; string A[]={"Ahmet", "Mehmet", "Bulent", "Fuat"}; for(i=0;i<=3;i++){ printf("%s",A[i]); } return 0; } ``` How can i see my array's elements as output? Compiler says "'string' undeclared".
This way: ``` char *A[] = {"Ahmet", "Mehmet", "Bülent", "Fuat"}; ``` Ais an array of pointers tochar.
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed9 years ago.Improve this question I'm looking for a simple (preferably C-based) Javascript compiler that I can use to ...
TheV8isn't good enough for you?
I have a string like "0189", for which I need to generate all subsequences, but the ordering of the individual characters must be kept, i.e, here 9 should not come before 0, 1 or 8. Ex: 0, 018, 01, 09, 0189, 18, 19, 019, etc. Another example is "10292" for which subsequences would be: 1, 10, 02, 02, 09, 29, 92, etc. ...
Try a recursive approach: the set of subsequences can be split into the ones containing the first character and the ones not containing itthe ones containing the first character are build by appending that character to the subsequences which don't contain it (+ the subsequence which contains only the first character ...
In C/C++ How can I read from serial port, without removing the info I have already read from the buffer? I want to do something like the Peek function of arduino (http://arduino.cc/en/Serial/Peek) in a linux machine.
The serial port is accessed as though it is a file using a file descriptor so afgetc ungetcmethod should work.
I work on an embedded System - not a windows system. I declare: ``` static uint_8 i = 0; ``` So i is defined 0 at start moment. The question: After a reset is i redefined as 0 or does it get a junk information at the ram adress? E.g do I need to write a init function to redefine i as 0? Thanks
This depends on your runtime library (if any). If you have an existing runtime library, it will probably initialise your static data to zero on startup (beforemain()). However, some embedded systems may not have complete runtime library support so you may have to do this yourself.
Using Salsa20, how would one seek to a byte position (assume it's a multiple of 64) (using the public domain C implementation athttp://cr.yp.to/snuffle/salsa20/merged/salsa20.c I've tried this but it doesn't work: ``` void seekIV(unsigned long int pos) { int low_32bits, high_32bits; pos /= 64; low_32bits = pos & 0...
D'OH... the answer is... I forgot to also fseek in the stream ;)
Suppose, I wrote a function as follows: ``` void foo() { char *strArr[] = {"AA", "BB", "CC"}; ... } ``` Where the strArr will be allocated? When will it be initialized? For some reason I remember that such an array will be allocated in static memory space, not on the stack and initialized at the program start...
It has automatic storage so it will be allocated on the stack of the function. The elements belong to this automatic storage but the string literals themselves are stored in a persistent, possibly read-only area.
I am trying to return an array usingmallocin a function: ``` char* queueBulkDequeue(queueADT queue, unsigned int size) { unsigned int i; char* pElements=(char*)malloc(size * sizeof(char)); for (i=0; i<size; i++) { *(pElements+i) = queueDequeue(queue); } return pElements; } ``` The pro...
As the memory allocated by malloc() is on the heap and not on the stack, you can access it regardless of which function you are in. If you want to pass around malloc()'ed memory, you have no other option than freeing it from the caller. (in reference counting terms, that's what is called an ownership transfer.)
I would like to define the32(32 bit compilation) and64(64 bit compilation) in Visual C. Is there any predefined macros for this? I've scoured through MSDN in vain. Do you think this kind of definition for32and64would work? ``` #define _32_ if !(defined __LP64__ || defined __LLP64__) || defined _WIN32 && !defined _WI...
Fromthe docs: _M_IX86: Defined for x86 processors. ... This is not defined for x64 processors._M_X64: Defined for x64 processors._M_IA64: Defined for Itanium Processor Family 64-bit processors._WIN32: Defined for applications for Win32 and Win64. Always defined._WIN64: Defined for applications for Win64. Take your p...
I know there is a system_profiler command that returns information on mac and I also saw someone mention that the source code of that command hasn't been made public. How does one find that information considering that the code has to be written in C only? I would like to retrive as much as I can using the code and n...
The sysctl() function may give you the info you want. In your terminal type ``` man -s3 sysctl ```
Would it be possible to embed the private and public key for a simple server application into it through the C/C++ APIs? Preferably without hacking the entire OpenSSL library first. And by embed I mean by passing either something like a string or a char* to the API instead of reading directly from a file. Thanks.
You can use thed2i_X509()function to directly convert a DER-encoded certificate from anunsigned char *buffer into an X509 object: ``` const unsigned char cert_DER[] = /* ... */; const unsigned char *p = cert_DER; X509 *cert_X509 = d2i_X509(NULL, &p, sizeof cert_DER); ``` There are similard2i_*()functions for other ...
This question already has answers here:Closed11 years ago. Possible Duplicate:C -> sizeof string is always 8 If I dosizeof("HELLO");I get 6, which is expected, however if I have: ``` void printLength(char *s) { sizeof(s); } ``` When passing "Hello" to to this functionsizeofreturns 8. Why is this?
What you are getting is size ofchar *. To get it's actual length, usestrlen.
I am compiling code withclangwith -O4 optimization. However, I want to disable inlining of functions. I have my own LLVM pass that injects some code to the generated code. After my pass, I want to enable the inlining of functions. How can I do that.
You can use opt whichsaysit can run passes in any order. ``` clang -c main.cpp -O0 -emit-llvm | opt -load yourplugin -yourpass -inline ```
I would like to do this in one line (C programming language): ``` int x = index >> 8; int y = x < 10 ? x+1 : x+2; ``` Is it possible? How do I reference to value before ? sign, if I don't have it stored in separate integer? ``` "int y = (index >> 8) < 10 ? [what]+1 : [what]+2;" ```
You simply need to repeat the expression: ``` int y = (index >> 8) < 10 ? (index >> 8) + 1 : (index >> 8) + 2; ``` It's not very nice, or readable, so I don't get why you must do it this way. There's no built-in way in the language to reference the expression before the?. Since expressions can have side-effects in C...
i have two double arrays, let's say A and B. i want to compare their results to 7 significant digits. will the following be correct to make the comparison? ``` k = pow(10,7); for(...) { if(((int)A[i]*k)!=((int)B[i]*k)) { ... } } ```
In order to compare doubles, you could use something like this: ``` bool fequal(double a, double b) { return fabs(a-b) < epsilon; } ``` Taken fromhere. fabsreference. But make sure you understand thepotential pitfalls.
I have a print-function: ``` myprintf("%d ..... other_things_to_print"); ``` I call this myprintf() function from many different functions.Suppose function func() calls myprintf() but it has nothing to pass for the "%d" (shown as bold in the myprintf() above).I don't wanna print zero in place of this"%d" How can Ia...
If you don't want to print the%dwhen no argument was supplied for it, then use anif()-elsestructure inside yourmyprintf()function to not output that position. Here is an example: ``` if( d_variable ) { printf("%d ..... other_things_to_print"); } else { printf("..... other_things_to_print"); } ``` This is wha...
I have fixed an error in my code, but every time I callndk-buildthe same error is STILL there. I have calledndk-build cleanfifteen times at least, but I have had no luck. I have gone into my project and deleted my.o files. What should I do? Notice the spelling ofinitilized/initialized:
In Eclipse, menuWindow->project->Clean.
Are there any standards for error code handling? What I mean by this is not how a particular error event is handled but what is actually returned in the process. An example of this would be when an error in opening a file is identified. While theopen()function may return its own value, the function that called theopen...
I don't think ther's a standard, all errors must be detected and handled (the caller should always handle errors). in Unix in general: the standard C library for exemple alwaysreturn -1 on failandset the global variable errnoto the correct value.Some libraries for examplereturn NULLforinexistantfield rather thanabort...
This question pertains to ANSI C. I think that it should be a simple answer...so which of these methods is the fastest? It doesn't really have anything to do with my current projects but it just came to mind one day and I didn't see the answer right away on the web...
printfis by far preferable, by many orders of magnitude and in every sense. It is a library function that's part of the C standard, and it makes your own program print the desired output.systemon the other hand launches a new, separate process (something that takes a comparable eternity), and you still have to hope th...
I am embedding mono into an application i'm writing. One of the objects I have created looks like this: ``` public class MessageObject { public byte messagetype; public byte[] message; } ``` If i usemono_field_get_value_objectI can get aMonoObject *that represents the message array, but How can I access it like ...
Explicitly castMonoObject *toMonoArray *, and then simply use the functions as documentedhere.
Could someone help me by telling what is the Visual C equivalent of fseeko, fseeko64; ftello, ftello64? Thanks :)
There are no functions that returns/use off_t, if you need a 64bit position you can use: _fseeki64 _ftelli64
Why a char variable gets 'b' from assignment of 'ab', rather 'a'? ``` char c = 'ab'; printf("c: %c\n", c); ``` Prints: ``` c: b ```
According to the standard, it is implementation defined. From6.4.4.4 Character constants: An integer character constant has type int. The value of an integer character constant containing a single character that maps to a single-byte execution character is the numerical value of the representation of the mapped c...
This question already has answers here:Closed11 years ago. Possible Duplicate:C -> sizeof string is always 8 If I dosizeof("HELLO");I get 6, which is expected, however if I have: ``` void printLength(char *s) { sizeof(s); } ``` When passing "Hello" to to this functionsizeofreturns 8. Why is this?
What you are getting is size ofchar *. To get it's actual length, usestrlen.
I am compiling code withclangwith -O4 optimization. However, I want to disable inlining of functions. I have my own LLVM pass that injects some code to the generated code. After my pass, I want to enable the inlining of functions. How can I do that.
You can use opt whichsaysit can run passes in any order. ``` clang -c main.cpp -O0 -emit-llvm | opt -load yourplugin -yourpass -inline ```
I would like to do this in one line (C programming language): ``` int x = index >> 8; int y = x < 10 ? x+1 : x+2; ``` Is it possible? How do I reference to value before ? sign, if I don't have it stored in separate integer? ``` "int y = (index >> 8) < 10 ? [what]+1 : [what]+2;" ```
You simply need to repeat the expression: ``` int y = (index >> 8) < 10 ? (index >> 8) + 1 : (index >> 8) + 2; ``` It's not very nice, or readable, so I don't get why you must do it this way. There's no built-in way in the language to reference the expression before the?. Since expressions can have side-effects in C...
i have two double arrays, let's say A and B. i want to compare their results to 7 significant digits. will the following be correct to make the comparison? ``` k = pow(10,7); for(...) { if(((int)A[i]*k)!=((int)B[i]*k)) { ... } } ```
In order to compare doubles, you could use something like this: ``` bool fequal(double a, double b) { return fabs(a-b) < epsilon; } ``` Taken fromhere. fabsreference. But make sure you understand thepotential pitfalls.
I have a print-function: ``` myprintf("%d ..... other_things_to_print"); ``` I call this myprintf() function from many different functions.Suppose function func() calls myprintf() but it has nothing to pass for the "%d" (shown as bold in the myprintf() above).I don't wanna print zero in place of this"%d" How can Ia...
If you don't want to print the%dwhen no argument was supplied for it, then use anif()-elsestructure inside yourmyprintf()function to not output that position. Here is an example: ``` if( d_variable ) { printf("%d ..... other_things_to_print"); } else { printf("..... other_things_to_print"); } ``` This is wha...
I have fixed an error in my code, but every time I callndk-buildthe same error is STILL there. I have calledndk-build cleanfifteen times at least, but I have had no luck. I have gone into my project and deleted my.o files. What should I do? Notice the spelling ofinitilized/initialized:
In Eclipse, menuWindow->project->Clean.
Are there any standards for error code handling? What I mean by this is not how a particular error event is handled but what is actually returned in the process. An example of this would be when an error in opening a file is identified. While theopen()function may return its own value, the function that called theopen...
I don't think ther's a standard, all errors must be detected and handled (the caller should always handle errors). in Unix in general: the standard C library for exemple alwaysreturn -1 on failandset the global variable errnoto the correct value.Some libraries for examplereturn NULLforinexistantfield rather thanabort...
This question pertains to ANSI C. I think that it should be a simple answer...so which of these methods is the fastest? It doesn't really have anything to do with my current projects but it just came to mind one day and I didn't see the answer right away on the web...
printfis by far preferable, by many orders of magnitude and in every sense. It is a library function that's part of the C standard, and it makes your own program print the desired output.systemon the other hand launches a new, separate process (something that takes a comparable eternity), and you still have to hope th...
I am embedding mono into an application i'm writing. One of the objects I have created looks like this: ``` public class MessageObject { public byte messagetype; public byte[] message; } ``` If i usemono_field_get_value_objectI can get aMonoObject *that represents the message array, but How can I access it like ...
Explicitly castMonoObject *toMonoArray *, and then simply use the functions as documentedhere.
Could someone help me by telling what is the Visual C equivalent of fseeko, fseeko64; ftello, ftello64? Thanks :)
There are no functions that returns/use off_t, if you need a 64bit position you can use: _fseeki64 _ftelli64
Why a char variable gets 'b' from assignment of 'ab', rather 'a'? ``` char c = 'ab'; printf("c: %c\n", c); ``` Prints: ``` c: b ```
According to the standard, it is implementation defined. From6.4.4.4 Character constants: An integer character constant has type int. The value of an integer character constant containing a single character that maps to a single-byte execution character is the numerical value of the representation of the mapped c...
I am using beaglebone, that contains Angstrom distribution. In that there is no build directory, so I have downloaded the kernel source from kernel.org, but the size of that is too much for my SD card (~430 MB). So I thought of removing some unwanted files or directories. Which directories are not necessary to build ...
You can cross-compile kernel on your PC - it would be faster and much more comfortable. All you have to do is to get cross-compiler. As i remember there were some prepared for beagleboard so you can try to use them. Of course you can build it by yourself - there are tools such as crosstool-ng or buildroot, which can ...
When C has the/operator to divide two numbers, what is the purpose of having thediv()library function? Is there any scenario where/can't be used butdiv()can?
From the C99 Rationale document: (7.20.6.2 The div, ldiv, and lldiv functions) Because C89 had implementation-defined semantics for division of signed integers when negative operands were involved, div and ldiv, and lldiv in C99, were invented to provide well-specified semantics for signed integer division and remain...
Is there a way to convert a string to a number and vice versa in C? I know that I can use iostream in C++ and use atoi() or sprintf() etc.. I want to know if there's a way to accomplish this in C without the use of streams. The only solution I see at this point is to create my own function, unless someone knows an alr...
Both of these are C functions: atoiis instdlib.hsprintfis instdio.h And since these are included as part of C, neither require C++ streams.
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed11 years ago.Improve this question I have trouble writing arecursivefunction in C: ``` void func(int n) ``` which for a given number n prints "1" andnzeroe...
Just some pointers: Why do you think you must print "1" only on the first call of the function?Why can't you print it on the last call of the recursive function and then print all the 0's?How will you determine if a call to the function is the last call in the recursive way? (Can the value of "n" hold the answer?)
I need a way to analyze output file of my GCC compiler for ARM. I am compiling for bare metal and I am quite concerned with size. I can usearm-none-eabi-objdumpprovided by the cross-compiler but parsing the output is not something I would be eager to do if there exists a tool for this task. Do you know of such a tool ...
You can usenmandsizeto get the size of functions and ELF sections. To get the size of the functions (and objects with static storage duration): ``` $ nm --print-size --size-sort --radix=d tst.o ``` The second column shows the size in decimal of function and objects. To get the size of the sections: ``` $ size -A ...
I want people to stop using functions likesprintfas it is considered anunsafe function. Is there a compiler way to give compilation error ifsprintfis used in the code, or any other trick?
GCC supports this sort of thingwith#pragma GCC poison. Using this pragma followed by a list of identifiers will cause the use ofanyof the identifiers in the program to throw an error. For example, this program won't compile: ``` #include <stdio.h> #pragma GCC poison fprintf sprintf int main (void) { char foo[100]...
I seestrerror_r(...) API is no longer supported in visual C++ 2008, probably because of issue with thread safety. I want to use similar functionality in my program. Is there any other winapi which does the same thing as strerror_r(..)?
You can trystrerror_s. It appears to be thread safe. Note that the parameter order of strerror_s is different from strerror_r. If writing portable code you might want to use a define ``` #define strerror_r(errno,buf,len) strerror_s(buf,len,errno) ```
snprintfin a loop does not work onlinuxbut it works properly onwindows. ``` #include <stdio.h> #include <stdlib.h> int main( int argc, char **argv) { char buffer[255] ={0}; for ( int i = 0; i < 10; i++) { snprintf(buffer, 255, "%s:%x\0",buffer, i ); } printf ( "BUFFER = %s\n", b...
You can avoid the undefined behavior of using the buffer both as the target string and as an argument like this: ``` #include <stdio.h> #include <stdlib.h> int main( int argc, char **argv) { char buffer[255] ={0}; int offset = 0; for ( int i = 0; i < 10; i++) { offset += snprintf(buffer + offset, 255 - off...
I've source code of a huge project in one directory (/my/src/) and I want the cscope files to be built in some other directory (/my/db/). How can I do that ?
Try following steps: 1 . Generate cscope.files ``` find /my/src -name '*.c' -o -name '*.h' > /my/db/cscope.files ``` 2 . Run cscope on the generated result ``` cscope -i /my/db/cscope.files ``` 3 . Export to environment variable ``` CSCOPE_DB=/my/db/cscope.out; export CSCOPE_DB ```
Is it possible to import in C# structs definitions from C dlls? In all the examples I saw were to redefine the structs in C#. What if the struct changes? I need to alter in two locations in my project... ``` struct MyCStruct { unsigned long A; unsigned long B; unsigned long C; }; ``` and in C#: ``` [St...
You could compile your structs as C++/CLI where the compiler generates the managed counterparts for you and you can reference them then. You would need an ifdef to prepend value to make it a .NET struct. ``` #ifdef CLIEXPORT #define value #endif CLIEXPORT struct MyCStruct { unsigned long A; unsigned long B; ...
Below is a simple code snippet: ``` int main() { int *p; p=(int*)malloc(sizeof(int));//allocate m/y 4 1 int printf("P=%p\tQ=%p",p,p+2); } ``` In one sample run, it gave me the output as below: ``` P=0x8210008 Q=0x8210010 ``` Starting address of P is-P=0x8210008,next byte is 0x8210009,next byte is 0x821000A,next b...
Because it's treating it as an integer-element offset from the pointer. You have allocated an array for a single integer. When you ask forp+2it's the same as&p[2]. If you want two bytes from the beginning, you need to cast it tochar*first: ``` char *highWordAddr = (char*)p + 2; ```
Let's say I had a string that contains: ``` {"ticker":{"high":8.976,"low":8.843,"avg":8.9095,"vol":2096.78,"last":8.845,"buy":8.946,"sell":8.843,"server_time":1343686701}} ``` How would I take the numbers and put them into a separate variable? For example : ``` int high = 8.976 int low = 8.843 /* and so on */ ```
Lots of ways. "sscanf" is one alternative. The standard string functions "strstr()", "atof()", etc are another. I'd recommend finding a good JSON-parsing library. For example: http://www.digip.org/jansson/
Given this code: ``` char * pathname; // some string int returnValue = shm_open(pathname, O_CREAT | O_TRUNC | O_RDWR, mode); // create a shared memory object ``` If I do this: note - same pathname!) ``` int returnValue2 = shm_open(pathname, O_CREAT | O_TRUNC | O_RDWR, mode); // create a shared memory object ``` ...
You're just re-opening the existing shared memory segment. O_CREATCreate the shared memory object if it does not exist. (...)O_EXCLIf O_CREAT was also specified, and a shared memory object with the given name already exists, return an error. (From the Linuxman shm_open.) Additionally, fromPOSIX(a bit more expl...
I am using beaglebone, that contains Angstrom distribution. In that there is no build directory, so I have downloaded the kernel source from kernel.org, but the size of that is too much for my SD card (~430 MB). So I thought of removing some unwanted files or directories. Which directories are not necessary to build ...
You can cross-compile kernel on your PC - it would be faster and much more comfortable. All you have to do is to get cross-compiler. As i remember there were some prepared for beagleboard so you can try to use them. Of course you can build it by yourself - there are tools such as crosstool-ng or buildroot, which can ...
When C has the/operator to divide two numbers, what is the purpose of having thediv()library function? Is there any scenario where/can't be used butdiv()can?
From the C99 Rationale document: (7.20.6.2 The div, ldiv, and lldiv functions) Because C89 had implementation-defined semantics for division of signed integers when negative operands were involved, div and ldiv, and lldiv in C99, were invented to provide well-specified semantics for signed integer division and remain...
Is there a way to convert a string to a number and vice versa in C? I know that I can use iostream in C++ and use atoi() or sprintf() etc.. I want to know if there's a way to accomplish this in C without the use of streams. The only solution I see at this point is to create my own function, unless someone knows an alr...
Both of these are C functions: atoiis instdlib.hsprintfis instdio.h And since these are included as part of C, neither require C++ streams.
This is common in functional languages especially with TCO. I was just wondering if it provided any performance benefits besides being easier to write and keep track of. Is it just as fast to access the variables in the struct as it is to access them if they were just normal arguments? Is there any cons to this method...
There is no benefit, because structs are passed by value. Passing multiple arguments one by one will take the same amount of allocations from a running program as the allocation of astruct. Moreover,structmay give you worse results because of padding. Even if you pass yourstructby pointer, you would still need to all...
I'm compiling a DLL which needs to use portaudio. It uses all sorts of windows libraries for sockets and such too, but the linker wouldn't recognize the portaudio library. Then I remembered portaudio uses __cdcel instead of __stdcall. Normally I would just use __cdcel and be done with it, but the DLL I'm compiling nee...
Stupid me! All I have to do is use __cdcel and declare the exported functions as __stdcall!