question
stringlengths
25
894
answer
stringlengths
4
863
I have the following query: ``` SELECT * FROM versions WHERE path LIKE '%/dir1%' ``` that works perfectly fine when executing from sqlite command prompt. However, I am having trouble running this command from a C program. It is a little bit tricky because in sqlite the %Q is used to pass in strings but LIKE also u...
%%is converted to%. Making an answer to get accepted :)
I'm trying to increase a static array by doubling it dynamically in another array as soon as it is maxed. I planed on created new array withmalloc(), then copy values over. Once done, I planned on deleting first array and then pointing first pointer to second? ``` float FirstArray[1]; if (first array is full) { ...
Perhaps you should considerrealloc, as this is exactly why it exists.
I want to specify a color for the space on the screen that is unrendered (right now, where my object ARENT, it is just black). Is there a way I can change this to another color (or even better, a texture?) I am using c if that makes a difference.
I think what you are looking for isglClearColor. Though, I will add that no pixel on the screen is really "unrendered" so what you are wanting to do is set the default value that sits in the buffer until one of your objects renders over it.
I am learning C and I am wondering what I need to add for those values in my WriteFile and ReadFile methods lpNumberOfBytesRead and lpNumberOfBytesWritten ``` WriteFile((HANDLE)sock, "\x05\x01\x00", 3, NULL, NULL); ReadFile((HANDLE)sock, buf, 1024, NULL, NULL); ``` it says in the documentation one of the two NULL v...
Assuming that you are not going to use overlapped I/O, (and from your question, I get a strong feeling that you are not), you need to pass a pointer to aDWORDvariable that will receive the values: ``` DWORD NumberOfBytesWritten; WriteFile((HANDLE)sock, "\x05\x01\x00", 3, &NumberOfBytesWritten, NULL); ``` If the func...
I am working on a game in C using SDL and I created a window with SDL_NOFRAME so I loosed minimize & close native buttons , I added 2 buttons " _ " and " X " onclick " X " quit the game but I couldn't find a solution for Minimize " _ " any idea ?!!
You can useSDL_WM_IconifyWindowto minimize your window. http://www.libsdl.org/cgi/docwiki.cgi/SDL_WM_IconifyWindow
I have a nice C++ function, which supports multiple arguments through va_list + va_start + va_arg. But I had to convert my project to C. After conversion, this va_list construction gets rejected by the compiler (multiple errors). Is there any way to do that thing in C, and (if yes) what I need to change?
The Wikipedia page onstdarghas probably everything you need.
In C, how do you use the value of a variable or a field within a struct as the name of a variable or field within a struct to be used in a program? i.e.: ``` char variable_name[]; struct_x.value_of_variable_name = 1; // assuming the variable struct_x.value_of_variable_name is an int ```
You can't. Variable names exist only at compile-time. You could emulate this behaviour manually by creating a lookup table (that maps a string to a pointer, for instance), but there is no language support for this.
CODE : ``` int *Array[8]; Array[0] = (int *) malloc(sizeof(int) * 5); printf("%d" , sizeof(Array)/sizeof(int)); // Result = 8 : True printf("%d" , sizeof(Array[0])/sizeof(int)); // Result = 1 : False ``` How do I get length of Array[0] that is 5?
You can't. Dynamic arrays in C don't carry around their length information with them. So you'll need to write your code to remember that it allocated something of length 5.
This question already has answers here:Closed11 years ago. Possible Duplicate:Error handling in C codeWhat return value should you use for a failed function call in C? I always use 0, but its not really readable inif,while, etc. Should I return 1? Why main functionreturn 0for success?
It's defined by the C standard as0for success (credits go to hvd). But For greater portability, you can use the macrosEXIT_SUCCESSandEXIT_FAILUREfor the conventional status value for success and failure, respectively. They are declared in the filestdlib.h. (I'm talking about the value returned to the OS frommain,...
This question already has answers here:Closed11 years ago. Possible Duplicate:Why are C character literals ints instead of chars? folks, I tried to print out the size of char in C. With the following code, I got the result output as ``` int, 4 char, 1 char?, 4 ``` Why is the last one not the same as the 2nd one? ...
In C, a character constant like'a'has typeint. This is different from C++ and Java, where a character constant like'a'has typechar,
Code in question first (minimized case): ``` #include <stdio.h> #include <signal.h> int counter = 0; void react_to_signal(int n) { fprintf(stderr, "Caught!\n"); counter++; } int main(int argc, char** argv) { signal(SIGINFO, react_to_signal); while (1) { printf("%d\n", counter); } ...
In short: you cannotsafelyuseprintfwithin a signal handler. There's alist of authorized functionsin signal handler's man page. There is notfprintfin it. That's because this function is notreentrant, mainly because it can usemallocandfree. Seethis postfor a detailed explanation.
here goes the problem: suppose if I want to run a plot.exe in cmd, I wrote the following line in cmd, plot image.jpg BTW I was trying in this way in my c file: system("start plot image.jpg") the above command start the cmd and also the plot command but the image file did not popup. There is an error command: "im...
Probably the process'sworking directoryis not the directory that contains the image. You can either specify the full path to the image: ``` system("plot /full/path/to/image.jpg"); ``` or usechdirto change the working directory before running the command: ``` if(chdir("/full/path/to/") == -1) ; // TODO handle er...
I was compiling/linking my program ``` i386-gcc -o output.lnx func.opc mainc.opc ``` and I kept getting that error. I honestly have no idea what this means. Any clue? thanks,
This is usually a symptom of having too much code or data in the program. The relocation at offset 7 in .text segment (code) has been compiled with a fixed size (2 or 4), but the data/instruction it is referring to is more than 64k or 2G away. Other than that, I can't tell you how to fix it without actually seeing t...
I am working on a project that requires implementation of a fork() in unix. I read freeBSD and openBSD source code but it is really hard to understand. Can someone please Explain the returning twice concept? I understand that one return is pid of a child, and that gets returned to parent and other one is zero and it g...
When you callfork, it returns "twice" in that the fork spawns two processes, which each return. So, if you're implementingfork, you have to create a second process without ending the first. Then the return-twice behavior will happen naturally: each of the two distinct processes will continue execution, only differing...
I have the following query: ``` SELECT * FROM versions WHERE path LIKE '%/dir1%' ``` that works perfectly fine when executing from sqlite command prompt. However, I am having trouble running this command from a C program. It is a little bit tricky because in sqlite the %Q is used to pass in strings but LIKE also u...
%%is converted to%. Making an answer to get accepted :)
I'm trying to increase a static array by doubling it dynamically in another array as soon as it is maxed. I planed on created new array withmalloc(), then copy values over. Once done, I planned on deleting first array and then pointing first pointer to second? ``` float FirstArray[1]; if (first array is full) { ...
Perhaps you should considerrealloc, as this is exactly why it exists.
I want to specify a color for the space on the screen that is unrendered (right now, where my object ARENT, it is just black). Is there a way I can change this to another color (or even better, a texture?) I am using c if that makes a difference.
I think what you are looking for isglClearColor. Though, I will add that no pixel on the screen is really "unrendered" so what you are wanting to do is set the default value that sits in the buffer until one of your objects renders over it.
I am learning C and I am wondering what I need to add for those values in my WriteFile and ReadFile methods lpNumberOfBytesRead and lpNumberOfBytesWritten ``` WriteFile((HANDLE)sock, "\x05\x01\x00", 3, NULL, NULL); ReadFile((HANDLE)sock, buf, 1024, NULL, NULL); ``` it says in the documentation one of the two NULL v...
Assuming that you are not going to use overlapped I/O, (and from your question, I get a strong feeling that you are not), you need to pass a pointer to aDWORDvariable that will receive the values: ``` DWORD NumberOfBytesWritten; WriteFile((HANDLE)sock, "\x05\x01\x00", 3, &NumberOfBytesWritten, NULL); ``` If the func...
I am working on a game in C using SDL and I created a window with SDL_NOFRAME so I loosed minimize & close native buttons , I added 2 buttons " _ " and " X " onclick " X " quit the game but I couldn't find a solution for Minimize " _ " any idea ?!!
You can useSDL_WM_IconifyWindowto minimize your window. http://www.libsdl.org/cgi/docwiki.cgi/SDL_WM_IconifyWindow
I have a nice C++ function, which supports multiple arguments through va_list + va_start + va_arg. But I had to convert my project to C. After conversion, this va_list construction gets rejected by the compiler (multiple errors). Is there any way to do that thing in C, and (if yes) what I need to change?
The Wikipedia page onstdarghas probably everything you need.
In C, how do you use the value of a variable or a field within a struct as the name of a variable or field within a struct to be used in a program? i.e.: ``` char variable_name[]; struct_x.value_of_variable_name = 1; // assuming the variable struct_x.value_of_variable_name is an int ```
You can't. Variable names exist only at compile-time. You could emulate this behaviour manually by creating a lookup table (that maps a string to a pointer, for instance), but there is no language support for this.
CODE : ``` int *Array[8]; Array[0] = (int *) malloc(sizeof(int) * 5); printf("%d" , sizeof(Array)/sizeof(int)); // Result = 8 : True printf("%d" , sizeof(Array[0])/sizeof(int)); // Result = 1 : False ``` How do I get length of Array[0] that is 5?
You can't. Dynamic arrays in C don't carry around their length information with them. So you'll need to write your code to remember that it allocated something of length 5.
This question already has answers here:Closed11 years ago. Possible Duplicate:Error handling in C codeWhat return value should you use for a failed function call in C? I always use 0, but its not really readable inif,while, etc. Should I return 1? Why main functionreturn 0for success?
It's defined by the C standard as0for success (credits go to hvd). But For greater portability, you can use the macrosEXIT_SUCCESSandEXIT_FAILUREfor the conventional status value for success and failure, respectively. They are declared in the filestdlib.h. (I'm talking about the value returned to the OS frommain,...
This question already has answers here:Closed11 years ago. Possible Duplicate:Why are C character literals ints instead of chars? folks, I tried to print out the size of char in C. With the following code, I got the result output as ``` int, 4 char, 1 char?, 4 ``` Why is the last one not the same as the 2nd one? ...
In C, a character constant like'a'has typeint. This is different from C++ and Java, where a character constant like'a'has typechar,
Code in question first (minimized case): ``` #include <stdio.h> #include <signal.h> int counter = 0; void react_to_signal(int n) { fprintf(stderr, "Caught!\n"); counter++; } int main(int argc, char** argv) { signal(SIGINFO, react_to_signal); while (1) { printf("%d\n", counter); } ...
In short: you cannotsafelyuseprintfwithin a signal handler. There's alist of authorized functionsin signal handler's man page. There is notfprintfin it. That's because this function is notreentrant, mainly because it can usemallocandfree. Seethis postfor a detailed explanation.
I'm trying to increase a static array by doubling it dynamically in another array as soon as it is maxed. I planed on created new array withmalloc(), then copy values over. Once done, I planned on deleting first array and then pointing first pointer to second? ``` float FirstArray[1]; if (first array is full) { ...
Perhaps you should considerrealloc, as this is exactly why it exists.
I want to specify a color for the space on the screen that is unrendered (right now, where my object ARENT, it is just black). Is there a way I can change this to another color (or even better, a texture?) I am using c if that makes a difference.
I think what you are looking for isglClearColor. Though, I will add that no pixel on the screen is really "unrendered" so what you are wanting to do is set the default value that sits in the buffer until one of your objects renders over it.
I am learning C and I am wondering what I need to add for those values in my WriteFile and ReadFile methods lpNumberOfBytesRead and lpNumberOfBytesWritten ``` WriteFile((HANDLE)sock, "\x05\x01\x00", 3, NULL, NULL); ReadFile((HANDLE)sock, buf, 1024, NULL, NULL); ``` it says in the documentation one of the two NULL v...
Assuming that you are not going to use overlapped I/O, (and from your question, I get a strong feeling that you are not), you need to pass a pointer to aDWORDvariable that will receive the values: ``` DWORD NumberOfBytesWritten; WriteFile((HANDLE)sock, "\x05\x01\x00", 3, &NumberOfBytesWritten, NULL); ``` If the func...
I am working on a game in C using SDL and I created a window with SDL_NOFRAME so I loosed minimize & close native buttons , I added 2 buttons " _ " and " X " onclick " X " quit the game but I couldn't find a solution for Minimize " _ " any idea ?!!
You can useSDL_WM_IconifyWindowto minimize your window. http://www.libsdl.org/cgi/docwiki.cgi/SDL_WM_IconifyWindow
I have a nice C++ function, which supports multiple arguments through va_list + va_start + va_arg. But I had to convert my project to C. After conversion, this va_list construction gets rejected by the compiler (multiple errors). Is there any way to do that thing in C, and (if yes) what I need to change?
The Wikipedia page onstdarghas probably everything you need.
In C, how do you use the value of a variable or a field within a struct as the name of a variable or field within a struct to be used in a program? i.e.: ``` char variable_name[]; struct_x.value_of_variable_name = 1; // assuming the variable struct_x.value_of_variable_name is an int ```
You can't. Variable names exist only at compile-time. You could emulate this behaviour manually by creating a lookup table (that maps a string to a pointer, for instance), but there is no language support for this.
CODE : ``` int *Array[8]; Array[0] = (int *) malloc(sizeof(int) * 5); printf("%d" , sizeof(Array)/sizeof(int)); // Result = 8 : True printf("%d" , sizeof(Array[0])/sizeof(int)); // Result = 1 : False ``` How do I get length of Array[0] that is 5?
You can't. Dynamic arrays in C don't carry around their length information with them. So you'll need to write your code to remember that it allocated something of length 5.
This question already has answers here:Closed11 years ago. Possible Duplicate:Error handling in C codeWhat return value should you use for a failed function call in C? I always use 0, but its not really readable inif,while, etc. Should I return 1? Why main functionreturn 0for success?
It's defined by the C standard as0for success (credits go to hvd). But For greater portability, you can use the macrosEXIT_SUCCESSandEXIT_FAILUREfor the conventional status value for success and failure, respectively. They are declared in the filestdlib.h. (I'm talking about the value returned to the OS frommain,...
This question already has answers here:Closed11 years ago. Possible Duplicate:Why are C character literals ints instead of chars? folks, I tried to print out the size of char in C. With the following code, I got the result output as ``` int, 4 char, 1 char?, 4 ``` Why is the last one not the same as the 2nd one? ...
In C, a character constant like'a'has typeint. This is different from C++ and Java, where a character constant like'a'has typechar,
Code in question first (minimized case): ``` #include <stdio.h> #include <signal.h> int counter = 0; void react_to_signal(int n) { fprintf(stderr, "Caught!\n"); counter++; } int main(int argc, char** argv) { signal(SIGINFO, react_to_signal); while (1) { printf("%d\n", counter); } ...
In short: you cannotsafelyuseprintfwithin a signal handler. There's alist of authorized functionsin signal handler's man page. There is notfprintfin it. That's because this function is notreentrant, mainly because it can usemallocandfree. Seethis postfor a detailed explanation.
I have a variable type: ``` char (*p)[12] = calloc(n, sizeof(*p)); ``` I need the variable to stay this way, but I am having trouble passing it as a parameter due to the function type giving me errors: ``` void myMethod(char *p) { ... } ``` What can I use in myMethod as the parameter to make this work?
What can I use in myMethod as the parameter to make this work Possibly this: ``` void myMethod(char (*p)[12]) ```
I am callingexecvin my C code to launch an executable, but I want to set its working directory to something custom. For example, in one case, I am launchingls, but it lists the files in my original program's directory. But I want to set the working directory to something custom. How will I achieve it, such that, I'll...
Usechdir(2)after a successfulfork(2), before execing: ``` switch (fork()) { case 0: chdir(newpath); execvp(...); break; } ```
When the signal is delivered, the signal handler is executed on the stack of the process. If SA_ONSTACK is used insigaction(), then a different stack is used. What is the use of using different stack? Any use case example?
One use of an alternate stack is to try and handleSIGSEGVproperly. If your process just received aSIGSEGVbecause it exceeded its stack limit, you can't run the signal handler on the process's stack - it's full already. Having an alternate stack allows you to (carefully) run some more or less graceful shutdown in that...
I'm getting the following error when running a simple OpenAL program: AL lib: pulseaudio.c:612: Context did not connect: Access denied Interestingly, if I try playing audio then it plays correctly, although it sounds slightly distorted. Below is the code that produces the error. It also happens if I initialize with...
I fixed it by changing/etc/openal/alsoft.conf(I'm using Arch Linux) to this: ``` drivers=alsa,pulse ``` The default checks Pulse first, which I didn't have installed. Installing Pulse should fix it too.
I got the following code: ``` int main(int argc, char *argv[]) { char c = 128; c = c >> 1; printf("c = %d\n", c); return 0; } ``` Running the above code onWindows XP32 bit, I got the result:-64. Why-64?
Because thechartype is a signed 8-bit integer (in the implementation of C that you are using). If you try to store the value 128 in it, it will actually be -128. The bits for that would be: ``` 10000000 ``` Shifting a negative number will keep the sign bit set (as your implementation uses an arithmetic shift): ```...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. I am learning C language and got th...
Ifintis 16-bit, it means there are2^16different values. Of these,2^15 (= 32,768)(half) are negative,2^15 - 1 (= 32,767)are positive and the last one is0. The same reasoning can be used for 8-bit, 32-bit or any other size of integer. For floating point numbers (float and double), the how the range isexplained on Wiki...
I have a program (main.c) that calls an external assembly function (function.s). Themain.cdeclare and use the assembly function: ``` extern int function(int n); res = function(3); ``` It works: ``` > gcc function.s main.c -o test ``` But, how can I have to configure Netbeans to build and debug it? Thanks in adva...
Perhaps an issue for copying the code. Writing from scratch works well. That's all
// screen.h ``` #ifndef screen_h #define screen_h #define MAC 1 #define WIN 2 #define LNX 3 #ifdef PLATFORM # undef PLATFORM #endif #define PLATFORM MAC void screen_init(); #endif ``` // screen.c ``` #include <string.h> #include <stdlib.h> #include "screen.h" #if PLATFORM == MAC #include <curses.h> v...
ISO/IEC 9899:TC2 - 6.2.1.2:A function prototype is a declaration of a function that declares the types of its parameters. An empty argument list in a function declaration indicates that the number and type of parameters is not known. You must explicitly indicate that the function takes no arguments by using thevoidke...
I started a blank project inVisual Studio 2010to write a C application. How can I send debug information to theOutputwindow (menuDebug->Windows->Output)? Is there a relatively simple way to implementTRACEorOutputDebugStringor something similar?
You can useOutputDebugStringfrom a VS C program. ``` #include <windows.h> int _tmain(int argc, _TCHAR* argv[]) { OutputDebugString(_T("Hello World\n")); return 0; } ``` The output will only be visible if you run with debugging (Debug > Start Debugging) In the Output window, select "Debug" for "Show output ...
Is it possible to usefcntl()inside a function other thanmain()? Does the file get unlocked after calling it ? I say this because in this casefcntl()and most everything else insidelockfile()are out-of-scope when the functionreturns. ``` int lockfile(void){ int fd; const char *path = "path-to-lockfile"; st...
Thefcntlcall places a lock on the file. It remains until the file is closed or the lock is released. The structures are only needed to tellfcntlwhat to do.
How to Insert and then print data from jagged array in below code ? ``` int *jagged[5]; jagged[0] = malloc(sizeof(int) * 10); ```
You can insert by adding a second subscript for the nested array's index. ``` int i; for (i = 0; i < 10; ++i) jagged[0][i] = some_value; ``` and print like ``` int i; for (i = 0; i < 10; ++i) printf("%d\n", jagged[0][i]); ``` Keep in mind that you need to keep track of each nested array's length on your ow...
i want to get matrix values, rows and coloumn from user input. So i'm implementingdo whileto do this: This is only for the rows: ``` do { printf ("Inserisci il numero di righe ( intero-positivo-diverso da 0): "); scanf ("%d",&righe); } while (righe<=0); ``` I want to check that user insert only i...
scanfreturns an integer indicating how many "things" it successfully read. You can test this in a conditional to see if it got what you were looking for. Example: ``` const int result = scanf ("%d",&righe); if (1 != result) { /* didn't get the 1 input we were looking for, do something about it! */ } ``` You'll wan...
I have a simple UDP socket program in C. The client transmits data to the server and receives acknowledgements. I already know how to configure a timeout so that if 'recvfrom()' doesn't receive anything in a certain period of time the alarm goes off. HOWEVER, there are a few more situations I need to handle. What if ...
Look intoselect(2)andpoll(2)- you can wait on a socket for a specified amount of time. You can then restart the wait with lesser timeout if you need. If you are on linux, look intoepoll(7)andtimerfd_create(2).
I ran the following code in codeblocks and got the output:10 2010 20 ``` int main() { int i=10,j=20; printf("%d %d\n",i,j); printf("%d %d",i); return 0; } ``` What is the reason of second 20 ?
Since you're callingprintfa second time with no intervening code, the value ofjis still on the stack, left from the previous call. Of course, you shouldn't depend on this behavior. Just because you don'tseethe bug doesn't mean it's not there. :-)
I'm trying to compare two strings, and even though they look the same, I wasn't getting a match. Turns out one string contains \n. So my question is, is a way to check if a string contains '\n'? I'm using the strcmp function; ``` char *tempData; char *checkThis; tempData = "Hello \n"; checkThis = "Hello"; if(strcmp...
You could strip the white-space before comparing, then you do not require a check for '\n'. But instead you can just compare the strings, assuming that is what you want to do. This questionhas some answers on how to do that in C.
Gretings, I have cross compile, OpenSSl , libssh2 and finally cURL, Don't know why it has generated only static library. Anyway I tried to run sample ftpget.c program by linking all the three libraries but I am getting the following error : ``` .../libcurl.a(timeval.o): In function 'curlx_tvnow': timeval.c:(.text+0x...
Try linking with librt (-lrt).
Sorry for the probably basic question, but I'm trying to understand some code and I can't understand what this (%016llx) placeholder means. I understand that %x is HEX coding, and to the best of my knowledge the numbers in between should be the number of digits and the0padding; but I cannot decode the016llsequence, a...
Thedescription offprintf()in the C99 Standardtells us that the%016llxconversion specification is made up of the mandatory%charactera0flag for paddingthe16as "minimum field width"thellas "length modifiers"thexconversion specifier So, in whole it means to write aunsigned long long intin hexadecimal notation occupying ...
I am trying to launch an android applications from native code. In adb shell we can launch applications using "am" command. Link: How to run (not only install) an android application using .apk file? Is there any way to invoke this "am" command through C code? I tried the following line but exec is returning -1: ...
I got the answer... I 'exec'ed the shell itself and gave it the command... It worked ``` ret = execl("/system/bin/sh", "sh", "-c", "am start -a android.intent.action.MAIN -n com.android.browser/.BrowserActivity", (char *)NULL); ``` Thanks to m0skit0, Padma Kumar, Yuri ...
I have python code with C libraries, I use SWIG to plug it all together. I would like to profile the C libraries. I compiled them with-pgbut no profiling output is generated... Is there method to profile such a mixed code?
You can useValgrindwith theCallgrindmodule (built-in). This will produce a file that can be displayed in KCacheGrind, which is avaliable on most Linux distributions. To limit profiling to just your code, use thelimiting collection options, this will allow Python to run at almost full speed, and only profile your code...
I see some physical address structure is defined like this: ``` typedef union { struct { ULONG LowPart; LONG HighPart; } u; LONGLONG QuadPart; } PHYSICAL_ADDRESS; ``` I don't understand why the high part is defined as signed type... Can anyone give an explanation?
The number is signed to make math on it make more sense. If you subtract the address 123 from 456, you expect to get the address 333, right? So if you subtract 456 from 123, you expect to get -333, not 18,446,744,073,709,551,283, right? That's why addresses are signed. The reason only the high part is signed is that ...
I've read that the ideal size of a structure for performance, that's going to be used in a large collection, is 32 bytes. Is this true and why? Does this effect 64bit processors or is it not applicable? This is in context of modern (2008+) home Intel-based systems.
The ideal size of a struct is enough to hold the information it needs to contain.
I am actually very new to C, but for a project, I'd like to be able to calculate the value of Pi from 1 million to at least 32 million decimal places. Basically, like what SuperPi/HyperPi does for benchmarking a CPU. But obviously, the standard C library is incapable of this. What library can I use, and what algorit...
I'v used the quadratic algorithm fromtherewith success. I'd suggestMPFRfor the library part.
Say we have, ``` typedef struct{ char* ename; char** pname; }Ext; Ext ext[5]; ``` What I am trying to do is to populate the data as following: ``` ext[0].ename="XXXX"; ext[0].pname={"A", "B", "C"}; // and so on for the rest of the array ``` -- I am pretty sure this is not the right way of doing this beca...
The first assignment is correct. The second one is not. You need to dynamically allocate the array: ``` ext[0].pname = malloc( sizeof(char*) * 5 ); ext[0].pname[0] = "A"; ext[0].pname[1] = "B"; //and so on //you can use a loop for this ```
I am trying to port some C which uses read() and write() functions for sending sockets. I am trying to port this to windows and it is suggested (from what I have read) to use WriteFile and ReadFile to accomplish my task. I read according to Microsoft API documentation that WriteFile will accept a socket. But I am uns...
WriteFilewants a handle, not a pointer to a handle. You probably want to use: ``` WriteFile((HANDLE)sock, data, 17, NULL, NULL); ```
I find that there is no nativebooltype. People either useintorchar- though it seem thatintmight be more frequently used thanchar? Is this true? My first impulse was to usecharas it is a smaller data type, but there something I've missed? Isintbetter for boolean values, and if so - why?
There is a_BoolinC99, and aboolif you includestdbool.h. If you don't have it (a decently modern compiler), useint, it's usually the fastest type. The memory savings of usingcharare likely negligible.
I'm trying to learn a bit or 2 about process communication under Linux, so I wrote 2 simple C programs that communicate with each other. However, it's a bit annoying to have to run them manually every single time, so I'd like to know is there a way to make a program that will run them both, something like this: ``` ...
run.sh script ``` #!/bin/sh ./program1 & ./program2 & ``` run command: ``` $sh run.sh ```
A few years ago, when I was on my degree, my teacher told me that if I make a infinite loop in C it would crash my computer making it to use all processor resources with nothing and I need to reboot my system to make things good again. Today I tested the same situation on my Windows Seven computer and I saw that my co...
An infinite loop will only "crash" the OS if the OS doesn't support preemptive multitasking. In any decent OS the scheduler will make that process take a break once in a while and allow other stuff to run. At any rate, if the resource usage is low, look at the generated code - the compiler might have done something s...
I'm trying to compile example from GnuTLS. I can compile GnuTLS with no problem. I usually use this command when I have default GnuTLS package installed. I compile the example with this commend. ``` gcc -o server ex-serv-srp.c -lgnutls ``` I build GnuTLS from source. I can compile the example with the same command...
For a permanent solution add/usr/local/libto/etc/ld.so.confand rerunldconfig, otherwise do as zvbra proposes.
I'd like to add some debugging code to an abstraction ofpthread_cond_waitin my code to check that the calling code really holds the mutex, as it should. This is to check correctness of the rest of the callers. Is there a way to check if the mutex is locked, or enable a debug mode in the pthreads implementation (on Li...
If you create the mutex as an error-checking mutex, using: ``` pthread_mutexattr_t attr; pthread_mutex_t errchkmutex; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); pthread_mutex_init(&errchkmutex, &attr); ``` ...thenpthread_cond_wait()will returnEPERMif the mutex is not ...
I created a 2d array of structures and now I want to assign values to x, y, and z. Any ideas where the segmentation fault is coming from? ``` struct xyz { int x; int y; int z; }; char buf[80]; struct xyz array[width][height]; for(row=1;row<=width;row++) { for(col=1;col<=height;col++) { ...
Arrays start from0in C. You're stepping outside the allocated space since you're accessingarray[width]. Perhaps you want: ``` for(row = 0; row < width; row++) ^ ^ ``` Remember, if you declaretype array[LENGTH], it's never valid to touch the elementarray[LENGTH].The last valid element isLENGTH - 1.
This is a beginner question, but please bear with me. I'd like to pass in a char* to a function, and have it populated, with the contents of multiple existing strings. Here's what I have (and doesn't work) ``` int func(char *out) { int i; int x = 10; int y = 10; char array[x][y]; out = malloc(x *...
Achar*is just a pointer, passing it in doesnt let you pass a new one back out again. You need to pass achar**like so: ``` void get_name( char** ppname ){ char * pname = strdup("my name is fred"); *ppname = pname; } ``` You then feed the function somewhere to put the pointer like so: ``` char * name; get_name( &...
I'm reading a C code that do char * buf = malloc(sizeof (char *) * 16) instead of char buf[sizeof (char *) * 16] what's the difference? well, I think the first expression unnecessary, ifrealloc()is not called, or am I wrong thinking?
char buf[sizeof(char*)*16]is an array allocated automatically, which is generally the stack. It is valid as long as buf is in scope, and there is sufficient stack space. mallocallocates memory from some heap. It is valid until this memory isfree()ed. Generally, there is much more heap available.
I know there are similar questions answered but I did not find the answer I am looking for. Is there any short and simple way of converting an integer(1digit) to char? Something similar to how we do it with char to int, just by adding+'0'
Assuming you are asking how to go from'9'to9, just apply the inverse operation, i.e., subtract'0': ``` char digit= value + '0'; int value= digit - '0'; ```
I have a MATLAB code which I have to convert to C language. According to the MATLAB code, ``` n1 = 11; x1 = randn(2,n1) + repmat([-1 1]’,1,n1); w = [0 0]’; ``` here acccording to my calculation, the output of ``` w’*x1 ``` will be a 1x3 matrix, that is a row vector as far as I know. Then what will be the output o...
Like many MATLAB functions, theexpfunction operates element-wise when applied to arrays. For further details, please refer tothe documentation.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. In Matlab, what would be the output...
This is what you get: v = [ 1 2 3 4] ``` v = 1 2 3 4 ``` b = [2 2 2 2]' ``` b = 2 2 2 2 ``` v + b ``` Error using + Matrix dimensions must agree. ```
In C, if I have a tree or linked list, I have to declare a function for insertion like ``` insert(Node ** node) ``` so I can insert a new root/head.My question is, how to write it with references in C++?
You would write the function as ``` ReturnType insert(Node* &node) ``` That is, the parameter is a reference to theNode*variable holding the root of the tree. From there, you would proceed as usual, except that compared with the C version of the function you wouldn't need to dereferencenodeto reassign the root For...
I currently have something of the form ``` char** args = { "a", "s", "d", "f" }; ``` What I want is ``` char** newArgs = { "s", "d", "f" }; ``` What's the easiest way to do this? Thanks.
Perhaps this: ``` newargs = args + 1; ``` Or maybe: ``` newargs = &args[1]; ```
I am following a tutorial onhttp://www.corelan.be/index.php/2009/07/19/exploit-writing-tutorial-part-1-stack-based-overflows/to learn more about exploits. The scripts shown are in perl and I wanted to write it in C I'm having trouble finding a function similar to "\x41" * 10000 in C. I looked around and found memset t...
Use ``` memset(junk, 'A', sizeof(junk)); ``` In C, there is a huge difference between single quotes'and double quotes". Single quotes are used forcharvalues, and double quotes are used for string (multiple character, orconst char *) values.
Let's suppose that in my OS exists N file descriptors. How many file descriptors will OS have after executing the code below: ``` int fd = dup(oldfd); ``` How about : ``` int fd = dup2(oldfd,newfd); ``` Thanks!
Its given in man pages. You'll haveN+1file descriptors after calling either one of them. ``` From manpages ... dup and dup2 create a copy of the file descriptor oldfd. After successful return of dup or dup2, the old and new descriptors may be used interchangeably. dup uses the lowest-numbered ...
In my case, product of two INT_MAX numbers is296447233, which is incorrect. ``` long long int product = 0; product = 2137483647 * 2137483647; printf("product: %lli\n", product); ``` What I am doing wrong, and how to correct it ?? Thanks !
Both of your2137483647are of typeint. So they stay that type and overflow. Make themlong longs: ``` product = 2137483647LL * 2137483647LL; ``` or cast: ``` product = (long long)2137483647 * 2137483647; ```
Fromthe example of hooking C++ methods with MobileSubstrateI found this: ``` void (*X_ZN20WebFrameLoaderClient23dispatchWillSendRequestEPN7WebCore14DocumentLoaderEmRNS0_15ResourceRequestERKNS0_16ResourceResponseE) (void* something, void* loader, unsigned long identifier, void* request, const void** response); ``` W...
C++ mangles names of symbols emitted to the binary, to distinguishvoid foo(int)andvoid foo(double). Also, on many platforms, it needs to encodeX::Ysomehow to make it an alphanumeric string. This adds the extra characters and is platform dependent.
I tried using atoi but I can only get to the 500 that way. Not sure where to go from here.
You can usestrtolto "tokenize" a chain of whitespace-separated integers: ``` int a, b; char src[] = "500 600"; char *tmp = src; // The first call to strtol parses 500 a = strtol(tmp, &tmp, 10); // The call looks the same, but tmp now points at the space between 500 and 600 // The next call to strtol skips the space, ...
This question already has answers here:Closed11 years ago. Possible Duplicate:In C arrays why is this true? a[5] == 5[a] Is this instruction correct in c : 5["abcdef"] If yes, what does it mean ? I had this question in a c test.
Yes, it is correct, and means the same as"abcdef"[5], which evaluates to'f'. It is becausea[b] == *(a+b) == *(b+a) == b[a]by definition.
This question already has answers here:Windows: How to create custom appcompat shims (Application Fixes)?(5 answers)Closed9 years ago. This blog postmentions how to create your own shims. What I don't understand is: When a newer version of a DLL comes out (with more exported functions), wouldn't this technique brea...
This isn't the only way to do it. The easiest solution is probably to useDetours, though the free version is 32-bit only and for non-commercial use, and the paid version is seriously expensive. This articledescribes a bunch of methods of doing it yourself.
Can fragment shader in OpenGL ES 2.0 change the Z value (depth) of a pixel? How is this achieved in OpenGL ES 2.0?
No --gl_FragDepth(which is part of the desktop version of GLSL) is not present in OpenGL ES. You can, however, check for the existence ofGL_EXT_frag_depth. If it's available, then you can write the depth togl_FragDepthEXT. Theextension papergives more details about how to enable the extension and such.
is it possible to overlay %d on the screen using opencv? CvPutText() was tried but that cant be done
Let's pretend I didn'texplained to you in a comment before. ``` int number = 5; char text[255]; sprintf(text, "Score %d", (int)number); CvFont font; double hScale=1.0; double vScale=1.0; int lineWidth=1; cvInitFont(&font,CV_FONT_HERSHEY_SIMPLEX|CV_FONT_ITALIC, hScale,vScale,0,lineWidth); cvPutText (img, text, ...
Could someone tell me is there is a way to retain the correct size of the arrays when looking them up in the LOOKUP array? I have a felling it is impossible due to C losing the information as soon as you treat the array as an int pointer. ``` const int NUMBERS1[] = {1, 2, 3, 4, 5 }; const int NUMBERS2[] = {1, 2, 3, 4...
No,sizeofis correct.LOOKUP[0]is of typeint*andsizeof(int*)is 4 on your system. I have a feeling it is impossible due to C losing the information as soon as you treat the array as an int pointer. That is correct. You have to keep track of the length.
a friend of mine gave me a piece of his software and I'm trying to compile it on Ubuntu 11.04.Now gcc says thatev.his not installed and I thought you could tell me where to get it because I did not find it by myself.
libev? If so, you'd need to install the libev-devUbuntu package.
Using XCode 3. I know there's an option preferences > debugging > On Start: show console. This automatically brings up aseparateconsole window. Is there anyway to attach the console window so, say, it appears below code C code I'm currently working on? Help appreciated.
Switch to All-In-One mode of Xcode from it's preferences (it's possible, when all project windows are closed). After that you will have normal/debug mode switch and in debug mode will be able to see watch & console sections at the bottom.
I need help to clear my concepts. I have a function which toggle the Led status on/off after every second. Now the code for the on/off runs inside infite loop. Example: ``` void ToggleLed( int pin_number) { // some code while(1) { // code to execute the Led status ...
Yes you will need a separate thread, or some other form of asynchronous execution. Once you enter that while loop, no other code runs in that thread. Ever.
I'm using OpenSSl to encrypt and decrypt files based on CMS/SMIME. Normally I load certificates withrcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);but this is only for PEM formatted files I guess. I haven't found anyder.hheader or something similar. So is there a way in OpenSSL to load DER formatted certificates? I'v...
DER is indeed encoded using ASN.1, and thed2i_*()family of functions is the way to load a DER file.
How do the C stream system works? For example, the code: ``` FILE *f; // opens f... fputc(f, "x"); ``` will do different things, depending on how 'f' was open. If 'f' was open as a file, a character will be written in that file. If 'f' was open as a memory stream, a char will be written in the memory, and possibly ...
The open function stores that information inside theFILEstructure thatfpoints to. It's pure C, though the low-level code to do the writing to the file will be platform-dependent.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. I want to build a code which given ...
Note that "reachability" on IP networks is kind of tricky to test for. It's perfectly possible that a server machine is running any number of real services (www, ftp, whatever), but has been configured not to reply to pings sincesome people do that. If possible, it's better to just connect like the real service you ...
I read about the removing of border from this GTK widget (you can see it in this imagehttp://developer.gnome.org/gtk/2.24/scrolledwindow.png) in Python or C# remove border of a gtk.buttonHow to remove frame (or border?) form a GtkScrolledWindow How to do that if I'm working in ANSI C? How can I set the "famous" bord...
I think I figured out by myself. My scrollable window isscrollable_component, the trick is to get its child, that's the viewport, and set its shadow property. ``` gtk_viewport_set_shadow_type(GTK_VIEWPORT(gtk_bin_get_child(scrollable_component)), GTK_SHADOW_NONE); ```
When we are passing a string to the strrev function, which is provided by Microsoft, and has the function prototype in string.h. It reverses the string we are passing to it and returns the same address back. First thing - should it modify the original char array? Second thing - When it is modifying the same pointer w...
First, yes, it should modify the original array. That's its sole purpose. Second, yes, it should return the pointer to the array. There's nothing else useful for it to return, and sometimes getting the pointer back makes the code more compact, saving the need for a temporary if the parameter passed tostrrevisn't alre...
Kindly bare if the question is very basic. ldd command displays the dependent libraries over the executable file is what i know. In executable file, where these information is kept?.
This is stored in the.dynamicsection of theELFexecutable. SeeELF-64 Object File Format, starting on page 14 (Dynamic Tables): Dynamically-bound object files will have aPT_DYNAMICprogram header entry. This program header entry refers to a segment containing the.dynamicsection, whose contents are an array ofElf64_...
I've problem with binding current date. I want to usedatetime('now')function as one of inserted value. I've used something like this: ``` sqlite3_bind_text(stmt, i + 1, values[i], -1, SQLITE_STATIC); ``` wherevalues[i]ischar * text = datetime('now'). But obviously it inserts that text. Is there possibility to bind ...
Binding, by definition, nicely escapes everything and makes sure everything is a string that the SQL interpreter doesn't actually misread as an SQL component. It's a data safety issue. Instead, make yourstmtvariable put the datetime('now') directly where it should be in the original SQL expression. IE, remove the re...
``` #include <stdio.h> #include <stdlib.h> int main() { char *str="Helloworld"; printf("%d",printf("%s",str)); return 0; } ``` output of this program is Helloworld10 instead of Helloworld1from where that miscellaneous zero comes
Why would you like the program to writeHelloworld1? What should that 1 come from?the return value of functions of theprintffamily is the number of characters outputted(except the final\0for the variants likesprintf).Helloworldhas length 10.
I am rewriting a c program which was used to linux, now I'll reused it on windows, I write a bat file. I run this file as administrator, then error occurs: syslog.h:No such file or directory. Could you please give me some advices? thx.
Probably the program you are porting to windows uses the syslog(3) function call (in addition to openlog and closelog). These are defined in syslog.h on unix. Windows does not have these, so you can do the following: Remove syslog.h and these function calls from the code.Create a syslog.h and implement these calls or...
I take a string like "abcd" as a command line argument in my java code. I need to pass this string to my C JNI code which should take this string and use it as a shared memory identity. I am looking to know how and where I can make this string to be representing a hexa value.
Java or C? In C, you usestrtoul: ``` #include <stdlib.h> int main(int argc, char * argv[]) { if (argc > 1) { unsigned int n = strtoul(argv[1], NULL, 16); } } ``` Check the manual; when parsing user input it's vital to check for errors, and there are several aspects to this when usingstrtoul.
This question already has answers here:What's the best way to check if a file exists in C?(8 answers)Closed5 years ago. I'm attempting to open a file in a C application. How do I check that a file exists before trying to read from it?
Try to open it: ``` FILE * file; file = fopen("file_name", "r"); if (file){ //file exists and can be opened //... // close file when you're done fclose(file); }else{ //file doesn't exists or cannot be opened (es. you don't have access permission) } ```
I use MPI library for C and I would like to know is it possible to call the MPI collective communication methods from different parts of code by different processes? Pseudo Example: ``` MPI_Rank(&rank,MPI_COMM_WORLD); switch(rank) { case 0: MPI_Bcast(buf1,count, type, 0, comm); break; case 1: MPI_B...
It can be called from different parts of the code, but you must make sure that all processes in the communicator actually callMPI_Bcastto avoid deadlocking. This might be slightly more difficult to ensure if all processes follow different execution paths.
I want to create secure server and client which use GnuTLS for encrypting the network communication. I want to deploy the clients on many Unix operating systems and many Linux distributions. I found that for example in Centos 5 and 6 the versions of GnuTLS which are by default installed are different versions. Maybe i...
No, because POSIX does not specify binary compatibility, only source compatibility. You'll have to (cross-)compile GNU TLS for every OS you're targeting that does not have the required version.
I am trying to build an appliction based upon the pcredemo application. When I try and compile the application in Windows I get the following compiler errors. ``` undefined reference to `_imp__pcre_compile'| undefined reference to `_imp__pcre_exec'| undefined reference to `_imp__pcre_free'| ``` Am I missing some .dl...
Those are linker errors. You need to make sure that you are passing the PCRE .lib files to the linker. Another possible problem could be that your compiler/linker is using a different .lib file format from that used to build the PCRE .lib files.
I'm trying to match a pattern and this keeps failing (return 1): ``` fnmatch(findme, d_name, FNM_PATHNAME) ``` when findme= "cproject", d_name="./.cproject" Also in gdb debugger I tried this: ``` //in gdb p fnmatch("f","fa",0x10) ``` returns 1. If match "f" and "f" it returns 0 (match).
f only matches f. You need f* to match fa.