question
stringlengths
25
894
answer
stringlengths
4
863
i'm trying to run one c executable file using phpexec(). When c contains a simple program likeprint hello. I'm using ``` exec('./print.out') ``` It's working fine. But when I need to pass a argument to my c program I'm using ``` exec('./arugment.out -n 1234') ``` It is not working. Can any body tell me how to pass arugment usingexecto c program.
From taking a look at the php documentation, it appears thatexectreats arguments a bit oddly. You could try doing ``` exec("./argument.out '-n 1234'") ``` to prevent it from mangling them (it normally separates them all on space, which might be what's messing it up).
I'm in the process of documenting some firmware but I'm unsure what the standard is (if there is one) for representing static variable declaration in flowcharts
In the 'classic' flowchart it would just be the rectangle.
What does theexternkeyword mean? I've seen that in front of an function declaration like ``` extern void DoFoo ... ```
externgives a nameexternal linkage. This means that the object or function is accessible through this name from other translation units in the program. For functions, this is the default linkage in any case so its usage (in this context) is usually redundant.
Is an NSInteger big enough for UInt32? Or is it even the same thing?
No becauseNSIntegeris a signed type whileUInt32is unsigned. You should inspect the definitions of these types in Apple's header files to understand what they mean. It's very easy to do so. From an open project in Xcode, select File -> Open Quickly... (Command-Shift-D) and type the type name you are interested in into the text field. It will find the file where it is defined. Or just Command-double click a type in your source code.
I have an CGFloat property and sometimes I get a return value of type Float64 or also of type Float32. Could I store both safely to CGFloat?
From the headers: ``` // CGBase.h typedef float CGFloat; // MacTypes.h typedef float Float32; typedef double Float64; ``` SoCGFloatandFloat32are bothfloats whileFloat64is adoubleso you would lose precision. (Edit to clarify: this is for 32 bit systems such as the iPhone. If you are building for 64 bit,CGFloatis defined as adouble.)
so if I do: ``` dup2(0, backup); // backup stdin dup2(somefile, 0); // somefile has four lines of content fgets(...stdin); // consume one line fgets(....stdin); // consume two lines dup2(backup, 0); // switch stdin back to keyboard ``` I am finding at this point.. stdin still contains the two lines I haven't consumed. Why is that? Because there is just one buffer no matter how many times you redirect? How do I get rid of the two lines left but still remember where I was in the somefile stream when I want to go back to it?
You haven't flushed the stdin buffer. It has buffered up all the lines of somefile even if the underlying file descriptor is restored.
Why canWinMainhave two return types? If I remove it,will report this warning: ``` warning C4007: 'WinMain' : must be '__stdcall' ``` Or I'm reading intWINAPIwrongly? UPDATE I tried these two variants which are said to be the same asWINAPI,none work: ``` int __declspec WinMain int __declspec(stdcall) WinMain ```
WINAPIisn't a return type it's a macro expanding to an implementation specific decoration or attribute for the function. In this instance it specifies the calling convention and is equivalent to__stdcall. Grammatically, WINAPI is roughly (but not exactly) equivalent to a storage class specifier likestatic.
I have assigned the complement value in an unsigned variable. Then why this C program outputs a negative number? ``` #include<stdio.h> #include<conio.h> int main() { unsigned int Value = 4; /* 4 = 0000 0000 0000 0100 */ unsigned int result = 0; result = ~ Value; /* -5 = 1111 1111 1111 1011 */ printf("result = %d", result); /* -5 */ getch(); return 0; } ```
The%dformat specifier instructsprintfto treat the argument as a signed integer. Use%uinstead.
I'm using GCC on Windows 7 (using the TDM's build). I installed MSYS to be able to executeMakeand compile using makefiles. However, it is tedious to every time start up the MSYSBashshell, navigate to the directory of the project and runmake. What I want is to automate this process. I prefer to have a batch file in Windows, or something similar, from which I then invoke the MSYS Bash shell. It should navigate to the directory the batch file resides in and callmake. Is this possible? Can I send commands to MSYS Bash from cmd (like navigation/invokingmake)? Or can I let the MSYS Bash run a "Bash script", which sets the commands to be executed much like batch scripts? PS: This is something similar to Stack Overflow questionExecuting MSYS from cmd.exe with arguments.
Not an MSYS expert, but does something like this work for you: ``` rem Call this something like compile-project.bat c: cd \src\project bash -c "make" ```
As I know, C inline function body should be defined in .h file because it causes an error 'function-name used but never defined" if body defined in .c file. Is this the regular way? Or how to define inline function body in .c file?
Each.cfile is compiled independently into.ooutput. If you define the inline function in a.cfile, other source files cannot see such function, so that cannot be inlined. Therefore the inline function should be in the.hfile to allow the code to be shared.
What's the "DNS_BLOCK_ASSERTIONS" (C compiler flag)?
The NS_BLOCK_ASSERTIONS macro (no "D") suppresses the checks performed by NSAssert. You supply it to the compiler using-DNS_BLOCK_ASSERTIONS(see the comments for an explanation of the "D").
And, if it does, how do you use one? (syntax) Also, why does or why doesn't C support lambda expressions?
No, C has no support for lambda expressions. If you're willing to use C++, Boost has a library that emulates lambdas. Also, C++0x will have built-in support for lambda expressions. There wasn't a huge demand for lambda expression support in C at the time, so the language didn't support it.
I’m buried in multithreading / parallelism documents, trying to figure out how to implement a threading implementation in a programming language I’ve been designing. I’m trying to map a mental model to thepthreads.hlibrary, but I’m having trouble with one thing: I need my interpreter instances to continue to exist after they complete interpretation of aroutine(the language’s closure/function data type), because I want to later assignotherroutines to them for interpretation, thus saving me the thread and interpreter setup/teardown time. This would be fine, except thatpthread_join(3)requires that I callpthread_exit(3)to ‘unblock’ the original thread. How can I block the original thread (when it needs the result of executing theroutine), and then unblock it when interpretation of the child routine is complete?
Use apthread_cond_t; wait on it on one thread and signal or broadcast it in the other.
I'm trying to find a way to multiply an integer value with negative value just with bit shifting. Usually I do this by shifting with the power of 2 which is closest to my factor and just adding / subtracting the rest, e.g.x * 7 = ((x << 3) - x) Let's say I'd want to calculatex * -112. The only way I can imagine is-((x << 7) - (x << 4), so to calculatex * 112and negate it afterwards. Is there a "prettier" way to do this?
Get the compiler to do it, then check the produced assembly.
Is this code correct? ``` char *argv[] = { "foo", "bar", NULL }; ```
It's syntactically correct, and it does create a NULL-terminated array of strings. argv is passed tomainaschar*[](or equivalently,char**), but it's "more correct" to treat string literals as aconst char*rather than achar*. So with this particular example you'd wantconst char *argv[] = {"foo", "bar", NULL }; Maybe you aren't really going to initialise it with "foo", but actually with a modifiable string that you will want to modify via argv. In that casechar*[]is right. This is the kind of thing Charles probably means by saying that whether code is "correct" depends on what you do with it.
I was inspecting the code of a linux application and i saw the #include in one of the code files. I tried looking it up on opengroup.org but i couldn't find it there, this is what the sys directory looks like:http://www.opengroup.org/onlinepubs/000095399/basedefs/sys/. I guess it's not standard header file, but i checked it in my /usr/include/sys and it was there. What does it do and what it is used for ? If you can provide me with some manual for it, i would be grateful. Thanks.
Used in conjunction with ptrace(2) (see PTRACE_PEEKUSER):http://linux.die.net/man/2/ptrace
Will this code: ``` inline int funcA(int a) __attribute__((always_inline)) { return a + 1; } inline int funcB(int b) __attribute__((always_inline)) { return funcA(b + 2); } int main() { return funcB(3); } ``` transformed to code like this?: ``` int main() { return ((3) + 2) + 1; } ``` GCC, ARM (iPhone)
Inlining function calls is not something the language requires compilers to do. It's a quality of implementation issue (QoI). But any of GCC, MSVC and clang will do it. Of course, you have to enable optimization. For instance ``` # clang++ -cc1 -emit-llvm -O2 -o - main.cpp define i32 @main() nounwind readnone { entry: ret i32 6 } ```
All, My company is in the situation where we are using an embedded control system from another company in another country. We do not have the source code or the schematics to this system, and the manufacturer doesn't want to release them, seemingly at any price or under any terms. We are thus stuck with a 6 month turn around to get even a small modification done, and they can basically charge any amount they want. Legal aspects aside, would it be at all feasible to reverse engineer the embedded code back into C? Do any companies exist that could do this for us? Thank you, Fred
There are plenty of companies that will re-implement the embedded control system without reverse engineering the one you are using now, as long as you know that system's requirements.
MASSIVE EDIT: I have a long int variable that I need to convert to a signed 24bit hexadecimal string without the "0x" at the start. The string must be 6 characters followed by a string terminator '\0', so leading zeros need to be added. Examples: [-1 -> FFFFFF] --- [1 -> 000001] --- [71 -> 000047] AnswerThis seems to do the trick: ``` long int number = 37; char string[7]; snprintf (string, 7, "%lX", number); ```
Because you only want six digits, you are probably going to have to do some masking to make sure that the number is as you require. Something like this: ``` sprintf(buffer, "%06lx", (unsigned long)val & 0xFFFFFFUL); ``` Be aware that you are mapping all long integers into a small range of representations. You may want to check the number is in a specific range before printing it (E.g. -2^23 < x < 2^23 - 1)
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed7 years ago.Improve this question What's the simplest C image library for loading and saving? I just want a 2D array to test some algorithms, and built-in functions are not needed.
All these libraries are way too complicated for me. In your place I'd grit my teeth, define an abstraction for a dynamic two-dimensional array, and I'd read and writeplain ASCII PNM format.
I'm trying to take a CGImage and copy its data into a buffer for later processing. The code below is what I have so far, but there's one thing I don't like about it - it's copying the image data twice. Once forCGDataProviderCopyData()and once for the:getBytes:lengthcall on imgData. I haven't been able to find a way to copy the image data directly into my buffer and cut out theCGDataProviderCopyData()step, but there has to be a way...any pointers? (...pun ftw) ``` NSData *imgData = (NSData *)(CGDataProviderCopyData(CGImageGetDataProvider(myCGImageRef))); CGImageRelease(myCGImageRef); // i've got a previously-defined pointer to an available buffer called "mybuff" [imgData getBytes:mybuff length:[imgData length]]; ```
See this answer:Does CGDataProviderCopyData() actually copy the bytes? Or just the pointer? Looks like direct access to the buffer behind a CGDataProvider is restricted to private APIs.
Being a developer born and raised on OO, I was curious to hear how it's possible to avoid global state in a procedural program.
You can also write object-oriented code in C. You don't get all the C++ goodies and it's ugly, and you have to manually pass the this pointer (I've seenselfused for this, in order to make it compatible with C++), but it works. So technically, you don't need global state in pure procedural languages for the very same reasons you don't need it in object-oriented languages. You just have to pass the state around explicitly, rather than implicitly like in OO languages.
``` printf("pointer: %d\n", sizeof(*void)); ``` This line results in a syntax error because of the *. What should I do to get it to work?
You are currently trying to find out the size that is at address void. If you are looking to find the size of a void pointer perhaps try: sizeof(void*) instead. ``` printf("pointer: %zu\n", sizeof(void*)); ``` should do what you want. Use %zu and not %d as the pointer is an unsigned value and not a decimal. Edit: Something else that I just thought of for the first time, is %zu compiler dependent? Do we need to do things differently on 32bit or 64bit architecture?
Often I see a function declared like this: ``` void Feeder(char *buff, ...) ``` what does "..." mean?
It allows a variable number of arguments of unspecified type (likeprintfdoes). You have to access the arguments with theva_start,va_argandva_endfunctions. Seehttp://publications.gbdirect.co.uk/c_book/chapter9/stdarg.htmlorWhere in the C standard variadic functions are described?for more information
HI...i want to write something like this in a file, using fwrite ``` fwrite("name is %s\n",name, 60, fp); ``` but is not working, only write in the file the string. any idea?
Do you meanfprintf? ``` fprintf(fp, "name is %s\n", name); ``` fwriteis designed mainly for writing raw binary data into a file, not text output. For text output it's more natural to usefprintf,fputs,fputcetc. If you really needfwrite, you have to separate thenamepart out, like: ``` fwrite("name is ", 1, 8, fp); fwrite(name, 1, strlen(name), fp); fwrite("\n", 1, 1, fp); ```
I am new at C programming. I thought when you type something like#define Const 5000that the compiler just replaces every instance of Const with 5000 at compile time. Is that wrong? I try doing this in my code and I get a syntax error. Why can't i do this? ``` #define STEPS_PER_REV 12345 ... in some function if(CurrentPosition >= STEPS_PER_REV) { // do some stuff here } ``` The compiler complains about the if statement with a syntax error that gives me no details.
the people in the comments are right. You almost definitely have a semicolon at the end of your #define. This means that your assignment becomes: ``` CURRENT_POSITION = 12345;; ``` (assuming that you HAD a semicolon at the end of the line...) but your if becomes: ``` if(CurrentPosition >= 12345;) ``` which is of course invalid. remember, #defines are NOT C code. They don't need semicolons.
Hi can we hide variables in a structure from outside of the given file using static keyword??? similarly can we hide a global variable from outside of the given file using static keyword? if so please let me know how. Thanks in advance...
Use an opaque data type, where the type is declared in a header, but the struct is defined in the implementation. This means any code which includes the header can pass pointers around to the type, but only the implementation can modify and process data contained by the struct. The typical example isFILEfromstdio.h. For more information seehttp://en.wikipedia.org/wiki/Opaque_pointer
I have a 32 bit long variable, CurrentPosition, that I want to split up into 4, 8bit characters. How would I do that most efficiently in C? I am working with an 8bit MCU, 8051 architectecture. ``` unsigned long CurrentPosition = 7654321; unsigned char CP1 = 0; unsigned char CP2 = 0; unsigned char CP3 = 0; unsigned char CP4 = 0; // What do I do next? ``` Should I just reference the starting address of CurrentPosition with a pointer and then add 8 two that address four times? It is little Endian. ALSO I want CurrentPosition to remain unchanged.
``` CP1 = (CurrentPosition & 0xff000000UL) >> 24; CP2 = (CurrentPosition & 0x00ff0000UL) >> 16; CP3 = (CurrentPosition & 0x0000ff00UL) >> 8; CP4 = (CurrentPosition & 0x000000ffUL) ; ``` You could access the bytes through a pointer as well, ``` unsigned char *p = (unsigned char*)&CurrentPosition; //use p[0],p[1],p[2],p[3] to access the bytes. ```
Given integer valuesxandy, C and C++ both return as the quotientq = x/ythe floor of the floating point equivalent. I'm interested in a method of returning the ceiling instead. For example,ceil(10/5)=2andceil(11/5)=3. The obvious approach involves something like: ``` q = x / y; if (q * y < x) ++q; ``` This requires an extra comparison and multiplication; and other methods I've seen (used in fact) involve casting as afloatordouble. Is there a more direct method that avoids the additional multiplication (or a second division) and branch, and that also avoids casting as a floating point number?
For positive numbers where you want to find the ceiling (q) of x when divided by y. ``` unsigned int x, y, q; ``` To round up ... ``` q = (x + y - 1) / y; ``` or (avoiding overflow in x+y) ``` q = 1 + ((x - 1) / y); // if x != 0 ```
i have a text file where the first number defines the size of the arrays. I know thatcallocormalloccan reserve memory, but how? this code: ``` typedef struct alpha { int* size; char name; int tot; char line[60]; } ALPHA; fgets(line, 60, fp); tot = atoi(line); size = (int*)calloc(name, sizeof(int); ``` Imagine that in the first line of text is the number 10, with this code the size of name will be 10? like name[10]???
Use one of the following: ``` ALPHA* alphas1 = calloc(tot, sizeof(ALPHA)); // or ALPHA* alphas2 = malloc(tot * sizeof(ALPHA)); ``` Those allocate memory fortotof yourALPHAstructures.
I am using C as the programming language. How to ignore the sign when using float/signed int variables? For example if float/signed int f = -40 or +40 The result should be same after a mathematical operation like a+b*f
Useabsfor ints orfabsfor floats. ``` a+b*abs(f) ``` EDIT:It's not clear wether you want -40 to be treated as 40 or vice versa, if you for some reason wan't the latter: ``` a+b*-abs(f) ```
gcc 4.4.1 c89 I have the following code: ``` static enum states { ACTIVE, RUNNING, STOPPED, IDLE }; ``` And I get a warning: ``` useless class storage specifier in empty declaration ``` However, if i remove the static keyword I don't get that warning. I am compiling with the following flags: ``` -Wall -Wextra ``` Many thanks for any suggestions,
You get the message because you're not actuallydeclaring, you're onlydefiningsomething, namely an enumeration named "states". You can later use this definition to declare a variable of that type. That variable may be a static or instance variable, but the definition doesn't need (and shouldn't have) the storage specifier attached to it.
In some library I'm using (written in C) its ``` StorePGM(image, width, height, filename) char *image; int width, height; char *filename; { // something something } ``` All functions are defined this way. I never seen such function definitions in my life. They seem to be valid to MSVC but when I compile it as C++ it gives errors. What is it? some kind of old version C?
Yes. K&R, pre-standard C. Avoid using it.
I've got some code executing in a while(fscanf != EOF) loop. However, even when fscanf has finished executing, I need to keep running that code until some conditions are met. I mean I guess I could copy/paste the code to outside the while(fscanf) loop, and only use global variables, but that seems messy. Surely someone has encountered something like this before and has a cleaner solution.
Couldn't you just modify thewhilecondition to account for these additional conditions? ``` while(fscanf(...) != EOF || !(some_other_conditions_met)) ```
Given a string consisting of a single character followed by a number (one or two digits), I would like to split it into a character and an integer. What is the easiest way to accomplish this? My thoughts so far: I can easily grab the character like so: ``` string mystring = "A10"; char mychar = mystring[0]; ``` The hard part seems to be grabbing the one or two digit number that follows.
``` #include <sstream> char c; int i; std::istringstream ss("A10"); ss >> c >> i;//First reads char, then number. //Number can have any number of digits. //So your J1 or G7 will work either. ```
MASSIVE EDIT: I have a long int variable that I need to convert to a signed 24bit hexadecimal string without the "0x" at the start. The string must be 6 characters followed by a string terminator '\0', so leading zeros need to be added. Examples: [-1 -> FFFFFF] --- [1 -> 000001] --- [71 -> 000047] AnswerThis seems to do the trick: ``` long int number = 37; char string[7]; snprintf (string, 7, "%lX", number); ```
Because you only want six digits, you are probably going to have to do some masking to make sure that the number is as you require. Something like this: ``` sprintf(buffer, "%06lx", (unsigned long)val & 0xFFFFFFUL); ``` Be aware that you are mapping all long integers into a small range of representations. You may want to check the number is in a specific range before printing it (E.g. -2^23 < x < 2^23 - 1)
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed7 years ago.Improve this question What's the simplest C image library for loading and saving? I just want a 2D array to test some algorithms, and built-in functions are not needed.
All these libraries are way too complicated for me. In your place I'd grit my teeth, define an abstraction for a dynamic two-dimensional array, and I'd read and writeplain ASCII PNM format.
I'm trying to take a CGImage and copy its data into a buffer for later processing. The code below is what I have so far, but there's one thing I don't like about it - it's copying the image data twice. Once forCGDataProviderCopyData()and once for the:getBytes:lengthcall on imgData. I haven't been able to find a way to copy the image data directly into my buffer and cut out theCGDataProviderCopyData()step, but there has to be a way...any pointers? (...pun ftw) ``` NSData *imgData = (NSData *)(CGDataProviderCopyData(CGImageGetDataProvider(myCGImageRef))); CGImageRelease(myCGImageRef); // i've got a previously-defined pointer to an available buffer called "mybuff" [imgData getBytes:mybuff length:[imgData length]]; ```
See this answer:Does CGDataProviderCopyData() actually copy the bytes? Or just the pointer? Looks like direct access to the buffer behind a CGDataProvider is restricted to private APIs.
Being a developer born and raised on OO, I was curious to hear how it's possible to avoid global state in a procedural program.
You can also write object-oriented code in C. You don't get all the C++ goodies and it's ugly, and you have to manually pass the this pointer (I've seenselfused for this, in order to make it compatible with C++), but it works. So technically, you don't need global state in pure procedural languages for the very same reasons you don't need it in object-oriented languages. You just have to pass the state around explicitly, rather than implicitly like in OO languages.
``` printf("pointer: %d\n", sizeof(*void)); ``` This line results in a syntax error because of the *. What should I do to get it to work?
You are currently trying to find out the size that is at address void. If you are looking to find the size of a void pointer perhaps try: sizeof(void*) instead. ``` printf("pointer: %zu\n", sizeof(void*)); ``` should do what you want. Use %zu and not %d as the pointer is an unsigned value and not a decimal. Edit: Something else that I just thought of for the first time, is %zu compiler dependent? Do we need to do things differently on 32bit or 64bit architecture?
Often I see a function declared like this: ``` void Feeder(char *buff, ...) ``` what does "..." mean?
It allows a variable number of arguments of unspecified type (likeprintfdoes). You have to access the arguments with theva_start,va_argandva_endfunctions. Seehttp://publications.gbdirect.co.uk/c_book/chapter9/stdarg.htmlorWhere in the C standard variadic functions are described?for more information
I have a question: How to compile a static library in Linux withgcc, i.e. I need to compile my source code into a file named out.a. Is it sufficient to simply compile with the commandgcc -o out.a out.c? I'm not quite familiar withgcc, hope anyone can give me a hand.
SeeCreating a shared and static library with the gnu compiler [gcc] ``` gcc -c -o out.o out.c ``` -cmeans to create an intermediary object file, rather than an executable. ``` ar rcs libout.a out.o ``` This creates the static library.rmeans to insert with replacement,cmeans to create a new archive, andsmeans to write an index. As always, see theman pagefor more info.
Many places I saw that we can use startupinfoex structure in CreateProcess function. But when I checked the signature is only allowing startupinfo structure. Can anybody please give a snippet how startupinfoex can be used with createprocess function. Thanks in advance....
You need to cast theSTARTUPINFOEX*to aSTARTUPINFO*. Be sure to pass theEXTENDED_STARTUPINFO_PRESENTflag todwCreationFlagsand set theStartupInfo.cbmember tosizeof(STARTUPINFOEX).
I have the following variables: ``` char *p; int l=65; ``` Why do the following casts fail? ``` (int *)p=&l; ``` and: ``` p=&((char) l); ```
The result of type conversion is always anrvalue. Rvalue cannot be assigned to, which is why your first expression doesn't compile. Rvalue cannot be taken address of, which is why your second expression doesn't compile. In order to perform the correct type conversion, you have to to it as follows ``` p = (char *) &l; ``` This is the proper way to do what you tried to do in your second expression. It convertsint *pointer tochar *type. Your first expression is beyond repair. You can do ``` *(int **) &p = &l; ``` but what it does in the end is not really aconversion, but ratherreinterpretationof the memory occupied bychar *pointer asint *pointer. It is an ugly illegal hack that most of the time has very little practical value.
One aspect where C shows its age is the encapsulation of code. Many modern languages has classes, namespaces, packages... a much more convenient to organize code than just a simple "include". Since C is still the main language for many huge projects. How do you to overcome its limitations? I suppose that one main factor should belots of discipline. I would like to know what you do to handle large quantity of C code, which authors or books you can recommend.
Separate the code into functional units.Build those units of code into individual libraries.Use hidden symbols within libraries to reduce namespace conflicts. Think of open source code. There is a huge amount of C code in the Linux kernel, the GNU C library, the X Window system and the Gnome desktop project. Yet, it all works together. This is because most of the code does not see any of the other code. It only communicates by well-defined interfaces. Do the same in any large project.
gcc 4.4.1 c89 I have the following code snippet: ``` #include <stdlib.h> #include <stdio.h> char *buffer = malloc(10240); /* Check for memory error */ if(!buffer) { fprintf(stderr, "Memory error\n"); return 1; } printf("sizeof(buffer) [ %d ]\n", sizeof(buffer)); ``` However, the sizeof(buffer) always prints 4. I know that a char* is only 4 bytes. However, I have allocated the memory for 10kb. So shouldn't the size be 10240? I am wondering am I thinking right here? Many thanks for any suggestions,
You are asking for the size of achar*which is 4 indeed, not the size of the buffer. Thesizeofoperator can not return the size of a dynamically allocated buffer, only the size of static types and structs known at compile time.
Please take a look at this piece of code. I'm allocating one byte for the first variable and another byte for the second one. However, it seems like the compiler allocates more (or I'm missing something). The program outputs both strings, even though their length is more the one byte. ``` void main() { char* some1 = malloc(1); sprintf(some1,"cool"); char* some2 = malloc(1); sprintf(some2,"face"); printf("%s ",some1); printf("%s\n",some2); } ``` Please, could anyone spot some light on what's going on when memory is being allocated.
You allocate one byte, then overrun the bounds of your allocated memory.sprintfdoes no bounds checking (its friend,snprintfdoes bounds checking). When you overrun your allocated memory, you get undefined behavior, so anything can happen. In your case, it appears to work correctly. Your program could also crash, or anything else might happen.
Is there a standard C library function to escape C-strings? For example, if I had the C string: ``` char example[] = "first line\nsecond line: \"inner quotes\""; ``` And I wanted to print ``` "first line\nsecond line: \"inner quotes\"" ``` Is there a library function that will do that transformation for me? Rolling my own just seems a little silly. Bonus points if I can give it a length to escape (so it stops before or beyond the\0).
If you were writing GPL stuff you might usehttp://git.savannah.gnu.org/gitweb/?p=gnulib.git;a=blob;f=lib/quotearg.c;hb=HEAD
Is there a way to concatenate keywords in a macro and getC to behave in a more dynamic fashion as in: ``` #define macro(fun,ction,var,iable) function(variable) ``` I know this kind of thing exists in other languages.
You can use ## to concatinate names in macros fun##ction ...
I have a property defined in a class like so: ``` @interface myClass UIImageView *drawImage[4]; ... @property (nonatomic, retain) UIImageView **drawImage; ... @synthesize drawImage; // This fails to compile ``` I have found similar questions on StackOverflow and elsewhere, but none that really address this issue. What is the most Objective-C kosher way to do this?
You can't; you have to change thatretaintoassignand handle memory management yourself; as you can't send-[retain]to anUIImageView **(as it isn't an object.) That is to say; you can't actually use@synthesizeas that would lead to epic memory leaks withassignand doesn't work withretainorcopy; what you need to do is to implement-drawImageand-setDrawImage:and write some actually accessor code. But don't do that. Use anNSArray.
I have a text file with machine code in this form:B2 0A 05B2 1A 01B3 08 00 17B2 09 18 where an instruction has this format:OP Mode Operand Note: Operand could be 1 or 2 bytes. Where:(example)OP = B2Mode = 0AOperand = 05 How can I read the bytes in a variable? As shown in the above example. When i read the file I get individual characters. I have an array of pointers where I read individual line, but still cannot solve the problem of reading a byte. Any ideas,suggestions. I hope I am not confusing anyone here. Thank you.
Consider usingfscanf. You can use the%xformat specifier to read hexadecimal integers.
Whengetoptorgetopt_longencounters an illegal option, it stores the offending option character inoptopt. When the illegal option is alongoption, where can I find out what the option was? And does anything meaningful get stored inoptoptthen? I've setopterr = 0to suppress the automatically printed error message. I want to create my own message that I can print or log where I'd like, but I want to include the name of the unrecognized option.
The closest I can find is that if you get aBADCHreturn theargvitem that caused it is inargv[optind-1]. Seems like there should be a better way to find the problem argument.
There aresome new integer typesin the Windows API to support Win64. They haven't always been supported; e.g.they aren't present in MSVC6. How can I write an#ifcondition to detect if these types are supported by<windows.h>? (My code needs to compile under many different versions of Microsoft Visual C++, including MSVC6. So I need to provide my own definitions of these types, with an#ifto disable them in newer compilers). (For searchers, the full list of types is: DWORD_PTR, INT_PTR, LONG_PTR, UINT_PTR, ULONG_PTR)
The macroMSC_VERis a value that is within the range[1200, 1300)for MSVC 6. So you can use#if MSC_VER>=1200 && MSC_VER<1300. EDIT: As Anders said, this is not really that valid of a test beyond "is my compiler MSVC 6". However, you can also use: ``` #if defined(MAXULONG_PTR) ``` SinceDWORD_PTRis a value type, it has a maximum value defined for it inbasetsd.h.
I checked out the microsoft documents. it shows how to create a static library upon creation of the project. but not necessarily on how to convert a previously made project, into a static library. So my question is, where do I go to turn my previously made project, into a static lib. so I can include it in my other projects
Project | Properties -> Configuration Properties -> General -> Configuration Type (Static Library).
I would like to have a string (char*) parsed into a tm struct in C. Is there any built-in function to do that? I am referring to ANSI C in C99 Standard.
There is a function calledstrptime()available in time.h in UNIX derived systems. It is used similar toscanf(). You could just use ascanf()call if you know what format the date is going to be in. I.E. ``` char *dateString = "2008-12-10"; struct tm * parsedTime; int year, month, day; // ex: 2009-10-29 if(sscanf(dateString, "%d-%d-%d", &year, &month, &day) != EOF){ time_t rawTime; time(&rawTime); parsedTime = localtime(&rawTime); // tm_year is years since 1900 parsedTime->tm_year = year - 1900; // tm_months is months since january parsedTime->tm_mon = month - 1; parsedTime->tm_mday = day; } ``` Other than that, I'm not aware of any C99char *tostruct tmfunctions.
I've been reading a few gaming books. And they always prefer to create the engine as a static library over dynamic link. I am new to c++ so I am not highly knowledge when it comes to static libraries and dynamic link libraries. All I know is static libraries increase the size of your program, where DLL link libraries are loaded as you need them within your program. [edit] I've played games where it almost seemed they used DLL's to load in sound, lighting, and what not all individually. as the level was loading up. cause you don't necessarily need that when your at the game menu.
Dynamic link libraries need to be position independent; this can cause performance inefficiencies on some processor architectures. Static libraries can be optimized when included in your program, e.g., by stripping dead code. This can improve cache performance.
I want to do the inverse ofthis question. I am embedding a file into an executable as an array, and I would later like to extract the embedded file from the executable. It seems like objcopy might be useful here but I haven't figured out the proper incantation yet. (Edit: clarify question, I somehow removed the crux of it in editing originally...)
If you place the embedded file within its own section you can use objcopy to extract that section into a raw output file, I think. Look into gcc's__attribute__((section("embedded_file") ))Or if you are getting the file into the exe some other way using the linker you should be able to get it into another section another way, but I'm not familiar with doing that.
I'm looking for the C grammar in GCC source code, more specifically for the grammar in the yacc/bison form.
Found the C grammar in Yacc specification in the GCC version 3.3 in the file "c-parse.y"
I'm having a weird problem i'm trying to read a string from a console with scanf() like this ``` scanf("%[^\n]",string1); ``` but it doesnt read anything. it just skips the entire scanf. I'm trying it in gcc compiler
Trying to usescanfto read strings with spaces can bring unnecessary problems of buffer overflow and stray newlines staying in the input buffer to be read later.gets()is often suggested as a solution to this, however, From the manpage: Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead. So instead of usinggets, usefgetswith the STDIN stream to read strings from the keyboard
Please tell me how to convert bytes to NSInteger/int in objective-c in iPhone programming?
What do you mean by "Bytes"? If you want convert single byte representing integer value to int (or NSInteger) type, just use "=": ``` Byte b = 123; NSInteger x; x = b; ``` as Byte (the same asunsigned char- 1 byte unsigned integer) and NSInteger (the same asint- 4 bytes signed integer) are both of simple integer types and can be converted automatically. Your should read more about "c data types" and "conversion rules". for examplehttp://www.exforsys.com/tutorials/c-language/c-programming-language-data-types.html If you want to convert several bytes storing some value to int, then convertion depends on structure of these data: how many bytes per value, signed or unsigned.
I'm trying to read a return delimited file. full of phrases. I'm trying to put each phrase into a string. The problem is that when I try to read the file with ``` fscanf(file,"%50s\n",string); ``` the string only contains one word. when it bumps with a space it stops reading the string
``` fscanf(file,"%50[^\n]\n",string); ``` Every character except\nwill be consumed by[^\n]Maximum 0f 50 chars will be consumed (make sure string has space for 51 atleast)..\n",stringthis makes sure that\nis also consumed so that the next call does not just return a null string.
I'm having trouble passing a structure array as a parameter of a function ``` struct Estructure{ int a; int b; }; ``` and a function ``` Begining(Estructure &s1[]) { //modifi the estructure s1 }; ``` and the main would be something like this ``` int main() { Estructure m[200]; Begining(m); }; ``` is this valid?
No, you need to typedef your struct, and you should pass the array to it; pass by reference does not work in C. ``` typedef struct Estructure{ int a; int b; } Estructure_s; Begining(Estructure_s s1[]) { //modify the estructure s1 } int main() { Estructure_s m[200]; Begining(m); } ``` Alternatively: ``` struct Estructure{ int a; int b; }; Begining(struct Estructure *s1) { //modify the estructure s1 } int main() { struct Estructure m[200]; Begining(m); } ```
I'm trying to convert some c code to assmebly, and I need some help. ``` char encode(char plain){ __asm{ mov eax, plain add eax, 2 ret } //C code /* char code; code = plain+2; return code;*/ } ``` First problem is that visual studio complains that the register size doesn't match, i.e. eax is too small/large for char. I was under the impression that they were both DWORDs. Also, if I leave the variable in eax, and ret in assembly, it'll actually return that variable, right?
Remember, you can always look at the assembler output of a c file for hints on how to translate something. It's usually a single flag you have to enable.
I've been reading a few gaming books. And they always prefer to create the engine as a static library over dynamic link. I am new to c++ so I am not highly knowledge when it comes to static libraries and dynamic link libraries. All I know is static libraries increase the size of your program, where DLL link libraries are loaded as you need them within your program. [edit] I've played games where it almost seemed they used DLL's to load in sound, lighting, and what not all individually. as the level was loading up. cause you don't necessarily need that when your at the game menu.
Dynamic link libraries need to be position independent; this can cause performance inefficiencies on some processor architectures. Static libraries can be optimized when included in your program, e.g., by stripping dead code. This can improve cache performance.
I want to do the inverse ofthis question. I am embedding a file into an executable as an array, and I would later like to extract the embedded file from the executable. It seems like objcopy might be useful here but I haven't figured out the proper incantation yet. (Edit: clarify question, I somehow removed the crux of it in editing originally...)
If you place the embedded file within its own section you can use objcopy to extract that section into a raw output file, I think. Look into gcc's__attribute__((section("embedded_file") ))Or if you are getting the file into the exe some other way using the linker you should be able to get it into another section another way, but I'm not familiar with doing that.
I'm looking for the C grammar in GCC source code, more specifically for the grammar in the yacc/bison form.
Found the C grammar in Yacc specification in the GCC version 3.3 in the file "c-parse.y"
I'm having a weird problem i'm trying to read a string from a console with scanf() like this ``` scanf("%[^\n]",string1); ``` but it doesnt read anything. it just skips the entire scanf. I'm trying it in gcc compiler
Trying to usescanfto read strings with spaces can bring unnecessary problems of buffer overflow and stray newlines staying in the input buffer to be read later.gets()is often suggested as a solution to this, however, From the manpage: Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead. So instead of usinggets, usefgetswith the STDIN stream to read strings from the keyboard
Please tell me how to convert bytes to NSInteger/int in objective-c in iPhone programming?
What do you mean by "Bytes"? If you want convert single byte representing integer value to int (or NSInteger) type, just use "=": ``` Byte b = 123; NSInteger x; x = b; ``` as Byte (the same asunsigned char- 1 byte unsigned integer) and NSInteger (the same asint- 4 bytes signed integer) are both of simple integer types and can be converted automatically. Your should read more about "c data types" and "conversion rules". for examplehttp://www.exforsys.com/tutorials/c-language/c-programming-language-data-types.html If you want to convert several bytes storing some value to int, then convertion depends on structure of these data: how many bytes per value, signed or unsigned.
I'm trying to read a return delimited file. full of phrases. I'm trying to put each phrase into a string. The problem is that when I try to read the file with ``` fscanf(file,"%50s\n",string); ``` the string only contains one word. when it bumps with a space it stops reading the string
``` fscanf(file,"%50[^\n]\n",string); ``` Every character except\nwill be consumed by[^\n]Maximum 0f 50 chars will be consumed (make sure string has space for 51 atleast)..\n",stringthis makes sure that\nis also consumed so that the next call does not just return a null string.
I'm having trouble passing a structure array as a parameter of a function ``` struct Estructure{ int a; int b; }; ``` and a function ``` Begining(Estructure &s1[]) { //modifi the estructure s1 }; ``` and the main would be something like this ``` int main() { Estructure m[200]; Begining(m); }; ``` is this valid?
No, you need to typedef your struct, and you should pass the array to it; pass by reference does not work in C. ``` typedef struct Estructure{ int a; int b; } Estructure_s; Begining(Estructure_s s1[]) { //modify the estructure s1 } int main() { Estructure_s m[200]; Begining(m); } ``` Alternatively: ``` struct Estructure{ int a; int b; }; Begining(struct Estructure *s1) { //modify the estructure s1 } int main() { struct Estructure m[200]; Begining(m); } ```
I'm trying to convert some c code to assmebly, and I need some help. ``` char encode(char plain){ __asm{ mov eax, plain add eax, 2 ret } //C code /* char code; code = plain+2; return code;*/ } ``` First problem is that visual studio complains that the register size doesn't match, i.e. eax is too small/large for char. I was under the impression that they were both DWORDs. Also, if I leave the variable in eax, and ret in assembly, it'll actually return that variable, right?
Remember, you can always look at the assembler output of a c file for hints on how to translate something. It's usually a single flag you have to enable.
Looking at the information under the heading "Precision can be omitted or be any of:". The example:printf("%.*s", 3, "abcdef");works, outputting:abc(truncating the rest of the string.) Now, I would like to have a string with multiple parameters formatted (truncated): ``` printf("%.*s, %.*s", 3, 3, "abcdef", "xyz123"); ``` but the program crashes. What is the correct syntax? Thank You.
Maybe you should change order? ``` printf("%.*s, %.*s", 3, "abcdef", 3, "xyz123"); ``` By the way you can hardcode precision if you don't need it as a variable: ``` printf("%.3s, %.3s", "abcdef", "xyz123"); ``` (Stephen Canon kindly corrected the typo)
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 Is there any tool to show diagrammatic rep of flow of program if we input a C file? Thanks.
For an open source workflow to do this, useGNU cflowto generate a call graph in text format. ThenCflow2vcgcan convert the output into an intermediate graph format thatGraphvizcan use to generate an image for you.
``` #include<stdio.h> #include<math.h> int main () { FILE *fp; fp=fopen("output","w"); float t,y=0,x=0,e=5,f=1,w=1; for (t=0;t<10;t=t+0.01) { if( y==inf && y== nan) break; fprintf(fp,"%lf\t%lf\n",y,x); y = y + ((e*(1 - x*x)*y) - x + f*cos(w*t))*t; x = x + y*t; } return 0; } ``` Why is the ouput giving infinite and NAN values?
Your calculation is blowing up. Just look at the values printed out for x and y and you will see they start to get very large and then turn info inf. Because your conditional is wrong, you wind up using inf in the calculation which turns into nan.
I'm writing transpose function for 8x16bit vectors with SSE2 intrinsics. Since there are 8 arguments for that function (a matrix of 8x8x16bit size), I can't do anything but pass them by reference. Will that be optimized by the compiler (I mean, will these __m128i objects be passed in registers instead of stack)? Code snippet: ``` inline void transpose (__m128i &a0, __m128i &a1, __m128i &a2, __m128i &a3, __m128i &a4, __m128i &a5, __m128i &a6, __m128i &a7) { .... } ```
Who can say? Why not compile it and look at the disassembly? That is the only way to be sure.
For example: ``` #define FOO(x) (printf(x)) ``` and ``` #define FOO(x) {printf(x)} ``` It seems that both are viable for preprocessing, but which is better?
If you're treating the macro as an expression, use the()form. If you're treating it as a command (andneveras an expression) then use the{}form. Or rather, use thedo{}while(0)form as that has fewer substitution hazards when used near keywords likeif: ``` #define FOO(x) do { \ printf(x); \ } while(0) ```
I need a powerful HTML parser and manipulator for Objective-C/C, like HTML Agility Pack. Can anyone tell me some optimal solution? One solution is libxml2, but it seams is not the best. Thanks in advance!
On MacOS X,NSXMLDocumentis a good solution (but you want iPhone). Two packages that you should look at are:TouchXMLandKissXML. See alsoiPhone Development - XMLParser vs. libxml2 vs. TouchXML.
In the many search functions of C (bsearch comes to mind) if a result is found, a pointer to the spot in the array is returned. How can I convert this pointer to the index in the array that was searched (using pointer arithmetic, i assume).
``` ptrdiff_t index = pointer_found - array_name; ```
Although it runs correctly, the following results in the aforementioned compiler warning: ``` return ((item - (my->items))/(my->itemSize)); ``` 'item' is a 'void *'; 'my->items' is a 'void *'; 'my->itemSize' is an 'int' Casting 'item' and 'my->items' as an 'int *' caused the program to run improperly. What is the best way to remove the warning?
Additions and subtractions with pointers work with the size of the pointed type: ``` int* foo = 0x1000; foo++; // foo is now 0x1004 because sizeof(int) is 4 ``` Semantically speaking, the size ofvoidshould be zero, since it doesn't represent anything. For this reason, pointer arithmetic onvoidpointers should be illegal. However, for several reasons,sizeof(void)returns 1, and arithmetic works as if it was acharpointer. Since it's semantically incorrect, you do, however, get a warning. To suppress the warning, usecharpointers.
this may be a silly question, but I want to calculate the complexity of one of my algorithms, and I am not sure what complexity to consider for thememmove()function. Can you please help / explain ? ``` void * memmove ( void * destination, const void * source, size_t num ); ``` So is the complexity O(num) or O(1). I suppose it's O(num), but I am not sure as I lack for now the understanding of what's going on under the hood.
Since the running time ofmemmoveincreases in direct proportionality with the number of bytes it is required to move, it is O(n).
Recently I've been trying to debug some low-level work and I could not find thecrt0.Sfor the compiler (avr-gcc) but I did find acrt1.S(and the same with the corresponding.ofiles). What is the difference between these two files? Iscrt1something completely different or what? They both seem to have to do with something for 'bootstrapping' (setting upstack frameand such), but why the distinction?
Both crt0/crt1 do the same thing, basically do what is needed before calling main() (like initializing stack, setting irqs, etc.). You should link with one or the other but not both. They are not really libraries but really inline assembly code. As far as I understand, crt comes in two "flavors" crt1is used on systems that support constructors and destructors (functions called before and after main and exit). In this case main is treated like a normal function call.crt0is used on systems that do not support constructors/destructors.
When debugging a link error (undefined reference to _dso_handle) using the Android x86 toolchain, I noticed it's statically linkingcrtbegin_dynamic.o. What is the purpose of this file? There is another similarcrtbegin.oin the toolchain install directory that contains the missing symbol (_dso_handle). What is the difference between crtbegin.o and crtbegin_dynamic.o?
C++ has global constructors and destructors. crtbegin.o and crtend.o deal with calling those constructors and destructors. The variants of crtbegin.o such as crtbeginS.o do the same thing for other types of executables such as static executables and shared libraries.
In the C language, how do I convertunsigned longvalue to a string (char *) and keep my source code portable or just recompile it to work on other platform (without rewriting code? For example, if I havesprintf(buffer, format, value), how do I determine the size of buffer with platform-independent manner?
``` const int n = snprintf(NULL, 0, "%lu", ulong_value); assert(n > 0); char buf[n+1]; int c = snprintf(buf, n+1, "%lu", ulong_value); assert(buf[n] == '\0'); assert(c == n); ```
Is there an easy way (like a free program) that can covert c/c++ code to x86 assembly? I know that any c compiler does something very similar and that I can just compile the c code and then disassemble the complied executable, but that's kind of an overkill, all I want is to convert a few lines of code. Does anyone know of some program that can do that? EDIT: I know that GCC compiler does that but it's AT&T syntax and I'm looking for the Intel syntax (not sure if it's called intel syntax or not). The AT&T syntax looks a bit like gibberish to me and some commands use operands in reverse order and not how I'm used to and it can get really confusing.
GCC can output Intel syntax assembly using the following command line: ``` gcc -S input.c -o output.asm -masm=intel ```
Thewritefunction does not print a floating point number in the following code: ``` #include <unistd.h> int main(){ float f = 4.5; write(1,&f,sizeof float); return 0; } ``` This results in: ``` �@ ``` Whereas: ``` int main(){ char *c = "Hello world"; write (1,c,strlen(c)+1); return 0; } ``` PrintsHello worldas expected. What am I missing? Thanks in advance.
writeoutputs the bytes in the binary representation of the floating-point number. Those bytes do not even always correspond to readable characters, let alone to the textual representation of the number itself. I guess you want to convert the number to human-readable text. That's whatprintfis for: ``` printf("%f", f); ```
Is there an efficient way to get the least non-negative residue modulo n, where n is positive, in C? This is quite easy if the number is non-negative, then it's just a % n (where a is the non-negative integer). However when a is negative, it appears the behaviour, in C89, is implementation defined (thanks kennyTM). I.e. -2 % 11 = -2 or 9.
You could simply check if the result is negative and then act accordingly: ``` int mod(int n, int m) { int r = n % m; if (r < 0) return r + m; else return r; } ``` Or, without if-then-else and as a single expression: ``` r = ((n % m) + m) % m; ```
Is there any way in C/C++ to stop a backtracking algorithm after finding the first solution without exiting the program. I want my function to immediately exit the function,not to quit every level of recurrsion one by one stating return.
A quick and dirty way is to throw an Exception and catch it at the base level (around right now a lot of people will scream to only use Exceptions for Errors, I argue, founding a solution is an exceptional event since not finding one is the norm)
``` #include<stdio.h> #define a(x) (x * x) int main() { int i = 3, j; j = a(i + 1); printf("%d", j); return 0; } ``` I want to know why the program is not giving the output16. (I'm getting the output7.) I understood the point very much but if the program is like this: ``` #include<stdio.h> #define a(x) (x * x) int main() { int i = 3, j, k; j = a(i++); k = a(++i); printf("%d\n%d", j, k); return 0; } ``` Then why does the above program give the following output: ``` 9 49 ```
Because you made a bad macro: ``` a(i + 1) ``` expands to ``` i + 1 * i + 1 ``` which is equivalent to ``` i + i + 1 ``` or ``` 2 * i + 1 ``` Use parenthesis: ``` #define a(x) ((x) * (x)) ``` And then you'll get it to expand to ``` (i + 1) * (i + 1) ``` which does what you want.
How do I execute another program from within a C program in Windows 32 - in a similar way as Perl'ssystem()function or Python's sub-process module - such asDEL,REG, or other cmd.exe programs?
C does have asystemfunction in its standard library, see e.g. thewikipediaentry about it.
This is a simple problem, but I can't see it: ``` char *s = "f 8.649292" ; double d ; sscanf( s, "f %f", &d ) ; printf( "d is %f\n", d ) ; ``` Why isdnot containing the double value8.649292?
Oh wait, nevermind. d needs to be afloat. And to make it work you could use%lffor a double ``` char *s = "f 8.649292 " ; double d ; sscanf( s, "f %lf", &d ) ; printf( "d is %lf\n", d ) ; ```
I made a program to connect to a device via Bluetooth and send the data to the web using pure C in gcc. I won't be able to implement any GUI portion in the code right now but I need to deploy it to test users for testing. I want to have the executable with an icon so that a user can click on the executable and the program starts in the terminal. How do I add an icon to the executable and start the program in the terminal? Sorry I failed to mention before that its in Ubuntu Linux
This document explains how to add your program to the programs menu:http://standards.freedesktop.org/menu-spec/latest/.
i have a small program that uses 32bit object file, and i wish to run it under dos operating system. now, after searching i foundDJGPP.is there a way to use DJGPP to compile my program to 16Bit dos executable format?thanks in advance
Take a look atthisrelated Stack Overflow question. It might help.
This question already has answers here:Closed13 years ago. Possible Duplicate:Uses for multiple levels of pointer dereferences? I have used functions with doubly dereferenced pointers (**var) to return values. However, I was recently asked a question to figure out a use-case where a triple dereferencing (***var) may be needed. I couldn't think of any practical scenario. Does anyone have any experience here?
Three dimensional arrays.
I have the simple function below which swap two characters of an array of characters (s). However, I am getting a "Unhandled exception at 0x01151cd7 in Bla.exe: 0xC0000005: Access violation writing location 0x011557a4." error. The two indexes (left and right) are within the limit of the array. What am I doing wrong? ``` void swap(char* s, int left, int right) { char tmp = s[left]; s[left] = s[right]; s[right] = tmp; } swap("ABC", 0, 1); ``` I am using VS2010 with unmanaged C/C++. Thanks!
You can't modify a string literal. instead try this: ``` char s[] = "ABC" swap(s, 0, 1); printf("%s\n", s); ```
Could somebody tell me what is the proper way to convert a NSString* to an ANTLR3 string (used in C) ? EDIT: this seems to work ``` char buf[255]; if ( YES == [myNSString getCString:buf maxLength:255 encoding:NSStringEncodingConversionAllowLossy] ) { pANTLR3_UINT8 theExpression = (pANTLR3_UINT8*)buf; ... ```
Assuming that you want the complete string without loss, you can use the following code: ``` NSString *myString = ...; NSUInteger len = [myString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; char *buf = malloc(len + 1); if ([myString getCString:buf maxLength:(len + 1) encoding:NSUTF8StringEncoding]) { // pANTLR3_UINT8 is equivalent to ANTLR3_UINT8* pANTLR3_UINT8 theExpression = (pANTLR3_UINT8) buf; } free(buf); ``` Of course you can use another encoding if character loss is not important.
In gcc I can do compile-time warnings like this: ``` #if !defined(_SOME_FEATURE_) #warning _SOME_FEATURE_ not defined-- be careful! #endif ``` But in Visual Studio this doesn't work. Is there an alternative syntax for #warning?
About the closest equivalent would be#pragma message, or possibly#error(the latter stops compilation, the former just prints out the specified error message).
For example when we call say, a recursive function, the successive calls are stored in the stack. However, due to an error if it goes on infinitely the error is 'Segmentation fault' (as seen on GCC). Shouldn't it have been 'stack-overflow'? What then is the basic difference between the two? Btw, an explanation would be more helpful than wikipedia links (gone through that, but no answer to specific query).
Stack overflow is [a] cause, segmentation fault is the result. At least on x86 and ARM, the "stack" is a piece of memory reserved for placing local variables and return addresses of function calls. When the stack is exhausted, the memory outside of the reserved area will be accessed. But the app did not ask the kernel for this memory, thus a SegFault will be generated for memory protection.
I have set up the following struct: ``` typedef struct _thread_node_t { pthread_t thread; struct thread_node_t *next; } thread_node_t; ``` ... and then I have defined: ``` // create thread to for incoming connection thread_node_t *thread_node = (thread_node_t*) malloc(sizeof(thread_node_t)); pthread_create(&(thread_node->thread), NULL, client_thread, &csFD); thread_node->next = thread_arr; // assignment from incompatible pointer type thread_arr = thread_node; ``` where thread_arr isthread_node_t *thread_arr = NULL; I don't understand why the compiler is complaining. Maybe I'm misunderstanding something.
Shouldn'tstruct thread_node_t *next;bestruct _thread_node_t *next; Also, do away with theexplicitcast. ``` thread_node_t *thread_node = (thread_node_t*) malloc(sizeof(thread_node_t)); ``` to ``` thread_node_t *thread_node = malloc(sizeof(thread_node_t)); ```
I'm doing some networking programming for Windows right now envolving the HTTP protocol. Is it possible to handle prosies at socket level? And SSL proxies? If not, does Windows provide something at a higher level to handle them? I wouldn't like to use a third party library, but if there's no other way to go I would reconsider it. A pointer to an example would also be great. Thank you very much.
You can use for example Windows Internet (WinINet) APIhttp://msdn.microsoft.com/en-us/library/aa383630%28v=VS.85%29.aspxor Windows HTTP Services (WinHTTP)http://msdn.microsoft.com/en-us/library/aa384273%28v=VS.85%29.aspxif are interesting for HTTP protocol only. Advantage of using this API is: They are Microsoft standard and will be used in a lot of Microsoft productsThey are part of operation system and exists on any WindowsYou can find a lot of examples for almost every subject What kind of working with proxies do you plan?
Situation: I am writing a program in C that maintains a number of threads. Once a thread ends, a new one is created. Each thread forks - the child runs a PHP process via exec() and the parent waits for it to finish. Each PHP process takes the next item from a queue, processes it and exits. Problem: The PHP processes are Symfony tasks and Symfony requires a fairly huge amount of memory. How can I safely calculate the required stack space for each thread so that PHP processes will have enough memory? The memory limit set in php.ini is 128Mb so should I allocate this much space in the stack?
When youforkyou get a new process, when youexecthe process is replaced by the one you execute. So any setting of stack space in the C program are irrelevant with regards to PHP memory usage.