question
stringlengths
25
894
answer
stringlengths
4
863
To create a class usable in Python is pretty straight-forward:http://code.activestate.com/recipes/54352-defining-python-class-methods-in-c/ But how to make methods static?
Use theMETH_STATICflag inPyMethodDef. The method will be passed NULL as the first parameter rather than an instance of the type. ``` static PyMethodDef FooMethods[] = { {"__init__", Foo_init, METH_VARARGS, "doc string"}, {"doSomething", Foo_doSomething, METH_VARARGS | METH_STATIC, "doc string"}, ...
I need the send and integer to a function and then append that to the end of a constant character. ``` int main (void) { append(1); } int append(int input) { const char P = 'P'; //This where I want to append 1 to P to create "P1"' } ```
No matter what you do, you need to convert the number to a string, otherwise you can't create a string containing both numbers. You can actually combine both the concatenation and the int-to-string conversion in one function call:sprintf: ``` char output[16]; sprintf(output, "P%d", input); ```
I'm currently writing a C function that return a time_t value but I need to manage error cases (because this function uses I/O functions) too. Is it correct to use (time_t) -1 as an error indicator?
Using(time_t)-1is already used bytime()function to report a failure so does not seem an unreasonable choice: Current calendar time encoded as time_t object on success, (time_t)(-1) on error. If the argument is not NULL, the return value is equal to the value stored in the object pointed to by the argument. However, ...
This question already has answers here:Closed10 years ago. Possible Duplicate:Typedef function pointer? Could you please help me understand the meaning of this typedef and how to use it? ``` typedef void (*__handler)(int) ``` without the "typedef", I know the rest is a function pointer. Thank you.
This defines a type name for the function pointer. Using this,__handleris now a type alias for a pointer to a function that takes anintand returnsvoid. ``` void myFunction(int) { // ... } int main(int argc, char **argv) { __handler functionPtr = &myFunction; // ... } ```
How can I detach an executable file from its process using WinAPI (C/C++)? I found an application that releases files from processes, Unlocker, but I don't know how that works.
You don't, normally. Windows pages in your executable on-demand. When you call a function which isn't in RAM yet, Windows loads it (and the whole page it resides on). As a result, if you would detach the EXE and the process would call a function that's still on disk, the process would crash. For applications on remo...
How do I specify in my makefile that I want to link with thelibtifflibrary. Just specifying -ltiff in LDFLAGS is not working.
Either you can use the -L flag (see either manual for the compiler - I am assuming that you are using gcc or g++ or Set the environment variableLD_LIBRARY_PATHto include the path for the library But you should also consider static or dynamic linking. The documentation for both compilers are very good to explain how...
i have developing a C++ Api project. i will use dialogboxparam to create a dialogbox... i done to create and set the textbox,labels and buttons... its work fine... now i want to add a image in the top of the dialogbox... i did use this code in WM_INITDIALOG: ``` HBITMAP hImage= (HBITMAP)LoadImage(NULL,L"C:\\WI...
The easiest way is to override the WM_PAINT for the window and paint the bitmap at that point (between the BeginPaint and EndPaint) calls There is an MFC based example here: http://www.programmersheaven.com/mb/mfc_coding/113034/113034/how-do-i-set-a-background-picture-in-a-dialog-box-/
i have the follwing code: ``` char* id = someFunction(); if (id == "0x01") { id = .... } ``` so, what i basically need - is to check, if in theidvariable i have the string value "0x01", and if yes, then pass there the{0x01, 0x00}system symbols instead of it. Thanks for your help.
usestrcmp(). this function is available instring.h ``` Example: printf( "Enter your name: " ); scanf( "%s", name ); if( strcmp( name, "Mary" ) == 0 ) printf( "Hello, Dr. Mary!\n" ); ```
In C, suppose I need to take input from a string ``` int num,cost; char *name[10]; printf("Enter your inputs [quantity item_of_name at cost]"); scanf("%d%*c%s%*c%*s%*c%d",&num,name[0],&cost); printf("quantity of item: %d",num); printf("the cost of item is: %d",cost); printf("the name of item is: %d",name[0]);...
``` int num,cost; std::string name; std::cout << "Enter your inputs [quantity item_of_name at cost]: "; if (std::cin >> num >> name >> cost) { } else { /* error */ } ``` You will want to add errorhandling
``` int main() { char buf1[100], buf[100]="ddl"; sprintf(buf1, "log_name = '%.*s'", buf); } ``` The above program is crashing. I am not able to understand why is this crashing. As far as I know before the character makesprintfto skip the format code and assign buf to next format code. But here what is t...
The format specifier"%.*s"requires the number of characters to be written to be specified: ``` sprintf(buf1, "log_name = '%.*s'", 3, buf); /* For example */ /* ^ */ ``` In the posted code onlybufis provided so there are missing arguments, which is undefined behaviour (in this case a c...
I am trying to compile a simple gearman worker on C. I use mac. Here is the code:#include <libgearman/gearman.h> int main(void) { gearman_worker_st worker; gearman_worker_create(&worker); gearman_worker_add_server(&worker, "localhost", 4730); return 0; } When I try to compile it with: ``` #gcc test.c...
maybe your need to define the lib path, like-L/usr/lib/, use your libgearman.a stored path to substitute-L/usr/lib/
I am wish to implement a similar pattern to what Apple do withCGRectMake()and all their other~Type~Make()functions. What is the code for CGRectMake... I understand what it does, but more specifically I would like to know what it does (in terms of stack, heap et al.)? Is it just: ``` inline function CGRectMake(CGFloa...
If you command-click onCGRectMakeXcode shows you its implementation. You almost had it ;-) ``` CG_INLINE CGRect CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height) { CGRect rect; rect.origin.x = x; rect.origin.y = y; rect.size.width = width; rect.size.height = height; return rect; } ```
I was going through a book where I found this question Does mentioning the array name gives the base address in all the contexts? Can some one explain the cases where array name does not give the base address.thanks
Array-to-pointer decay does not happen everywhere. One example is the argument ofsizeof, another is the argument of&: ``` int arr[10]; sizeof(arr); // gives 10 * sizeof(int), NOT sizeof(int*) int (*p)[10] = &arr; // gives the address of the array, NOT of an rvalue ``` The second example is fairly obvious...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. I need to have a socket which liste...
You can't bind a single socket to several ports. The socket is bound only once with a "port-address" pair. You need to create several listening sockets and bind each of them to the local address (can be the same for them) and a port (which are different).
Declarations look like these: ``` void *malloc(size_t size); void free(void *pointer) ``` As far as I can understand, the void *malloc means that malloc returns a pointer to void ("Void pointer") and free is just void. What's the difference? Why does it look this way?
Thevoidjust means the return type isn't defined (not a pointer to achar, for example), just a contiguous block of memory of specified size. free()doesn't return anything. It doesn't need to.
I need to discover name of audio device by ID. I use WaveOut functions. please help me
This is an example on how to enumerate waveIn and waveOut devices on your system: http://blogs.msdn.com/b/matthew_van_eerde/archive/2012/03/13/sample-how-to-enumerate-wavein-and-waveout-devices-on-your-system.aspx So, you can just compare dev id you need and get name of the device.
With Bash you can do a simple variable test like this ``` $ [ $foo ]; echo $? 1 $ foo=bar $ [ $foo ]; echo $? 0 ``` The expression is true if and only if the argument is not null. What would be a similar test with C? Edit Lets say aninttype for argument sake.
In general, there is implicit boolean conversion in C. So all of the following will print "bad": ``` int a = 0; if (a) { // if a is nonzero. printf("good"); } else { printf("bad"); } char* str = NULL; if (str) { // if str is nonzero. (NULL is zero). printf("good"); } els...
I am wish to implement a similar pattern to what Apple do withCGRectMake()and all their other~Type~Make()functions. What is the code for CGRectMake... I understand what it does, but more specifically I would like to know what it does (in terms of stack, heap et al.)? Is it just: ``` inline function CGRectMake(CGFloa...
If you command-click onCGRectMakeXcode shows you its implementation. You almost had it ;-) ``` CG_INLINE CGRect CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height) { CGRect rect; rect.origin.x = x; rect.origin.y = y; rect.size.width = width; rect.size.height = height; return rect; } ```
I was going through a book where I found this question Does mentioning the array name gives the base address in all the contexts? Can some one explain the cases where array name does not give the base address.thanks
Array-to-pointer decay does not happen everywhere. One example is the argument ofsizeof, another is the argument of&: ``` int arr[10]; sizeof(arr); // gives 10 * sizeof(int), NOT sizeof(int*) int (*p)[10] = &arr; // gives the address of the array, NOT of an rvalue ``` The second example is fairly obvious...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. I need to have a socket which liste...
You can't bind a single socket to several ports. The socket is bound only once with a "port-address" pair. You need to create several listening sockets and bind each of them to the local address (can be the same for them) and a port (which are different).
Declarations look like these: ``` void *malloc(size_t size); void free(void *pointer) ``` As far as I can understand, the void *malloc means that malloc returns a pointer to void ("Void pointer") and free is just void. What's the difference? Why does it look this way?
Thevoidjust means the return type isn't defined (not a pointer to achar, for example), just a contiguous block of memory of specified size. free()doesn't return anything. It doesn't need to.
I need to discover name of audio device by ID. I use WaveOut functions. please help me
This is an example on how to enumerate waveIn and waveOut devices on your system: http://blogs.msdn.com/b/matthew_van_eerde/archive/2012/03/13/sample-how-to-enumerate-wavein-and-waveout-devices-on-your-system.aspx So, you can just compare dev id you need and get name of the device.
With Bash you can do a simple variable test like this ``` $ [ $foo ]; echo $? 1 $ foo=bar $ [ $foo ]; echo $? 0 ``` The expression is true if and only if the argument is not null. What would be a similar test with C? Edit Lets say aninttype for argument sake.
In general, there is implicit boolean conversion in C. So all of the following will print "bad": ``` int a = 0; if (a) { // if a is nonzero. printf("good"); } else { printf("bad"); } char* str = NULL; if (str) { // if str is nonzero. (NULL is zero). printf("good"); } els...
This question already has an answer here:Closed10 years ago. Possible Duplicate:What does “void *(*)(void *)” mean in c++? What does the type void(*)(void *) mean? I came across this type in the example code for the book "Mastering Algorithms with C" ``` void list_init(List *list, void (*destroy)(void *data)) { ...
It's a function pointer. ``` void (*destroy)(void *data) ``` destroyis a pointer to a function which returnsvoidand takes avoid*as an argument. cdecl.orgis a useful tool for discerning complex C declarations. Also, take a look atthe spiral rule.
Hey so I'm getting that error whenever I try to do something like this: ``` void swap(struct lnode* n1){ struct lnode*temp = n1->next; } ``` I thought that I could have the temp pointer point to n1->next but it's giving me the dereferencing pointer to incomplete type error. Can anyone help me? Thanks
To access members of the struct a declaration like this is insufficient: ``` struct lnode; ``` This gives you an incomplete type: the compiler now knows the name of the struct but doesn't know what fields it contains. You can have pointers to incomplete types, but you can't access their members, calculate their size...
Need help on a simple c program. Writing a TestValue program. The program runs but doesn't return a letter grade. This is what I have so far. ``` #include <stdio.h> int main() { double testValue; char getGrade; printf("Enter your score between o and 100:"); scanf("%if", &testValue); ...
%ifShould be%lf You have not called thegetGradefunction You have two identifiers with the same name. Remove thechar getGrade;declaration and just call thegetGradefunction.
I was asked this interview question. I am not sure what the correct answer for it is (and the reasoning behind the answer): Is sin(x) a good hash function?
If you meansin(), it's not a good hashing function because: it's quite predictable and for somexit's no better than justxitself. There should be no seemingly apparent relationship between the key and the hash of the key.it does not produce an integer value. You cannot index/subscript arrays with floating-point indice...
I'm reading the book"Objective-C Programming The Big Nerd Ranch Guide". They give out this code: ``` void congratulateStudent(char student, char course, int numDays) { printf("%s has done as much %s Programming as I could fit into %d days.\n", student, course, numDays); } ``` andcallit with this: ``` congratulat...
There might be a typo. Charmeans only one character in single quotes, as'a'. A constant string is in double quotes and decays into achar*or character pointer, like this. ``` "Hello World" ```
I'm reading the book"Objective-C Programming The Big Nerd Ranch Guide". They give out this code: ``` void congratulateStudent(char student, char course, int numDays) { printf("%s has done as much %s Programming as I could fit into %d days.\n", student, course, numDays); } ``` andcallit with this: ``` congratulat...
There might be a typo. Charmeans only one character in single quotes, as'a'. A constant string is in double quotes and decays into achar*or character pointer, like this. ``` "Hello World" ```
Now, the aim of the program is to take four names through a variable argument list and concatenate them using vsprintf() into a single string called 'total'. As the program currently is, only the first name appears in string 'total'. How can I solve this problem please? Thanks :)
Signature isint vsprintf(char *str, const char *format, va_list ap);. The second argument is the usualprintfformat string... so: ``` void concat(char *total, ...) { va_list pointer; va_start(pointer, total); vsprintf(total, "%s %s %s %s", pointer); va_end(pointer); } ``` This of course only works with ...
I would like to be able to check the format of an object file from within my C code so that I can use different functions for reading the file based on whether it is COFF or ELF format. Is this possible, and if so, how would I do it? This is in Linux btw if that makes any difference.
Read the first four bytes. If they are equal to\x7fELF, it's an ELF file. Otherwise, you should parse it as COFF and see if it makes sense. (Note that COFF magic is a lot more complicated; I get no less than 42 magic entries in/usr/share/file/magicfor it).
``` int main() { int i ; clrscr(); for(i = 0; i <= 6; i++) { if(i % 2 == 0) { **textcolor(2);** cprintf("%d\n", i); } if(i % 2 != 0) { **textcolor(3);** cprintf("%d\n", i); } } getch(); } ``` OUTPUT:(all evens are in ...
Probably\nis used literally and only does a line feed (= jump to next line and keep cursor at same column) and no carriage return (= put cursor at start of line). Change the\ns inside the calls tocprintfto\r\n.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he...
There is no standard, but many C projects use lowercase filenames, separating words with underscores. The main thing is to be consistent though.
I am trying to extract relative path name from absolute path name. Is there a function for this in C? Is there a function to print string starting from a particular character(I have the index)?
In POSIX.1-2001 (e.g. Linux),man 3 basenamegives: The functions dirname() and basename() break a null-terminated pathname string into directory and filename components. In the usual case, ... basename() returns the component following the final '/'. Trailing '/' characters are not counted as part of the pathname.
20.6.11 Temporary buffers [temporary.buffer] defines two function templates: ``` template<class T> pair<T*, ptrdiff_t> get_temporary_buffer(ptrdiff_t n) noexcept; template<class T> void return_temporary_buffer(T* p); ``` Is there something similar in the C standard? Something like: ``` void * get_temporary_buffer(...
There is not something similar in the C standard. The standard says this about get_temporary_buffer: ``` Obtains a pointer to storage sufficient to store up to n adjacent T objects. ``` I.e. you are not guaranteed to get the space you request. Most C++ standard library implementations today implement get_temporary_b...
How does the following snippet work? What is IN? Eclipse says that IN stands for 'macro expansion': ``` UWORD32 (*get_u32)(IN UWORD8 *buffer_ptr); /* Gets unsigned 32bit word */ /* from the buffer */ ``` This above code is part of a struct. and is used like this. ``` ...
I would guess thatINis#defined somewhere asconst: ``` #define IN const // input parameters are const ``` get_u32is just a function pointer - the function takes a single parameter (a pointer to aUWORD8) and returns aUWORD32.
I have an older program that was built with clang via CFLAGS="-Wunreachable-code" and it's displaying some warnings on certain switch(), on a break; where it's saying it's 'will never be executed', is it safe to simply remove the unreachable code, or is -Wunreachable-code beta in nature? Specifically, it's giving war...
Read the code, understand it, and if the code marked unreachable really is unreachable and it isn't unreachable because of a logic error, then you can just remove it. If you haven't read the code and understood it, then it isn't safe to modify it no matter what the compiler says.
This question already has answers here:Closed10 years ago. Possible Duplicate:C preprocessor and concatenationC preprocessor # and ## operators While searching through some C code of an OS that I develop with (on an embedded project,) I found the following defines statement: ``` #define concatn(s1, s2) s1 ## s2 ```...
It's part of thepreprocessor, concatenation of tokens, andconcatn(x,y)is replaced byxy.
I would like to know how to allocate sequential memory for an array of structures inside of another structure. Say I have struct1 which has an array of struct2, I would like to have it all in one sequential block of memory. I could use malloc to allocate the block, but how would I assign the array's memory? ``` stru...
Use aflexible array member: ``` #define NUM_ELEM 42 struct a { /* whatever */ }; struct b { int c; struct a d[]; // flexible array member }; struct b *x = malloc(sizeof *x + NUM_ELEM * sizeof x->d[0]); ```
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. Why it gives me that i cant open th...
I'm going to wager a guess it's because you're usingfgets()incorrectly for this use case. A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str So you're getting a newline character with the name and trying to open that. As this...
I've encountered many examples on the web, that haveextern int xin main.c, where the main function lies. The only use ofexternI'm aware of, is to make a declaration in another file, and use it in another file, after defining it. Like : a.h :extern int x; a.c :int x = 5; main.c :#include "a.h" // and start using x ...
externtells the compiler thatxexists in a different module and should be linked from elsewhere. Putting it in main.c directly just avoids pulling in a header (which would be included in-line anyways) Just like in a header,xstill needs to exist in another .c module where itisn'tdefinedextern.
I have the following pointer: ``` BSTR *PREVIOUS; ``` And I want make a new copy to: ``` BSTR *NEW; ``` I want to copy the CONTENTS/DATA (that PREVIOUS is pointing) from PREVIOUS to NEW. I've just tried the following command, but it doesn't work: ``` memcpy(NEW,PREVIOUS,SysStringByteLen(*PREVIOUS)); ``` I dont ...
BSTRis itself already a pointer, you should almost always use just a plainBSTR, not aBSTR*(which is a pointer to aBSTR). Ordinarily, you would copy aBSTRwithSysAllocString: ``` BSTR NEW = SysAllocString(PREVIOUS); ``` If you really do have a pointer to aBSTR(such as via a function's out parameter), then you add a l...
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen...
This is a linker failure. You need to link with the math library, specify-lmat the end of your compiler command. Fromman pow: Link with -lm.
I have a function to reverse an array and I think there are some issues with the same. Please guide me in the right path to get this sorted out. Function: ``` void reversearr (int arr[], int arrlen) { int a, b, arrtemp[arrlen]; b=arrlen; for (a=0; a<=arrlen; a++) { ar...
``` void reversearr (int arr[], int arrlen) { int a, tmp; for (a = 0; a < arrlen / 2; ++a) { tmp = arr[a]; arr[a] = arr[arrlen - a - 1]; arr[arrlen - a - 1] = tmp; } } ```
I have written a program which prints all the permutations of a given string. But it was printing some weird things. The code goes as follows: ``` #include <stdio.h> void swap (char *x, char *y) { char temp; temp = *x; *x = *y; *y = temp; } void permute(char *a, int i, int n) { int j; if (i == n) pr...
There is your problem: ``` printf("%d\n", a); ``` should be ``` printf("%s\n", a); ```
Is there a replacement forpiconst on OS X 10.8? When I use it I get the following warning: ``` 'pi' is deprecated: first deprecated on Mac OS X 10.8 ``` It works but I want to get rid of that warning.
Try includingmath.h, which defines the C standard library macroM_PI.
I have written some code in C and need to convert this to MIPS 64, with and without optimisation. I have been trying to convert this with gcc but this converts it to x86 which is far more complex. Furthermore, I have been trying to find a cross compiler but have not been able to get any compiler to work. Any help and ...
After downloading and installing Codesourcery codebench for MIPS, invoke the MIPS gcc cross compiler for the MIPS 64 revision 2 architecture as follows: ``` C:\Program Files (x86)\CodeSourcery\Sourcery_CodeBench_Lite_for_MIPS_GNU_Linux\bin\mips-linux-gnu-gcc -march=mips64r2 foo.c -S ``` This generates MIPS assembly ...
I am using a program which outputs TIFF file. However when I try to open that tiff file from paint or picture viewer or any other image viewer program, I get the responce that the tiff file has invalid format. I want to dig deeper and see why I'm getting the invalid format error. How can I check that. Is there any C ...
Take a look atlibtiffto see about opening up TIFF files andviewing errors.
Suppose I have a string value "110099" and I need to increment the substring value "00" in steps of x until y and wrap to zero , if x =10 and y=90 i.e "111099","112099" ... and after "119099" the string value is "110099". Can anyone please help how do I start with. thanks for your time. EDIT: Changed the question to ...
Take the substring you want to increment.Cast it to integer values.increment by 10 and then %100.Cast back to string.Replace it back in your original string.Code is pretty simple.
How can I achieve these conversions in C without using sprintf? ``` 20 => 0x20 12 => 0x12 ``` Currently I have: ``` int year = 12; int month = 10; int day = 9; unsigned char date[3]; date[0] = year & 0xFF; date[1] = month & 0xFF; date[2] = day & 0xFF; ``` date will contain { 0x0C, 0x0A, 0x09 } but I want it to be...
You just have to retrieve each digit in decimal base en multiply it to its equivalent in hexadecinal. ``` #include <stdio.h> int hex(int v){ int total = 0; int resultbase = 1; while(v > 0 ){ total += resultbase * (v % 10); resultbase *= 16; v /= 10; } return total; } int main(){ printf ("12 => %x, 20...
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen...
This is a linker failure. You need to link with the math library, specify-lmat the end of your compiler command. Fromman pow: Link with -lm.
I have a function to reverse an array and I think there are some issues with the same. Please guide me in the right path to get this sorted out. Function: ``` void reversearr (int arr[], int arrlen) { int a, b, arrtemp[arrlen]; b=arrlen; for (a=0; a<=arrlen; a++) { ar...
``` void reversearr (int arr[], int arrlen) { int a, tmp; for (a = 0; a < arrlen / 2; ++a) { tmp = arr[a]; arr[a] = arr[arrlen - a - 1]; arr[arrlen - a - 1] = tmp; } } ```
I have written a program which prints all the permutations of a given string. But it was printing some weird things. The code goes as follows: ``` #include <stdio.h> void swap (char *x, char *y) { char temp; temp = *x; *x = *y; *y = temp; } void permute(char *a, int i, int n) { int j; if (i == n) pr...
There is your problem: ``` printf("%d\n", a); ``` should be ``` printf("%s\n", a); ```
Is there a replacement forpiconst on OS X 10.8? When I use it I get the following warning: ``` 'pi' is deprecated: first deprecated on Mac OS X 10.8 ``` It works but I want to get rid of that warning.
Try includingmath.h, which defines the C standard library macroM_PI.
I have written some code in C and need to convert this to MIPS 64, with and without optimisation. I have been trying to convert this with gcc but this converts it to x86 which is far more complex. Furthermore, I have been trying to find a cross compiler but have not been able to get any compiler to work. Any help and ...
After downloading and installing Codesourcery codebench for MIPS, invoke the MIPS gcc cross compiler for the MIPS 64 revision 2 architecture as follows: ``` C:\Program Files (x86)\CodeSourcery\Sourcery_CodeBench_Lite_for_MIPS_GNU_Linux\bin\mips-linux-gnu-gcc -march=mips64r2 foo.c -S ``` This generates MIPS assembly ...
I am using a program which outputs TIFF file. However when I try to open that tiff file from paint or picture viewer or any other image viewer program, I get the responce that the tiff file has invalid format. I want to dig deeper and see why I'm getting the invalid format error. How can I check that. Is there any C ...
Take a look atlibtiffto see about opening up TIFF files andviewing errors.
Suppose I have a string value "110099" and I need to increment the substring value "00" in steps of x until y and wrap to zero , if x =10 and y=90 i.e "111099","112099" ... and after "119099" the string value is "110099". Can anyone please help how do I start with. thanks for your time. EDIT: Changed the question to ...
Take the substring you want to increment.Cast it to integer values.increment by 10 and then %100.Cast back to string.Replace it back in your original string.Code is pretty simple.
How can I achieve these conversions in C without using sprintf? ``` 20 => 0x20 12 => 0x12 ``` Currently I have: ``` int year = 12; int month = 10; int day = 9; unsigned char date[3]; date[0] = year & 0xFF; date[1] = month & 0xFF; date[2] = day & 0xFF; ``` date will contain { 0x0C, 0x0A, 0x09 } but I want it to be...
You just have to retrieve each digit in decimal base en multiply it to its equivalent in hexadecinal. ``` #include <stdio.h> int hex(int v){ int total = 0; int resultbase = 1; while(v > 0 ){ total += resultbase * (v % 10); resultbase *= 16; v /= 10; } return total; } int main(){ printf ("12 => %x, 20...
This question already has an answer here:Closed10 years ago. Possible Duplicate:How would you convert from ASCII to Hex by character in C? I like to convert a hex value, represented in ascii code to the number represented by the hex value. As an example: A5should convert to0xA5(which is 165) ButA5is represented i...
Usestrtol. ``` long x = strtol("A5", 0, 16) // x is now 165 ```
newbie question; I have two binary numbers; say for example; 0b11 and 0b00. How can I combine the two numbers so that I get 0b1100 (i.e. place them right next to each other to form a new number)
With bitwise shift and or operators: ``` unsigned int a = 0x03; /* Binary 11 (actually binary 00000000000000000000000000000011) */ unsigned int b = 0x00; /* Binary 00 */ /* Shift `a` two steps so the number becomes `1100` */ /* Or with the second number to get the two lower bits */ unsigned int c = (a << 2) | b; ...
Is there a way to use sscanf%cto read in the value of achar? How would I put in the escape sequence for unicode or ascii for a particular character? ``` sscanf("%c",chr); ```
You can read a character from the input with ``` char chr; scanf ("%c", &chr); ``` Reading escape sequences can be operating system specific. On most you would have to tell the terminal driver to not process escape sequences into other actions (like input line editing) and instead pass the raw characters through. ...
I need to implement a hash table to maintain IP packets. However, due to the uniqueness of packets, I cannot make a hash key using one single element (say IP address). Following are the elements in a packet which will be responsible for making an packet unique: Source IP address (16 byte string, due to IPv6 format)So...
You mention you know how to hash for a single element case. Then, you can put/copy/concat all your listed elements into a single buffer (say an unsigned char array with size 16+2+16+2+1), then treat this buffer like a single element.
I know that functions are taggedexternin C by default and it is also possible to use anexternvariable in C (if it is initialized in some other file or if I writeextern int foo = 1;). But can I useexternfor a C macro because they behave like functions?
Unless something radically changed in C99, preprocessor macros don't have storage classes. You can't declare them without simultaneously defining them. They aren't even treated by the compiler in the same way that other identifiers are treated -- they're a purely textual translation that (at least conceptually) happ...
This question already has answers here:Closed10 years ago. Possible Duplicate:C Macro definition to determine big endian or little endian machine? ``` int main() { int x = 1; char *y = (char*)&x; printf("%c\n",*y+48); } ``` If it's little endian it will print 1. If it's big endian it will print 0. Is that...
In short, yes. Suppose we are on a 32-bit machine. If it is little endian, thexin the memory will be something like: ``` higher memory -----> +----+----+----+----+ |0x01|0x00|0x00|0x00| +----+----+----+----+ A | &x ``` so(char*)(&x) == 1, and*y+48 == '1'. (48 is the ascii code of '...
Consider following C code - ``` typedef struct node { int data; }node; int main() { node *temp; temp->data=100; printf("%d",temp->data); return 0; } ``` It givesSegmentation faulton line containingtemp->data=100;because (I think) I haven't allocate memory for it. So, there is nothing such astemp...
The temp pointer takes some garbage value as its not initialised. By chance temp has a garbage value which may happen to be legal address for your program so it runs. If garbage value has illegal adress it will generate segment fault.
I am creating random integers with the following algorithm: ``` int random; int i; for (i = 0; i < RANDOM_COUNT; i++) { random = (((int) rand() << 0) & 0x0000FFFFd) | (((int) rand() << 16) & 0xFFFF0000d); fprintf(outputFile, " %d\n", random); } ``` I am getting the following warning: warning: i...
Does anyone know which part of the operation [(((int) rand() << 16) & 0xFFFF0000d);] is triggering the warning? Yes, it's the0xFFFF0000d, because it's 36 bits in size. Note that this number is equal to0xFFFF0000D. You probably meant0xFFFF0000. Likewise,0x0000FFFFdis equal to0x0000FFFFD. You probably meant0x0000FFFF....
I have created a 2D-array in following way: ``` int** map_array = (int**)malloc(sizeof(yy_value*xx_value)); ``` When i try to assign a value on a position: ``` map_array[y*xx_value+x] = 5; ``` I get following error: ``` Assigning to 'int *' from incompatible type 'int' ``` What am i doing wrong here?
Change: ``` int** map_array = (int**)malloc(sizeof(yy_value*xx_value)); ``` to: ``` int* map_array = (int*)malloc(yy_value*xx_value*sizeof(map_array[0])); ``` Explanation: you're allocating a "flattened" 2D array here, where you calculate your own 1D index rather than an actual 2D array. Also the size passed to ma...
I'm having problems with applesexamplesfor vDSP. I tried all of them but i need the convolution sample in the end. I can't even get it through the linker: ``` Undefined symbols for architecture i386: "_conv", referenced from: _ConvTiming in main.o ld: symbol(s) not found for architecture i386 ``` Is the erro...
You need to include the Accelerate framework in the build.
I have a header file, wich contain aunsigned char arraythat is in fact a ttf font file. In a .c file i'm able to load the font, and to use it ( i include the ttf header file in the .c file), but the problem is that when i'm trying to use this in another c file, i get one of those 2 errors; First error that i can get...
Useextern. In your header file, make: ``` extern unsigned char my_array[]; ``` Inexactly one.cfile, defined the array.
I have the followingcharinside an Arduino sketch: ``` char inData[80]; ``` When I print to the serial console: ``` Serial.print(strlen(inData) - 1); ``` I'm expecting to see:79instead I see:655356553501234567 Can someone shed some light as to why this is happening?
strlenis looking for a terminating nul. Calling it on an uninitialized array or pointer results in undefined behavior. You wantsizeof(inData)instead.
``` SHA1(data, length, hash); unsigned char *labelPtr; labelPtr = hash; mpz_set_str (encrypted, labelPtr, 16); gmp_printf("hashed= %Zd\n", encrypted); ``` encryptedequals 0? I need to get an integer from this hash so that I can perform RSA encryption. I see the hash when I debug, but cannot seem to turn this into a...
mpz_set_strsecond parameter must be a string. Thehashargument you pass toSHA1function is probably not a string. Convert it to a string format before passing it to thempz_set_strfunction.
I am using Slackware 14 and latest Eclipse Juno. As a regular Eclipse user, I installed CDT just like I always did. However, when I create a new project, there is no toolchain available. Screenshot here: I remember I used to get the default GCC toolchain available as soon as I have CDT installed in Linux. Even if ...
you should install it from help menu
How can I display files with extension ".txt" only in C using execl or execve? ``` #include <stdio.h> #include <unistd.h> #include <sys/types.h> int main(int argc, char **argv) { ( execl("/bin/ls","*.txt",NULL); return 0; } ```
You're looking forglob(3): ``` #include <glob.h> extern char **environ; int main(int argc, char *argv[]) { glob_t g={0}; g.gl_offs = 1; /* reserve slot for "/bin/ls" */ glob("*.txt",GLOB_DOOFFS,0,&g); g.gl_pathv[0] = "/bin/ls"; execve(*g.gl_pathv,g.gl_pathv,environ); } ```
What is the fastest algorithm for compressing RGBA 32 bit image data? I am working in C, but am happy for examples in other programming languages. Right now I am using LZ4 but I am considering run length / delta encoding. Lossless encoding, a mix of real life images and computer generated / clipart images. Alpha cha...
I ended up just using LZ4. Nothing else was even close to as fast and LZ4 usually got at least 50% size reduction.
This question already has answers here:Closed10 years ago. Possible Duplicate:Why are declarations put between func() and {}? In C, what does it mean when I declare a variable following a function signature, before the function body? Example: ``` int foo (i) int i { printf ("the value of variable 'i' is: %d", ...
It means you are looking at old code. That is the old K&R syntax.Basically it says,iis the argument, and it is anint You can rewrite it as ``` int foo (int i) { printf ("the value of variable 'i' is: %d", i); return i; } ```
For example, in the header fileexample.h, I wrote: ``` #include <stdio.h> #include <stdlib.h> #include <time.h> ``` And in the source fileexample.c, I wrote: ``` #include "example.h` ``` Do I still need to explicitly wrote these lines if I need functions of these libararies? ``` #include <stdio.h> #include <stdli...
No. Keep in mind that includes works like some kind of text substitution, as it's done by thepreprocessor. When you write, on some file: ``` #include "someheader.h" ``` It's just like that line will be replaced with the actual content of the header file.
How do I cut off decimal places in C without rounding? For example if the number is4.48 it will just show4.4 %.1frounds to4.5
You can (ab)use the fact that integer division truncates and doesn't round: ``` float original = 4.48; int tmp = original * 10; // 44.8 truncated to 44 float truncated = tmp / 10.0; // 4.4 ```
Does only declaring a variable reserves a space for it in the program memory? And if not, then please consider the following snippet: ``` void foo(int bar, int baz){ int a; char b[4]; } ``` This code as soon as it enters foo allocates a space in stack and creates an activation record like this: | baz | | ...
aandbare defined but not used. Since the program can't tell whether they were created, the compiler is free to ignore them.
I like to change the number of decimal digits showed whenever I use a float number in C. Does it have something to do with theFLT_DIGvalue defined infloat.h? If so, how could I change that from 6 to 10? I'm getting a number like0.000000while the actual value is0.0000003455.
There are two separate issues here: The precision of the floating point number stored, which is determined by usingfloatvsdoubleand then there's the precision of the number being printed as such: ``` float foo = 0.0123456789; printf("%.4f\n", foo); // This will print 0.0123 (4 digits). double bar = 0.01234567891234...
I have a code like: ``` int contains(LPCTSTR name) { char * data = "test.txt"; } ``` How can i check whethernamecontains 'data'? Thanks!
Since you are using Windows andTCHAR, a more idiomatic solution would be: ``` BOOL contains(LPCTSTR lpName) { return _tcsstr(name, _T("data")); } ``` Unless yourdatais deliberately achar *, in which case the answer changes.
I have an buffer of size 101 ``` char buffer[101] ``` I am trying to copy an address to the array ``` int i; for(i=0;i<sizeof(buffer);i+=4) *(long*)&buffer[i] = address ``` in which address is of type long. However I met with a stack smashing detection when I am running it. Any idea why?
Alignment issues aside, ``` for(i=0;i<sizeof(buffer);i+=4) *(long*)&buffer[i] = address ``` wheni == 100you write past the allocated buffer. You should stop wheni > sizeof buffer - 4.
I have a simple socket server that is supposed to receive a string and return another. The string received is multi-line. Is there a way to tell when the client finished sending without having a predefined end of transmission set of characters added at the end?
You have to know in advance either (1) what the length of message is or (2) what constitutes the end of a message. So either (1) prefix a message with the expected length; or (2) have all messages be the same size; (3) define different message types in which the length is known in advance; or (4) define exactly what ...
I was searching for how to add two numbers without using ('+'/'++') and went throughlink. But, I also found this solution: ``` #include<stdio.h> int add(int x, int y); int add(int x, int y) { return printf("%*c%*c", x, ' ', y, ' '); } int main() { printf("Sum = %d", add(3, 4)); return 0; } ``` Can so...
``` return printf("%*c%*c", x, ' ', y, ' '); ``` The*in theprintfformat means that the field width used to print the character is taken from an argument ofprintf, in this case,xandy. The return value ofprintfis the number of characters printed. So it's printing one' 'with a field-width ofx, and one with a field-wid...
I have a string being moved and i want to print it based on the register. I did the following: ``` gdb x $esp 0xbffff110: "\274\205\004\b\324\361\377\277\334\361\377\277]\257\344\267\304s\374\267" {then I copied the address} >> x *0xbffff110 0x80485bc <__dso_handle+12>: "test1" ``` Is there any way to do thi...
Is there any way to do this in one step? ``` (gdb) print *(char**)$esp ```
I compiled Connector/C from scratch, and when I try to connect using it, my_connect returns -1 and WSAGetLastError() == 2003 I have no clue what's wrong, any ideas? I've tried googling but I can't even find anything on what that error means. ``` MYSQL *my = mysql_init(NULL); if(my) { MYSQL *result =...
I've tracked the problem down to the MySQL C connector using the ipv6 getaddrinfo which returns ::1, I'm using an old mysql server version which doesn't support ipv6.
I have a simple C program and when I compile and run it with./output, does it get a PID on Linux? (I think, every running program is a process and it should have a PID.) I used theps auxcommand but I couldn't find the process name there. I remember, when my console application (a C program) was running on Windows 7,...
Yes, every running program on Linux gets a PID. Your program just prints"Hello, World!", and will complete so quickly that by the time you runps auxit will have finished. Also,void main()should beint main(void), and you should add\nto the end of your output string.
Current way is like this, which looks quite clumsy.. ``` ex1_test : ex1.o ex1_test.o cc -o ex1_test ex1.o ex1_test.o ex2_test : ex2.o ex2_test.o cc -o ex2_test ex2.o ex2_test.o ex3_test : ex3.o ex3_test.o cc -o ex3_test ex3.o ex3_test.o ``` Is there a variable that I can use to represent the current targ...
Step 1, introduce automatic variables: ``` ex1_test : ex1.o ex1_test.o cc -o $@ $^ ex2_test : ex2.o ex2_test.o cc -o $@ $^ ex3_test : ex3.o ex3_test.o cc -o $@ $^ ``` Step 2, realize that these rules all look the same, and replace them with a pattern rule: ``` ex%_test: ex%.o ex%_test.o cc -o $@ $^ ...
This question already has answers here:Closed10 years ago. Possible Duplicate:trying to create a simple shell in c for win32 api I'm doing some C programming in Windows for a low level coding assignment and I'm trying to get this create process to work however. I am try to trying to execute a command as a process...
Since dir is a cmd.exe built in you need to run cmd , ie setlpApplicationNametocmd.exeandlpCommandLineto dir
I've started writing a boot loader for my z80 system. So far the program can accept hex via serial and load it to a location in the memory. The problem I have though is the boot loader is at the start of memory and uses the interrupts, How can I load a new program with out overwriting the boot loader? (Also a loade...
The best and most widely used approach is to split your app into a stable boot loader that is never updated, and the application that you can replace from time to time. AFAIK, in Z80 there are just interrupt vectors and there no support for replacing them in the CPU itself. You need to have something in your hardware...
Does only declaring a variable reserves a space for it in the program memory? And if not, then please consider the following snippet: ``` void foo(int bar, int baz){ int a; char b[4]; } ``` This code as soon as it enters foo allocates a space in stack and creates an activation record like this: | baz | | ...
aandbare defined but not used. Since the program can't tell whether they were created, the compiler is free to ignore them.
I like to change the number of decimal digits showed whenever I use a float number in C. Does it have something to do with theFLT_DIGvalue defined infloat.h? If so, how could I change that from 6 to 10? I'm getting a number like0.000000while the actual value is0.0000003455.
There are two separate issues here: The precision of the floating point number stored, which is determined by usingfloatvsdoubleand then there's the precision of the number being printed as such: ``` float foo = 0.0123456789; printf("%.4f\n", foo); // This will print 0.0123 (4 digits). double bar = 0.01234567891234...
I have a code like: ``` int contains(LPCTSTR name) { char * data = "test.txt"; } ``` How can i check whethernamecontains 'data'? Thanks!
Since you are using Windows andTCHAR, a more idiomatic solution would be: ``` BOOL contains(LPCTSTR lpName) { return _tcsstr(name, _T("data")); } ``` Unless yourdatais deliberately achar *, in which case the answer changes.
I have an buffer of size 101 ``` char buffer[101] ``` I am trying to copy an address to the array ``` int i; for(i=0;i<sizeof(buffer);i+=4) *(long*)&buffer[i] = address ``` in which address is of type long. However I met with a stack smashing detection when I am running it. Any idea why?
Alignment issues aside, ``` for(i=0;i<sizeof(buffer);i+=4) *(long*)&buffer[i] = address ``` wheni == 100you write past the allocated buffer. You should stop wheni > sizeof buffer - 4.
I have a simple socket server that is supposed to receive a string and return another. The string received is multi-line. Is there a way to tell when the client finished sending without having a predefined end of transmission set of characters added at the end?
You have to know in advance either (1) what the length of message is or (2) what constitutes the end of a message. So either (1) prefix a message with the expected length; or (2) have all messages be the same size; (3) define different message types in which the length is known in advance; or (4) define exactly what ...
I was searching for how to add two numbers without using ('+'/'++') and went throughlink. But, I also found this solution: ``` #include<stdio.h> int add(int x, int y); int add(int x, int y) { return printf("%*c%*c", x, ' ', y, ' '); } int main() { printf("Sum = %d", add(3, 4)); return 0; } ``` Can so...
``` return printf("%*c%*c", x, ' ', y, ' '); ``` The*in theprintfformat means that the field width used to print the character is taken from an argument ofprintf, in this case,xandy. The return value ofprintfis the number of characters printed. So it's printing one' 'with a field-width ofx, and one with a field-wid...
I have a string being moved and i want to print it based on the register. I did the following: ``` gdb x $esp 0xbffff110: "\274\205\004\b\324\361\377\277\334\361\377\277]\257\344\267\304s\374\267" {then I copied the address} >> x *0xbffff110 0x80485bc <__dso_handle+12>: "test1" ``` Is there any way to do thi...
Is there any way to do this in one step? ``` (gdb) print *(char**)$esp ```
I compiled Connector/C from scratch, and when I try to connect using it, my_connect returns -1 and WSAGetLastError() == 2003 I have no clue what's wrong, any ideas? I've tried googling but I can't even find anything on what that error means. ``` MYSQL *my = mysql_init(NULL); if(my) { MYSQL *result =...
I've tracked the problem down to the MySQL C connector using the ipv6 getaddrinfo which returns ::1, I'm using an old mysql server version which doesn't support ipv6.
I have a simple C program and when I compile and run it with./output, does it get a PID on Linux? (I think, every running program is a process and it should have a PID.) I used theps auxcommand but I couldn't find the process name there. I remember, when my console application (a C program) was running on Windows 7,...
Yes, every running program on Linux gets a PID. Your program just prints"Hello, World!", and will complete so quickly that by the time you runps auxit will have finished. Also,void main()should beint main(void), and you should add\nto the end of your output string.
Current way is like this, which looks quite clumsy.. ``` ex1_test : ex1.o ex1_test.o cc -o ex1_test ex1.o ex1_test.o ex2_test : ex2.o ex2_test.o cc -o ex2_test ex2.o ex2_test.o ex3_test : ex3.o ex3_test.o cc -o ex3_test ex3.o ex3_test.o ``` Is there a variable that I can use to represent the current targ...
Step 1, introduce automatic variables: ``` ex1_test : ex1.o ex1_test.o cc -o $@ $^ ex2_test : ex2.o ex2_test.o cc -o $@ $^ ex3_test : ex3.o ex3_test.o cc -o $@ $^ ``` Step 2, realize that these rules all look the same, and replace them with a pattern rule: ``` ex%_test: ex%.o ex%_test.o cc -o $@ $^ ...
This question already has answers here:Closed10 years ago. Possible Duplicate:trying to create a simple shell in c for win32 api I'm doing some C programming in Windows for a low level coding assignment and I'm trying to get this create process to work however. I am try to trying to execute a command as a process...
Since dir is a cmd.exe built in you need to run cmd , ie setlpApplicationNametocmd.exeandlpCommandLineto dir