question
stringlengths
25
894
answer
stringlengths
4
863
Is it possible to tell GCC to compile the source code, and ignore macros like__FILE__,__LINE__, etc, etc, or redefine them to expand into let's say - an empty string?
As with any macro you can just use: ``` #undef __LINE__ #undef __FILE__ ``` and then you can redefine them. You can also pass-U macronameto undef a macro name and-D macroname=definitionto define a macro name to thegccoptions. Note that, as indicated in another answer, undefining or redefining__LINE__or__FILE__in C...
I want to allocate some memory on the heap that is not reachable from any stack pointer. (This is for test purpose). ``` void *ptr = malloc(sizeof(int)); void *ptr2 = malloc(sizeof(int)); ptr = ptr2; ``` If I do this code, I think that ptr and ptr2 at the start is two pointers on the stack referring to some allocat...
That works. It's more complex than necessary, though: ``` malloc(4); ``` The easiest way to leak memory is to just not save a reference to it in the first place.
I was testing some code and here is a strange thing I found: ``` #include<stdio.h> void main() {int m,n; for(m=0, n=0; m<0,n<4; m++,n++) printf("hello\n"); } ``` My guess was that it wouldn't do print because the conditionm<0isn't satisfied. But I was shocked with this: Output ``` hello hello hello hello ``` ...
In C (and many other languages), the comma operator is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns the result of the 2nd operand. Socond1, cond2evaluates both conditions but onlycond2matters. If you want both conditions to be satisfied...
I'm thinking how can I assign a string value to a row in a 2*2 character array in C? this can be done in java like this: ``` char [][] array = new char[10][10]; array[1] = "foo".toCharArray(); ```
In C, you can't "assign" to an array. You can, however,copya string literal (or any string) into the array. You just need to make sure that you don't cause buffer overflows: ``` char arr[10][10]; const char *str = "foo"; if (strlen(str) < sizeof(arr[1])) { strcpy(arr[1], str); } ``` Alternatively, you can assig...
This question already has answers here:How to escape the % (percent) sign in C's printf(13 answers)Closed9 years ago. I have tried escaping it using a backslash. ``` #include <stdio.h> int main(void) { printf("\%"); return 1; } ``` But it doesn't work. What is the correct syntax?
Two percentage signs: ``` printf("%%"); ```
InC, I can autoconnect signals with this code: ``` gtk_builder_connect_signals (builder, NULL) ``` How to do this inC++withGTKmm?
You cannot useGladeto connect your signals when usinggtkmm, you need to do that manually. ``` Glib::RefPtr builder = Gtk::Builder::create_from_file("glade_file.ui"); Gtk::Window *window1 = 0; builder->get_widget("window1", window1); Gtk::Button *button1 = 0; builder->get_widget("button1", button1); ...
As some DOS application, how to display a pull-down menus in C with ASCII? (and can be controlled by arrow keys) like this: ``` +-------------------- +-------------------- | File | Edit | Help ... | File | Edit | Help ... +----------+--------- +------+----------+-- | New (N) | ...
I would suggest using a library like ncurses. Doing this from scratch is pretty tough, but, if you really want, you need to use a lot of printf's and functions to write a character at a certain position. Here you will find more ncurses alternatives for windows:NCurses-Like System for Windows
I Have 3 files: main.c lists.c lists.h main.c includes lists.h i want to make a makefile, i run it from the terminal but it seems like it only creates the objects and doesn't run them. What am i doing wrong? (Sorry if it seems like a retarded question): ``` CC=gcc CFLAGS=-Wall maman21: main.o lists.o main.o: mai...
Your rules compiles and links the maman21 executable. You can run it manually after it succeeded with the command./mman21 If you want the makefile to run the program when it's compiled, make a rule for that, ``` CC=gcc CFLAGS=-Wall runit: maman21 ./maman21 maman21: main.o lists.o ``` ... Note that the line...
I have a small RTOS which does not useglibcand I have written own functions (e.g.tolower) in string.c When compiling I am getting the error: ``` common/string.c:11:6: error: conflicting types for built-in function ‘tolower’ [-Werror] ``` Is there a CFLAGS to fix this? Update Answer: use -fno-builtin
toloweris a function from the C library and its identifier is a reserved identifier for use as an identifier with external linkage, even if you don't include the header where it is declared. You could get rid of the warning by using-fno-builtinbut the best is simply to chose another name fortolower. (C99, 7.1.3p1) "...
Why is the second line of the following code throwing a C error : lvalue required as left operand of assignment ``` if (!str_cmp( type, "obj")){ if ( ((OBJ_DATA*) tar = get_obj_here( NULL, room, target)) == NULL){ bug("prog_destroy: obj target not found.", 0); return; } else{ list = (OB...
You cannot cast on the LHS of an assignment. I.e.(OBJ_DATA*)tar is not allowed on the second line. You can try declaringOBJ_DATA * tar = NULL;then using it as ``` tar = get_obj_here( NULL, room, target) ``` or ``` tar =(OBJ_DATA*) get_obj_here( NULL, room, target) ``` depending on whatget_obj_here()returns.
Hello i'm beginner in C programming. I'm making program that should crawls though elements of a string, the string is input from the user. The problem is that I need the size of the characters in the string I have try a lot of thing none of them worked. ``` for(int i = 0; i <= cUserInput; i++){ if(&cUserInpu...
Use the functionstrlen(const char* str)to get a strings' size. It will count the characters until theNULterminator. See reference here:http://www.cplusplus.com/reference/cstring/strlen/ NOTE: to use it you have to include the header"string.h"
I have a 2D array. ``` int MARIO[4][4]; ``` I want to show the values of this array on the screen. The problem is that I don't know how to declare a pointer to a 2D array. Can anyone help?
Ugh, so to answer theactualquestion:int (*ptrTo2DArr)[4][4];
If i have a structure say "apple", so is there a way to check whether a particular element say "color" exist inside the structure? ``` struct apple A{ char color; int pack; } ``` The function which uses this may be knowing the internals of this structure other than its name.....
The only way to do this in C is to use the particular field you are interested in. If the program compiles then it exists. If not, than it either does not or you have other errors.
I have a small RTOS which does not useglibcand I have written own functions (e.g.tolower) in string.c When compiling I am getting the error: ``` common/string.c:11:6: error: conflicting types for built-in function ‘tolower’ [-Werror] ``` Is there a CFLAGS to fix this? Update Answer: use -fno-builtin
toloweris a function from the C library and its identifier is a reserved identifier for use as an identifier with external linkage, even if you don't include the header where it is declared. You could get rid of the warning by using-fno-builtinbut the best is simply to chose another name fortolower. (C99, 7.1.3p1) "...
Why is the second line of the following code throwing a C error : lvalue required as left operand of assignment ``` if (!str_cmp( type, "obj")){ if ( ((OBJ_DATA*) tar = get_obj_here( NULL, room, target)) == NULL){ bug("prog_destroy: obj target not found.", 0); return; } else{ list = (OB...
You cannot cast on the LHS of an assignment. I.e.(OBJ_DATA*)tar is not allowed on the second line. You can try declaringOBJ_DATA * tar = NULL;then using it as ``` tar = get_obj_here( NULL, room, target) ``` or ``` tar =(OBJ_DATA*) get_obj_here( NULL, room, target) ``` depending on whatget_obj_here()returns.
Hello i'm beginner in C programming. I'm making program that should crawls though elements of a string, the string is input from the user. The problem is that I need the size of the characters in the string I have try a lot of thing none of them worked. ``` for(int i = 0; i <= cUserInput; i++){ if(&cUserInpu...
Use the functionstrlen(const char* str)to get a strings' size. It will count the characters until theNULterminator. See reference here:http://www.cplusplus.com/reference/cstring/strlen/ NOTE: to use it you have to include the header"string.h"
I have a 2D array. ``` int MARIO[4][4]; ``` I want to show the values of this array on the screen. The problem is that I don't know how to declare a pointer to a 2D array. Can anyone help?
Ugh, so to answer theactualquestion:int (*ptrTo2DArr)[4][4];
If i have a structure say "apple", so is there a way to check whether a particular element say "color" exist inside the structure? ``` struct apple A{ char color; int pack; } ``` The function which uses this may be knowing the internals of this structure other than its name.....
The only way to do this in C is to use the particular field you are interested in. If the program compiles then it exists. If not, than it either does not or you have other errors.
This question already has answers here:typedef fixed length array(7 answers)Closed9 years ago. One of my C functions takes the following as it first argument ``` struct list *items[32] ``` how do I make atypedeffor this?
The answer istypedef struct list* ProcList[32];
I need to pass a double to my program, but the following does not work: ``` int main(int argc, char *argv[]) { double ddd; ddd=atof(argv[1]); printf("%f\n", ddd); return 0; } ``` If I run my program as./myprog 3.14it still prints0.000000. Can somebody please help?
My guess is you forgot to include#include <stdlib.h>. If this is the case,gccwill issue the following warning: ``` warning: implicit declaration of function 'atof' [-Wimplicit-function-declaration] ``` And give the exact output you provided:0.000000.
I have an enum declaration as below. ``` //declaring the situations can happen by next step enum step {CANGO, CANTGO, WILLFALL, LOSEPOINT, GAINPOINT}; ``` and I want to delcare a function which its output is of that declared enum. How I can do that?
Easy: ``` enum step myfunction(); ``` Or if you want you could usetypedef, but I wouldn't recommend it in this case: ``` typedef enum step step; step myfunction(); ``` The trick to remember is that in C, an enum type must be referred to using theenumkeyword, so a plainstepwould not work, which is probably what yo...
I have a counter in my code and I want my counter back to 0 when it reach the unsigned int max value. I tested with a small code and it works but I do not know if it's an undefined behaviour ``` #include <stdio.h> #include <string.h> main() { unsigned int a = 0; a= ~a; // Max value of unsigned int printf("%u ...
``` a= a+1; //is it allowed to increment "a" when "a" reach the Max ? ``` Yes, unsigned integers never overflow (this is C terminology). SoUINT_MAX + 1is defined behavior and is evaluated to0. (C99, 6.2.5p9) "A computation involving unsigned operands can never overflow, because a result that cannot be represented by...
What is the difference in the code below? Obviously the first declaration can hold up to 200 characters but what about the second? ``` char name[200] = "Name"; char name[] = "Name"; ```
The first create an array of 200chars and initialize its contents with{'N','a','m','e','\0', ... }(the rest is filled withNULs). The second create an array just large enough to hold"Name", that is, 5chars (one more for theNUL) Besides, you should use double quotes for string literals in C and C++.
In C: 1.- How could I define a token with the content of another token but in quotation marks? Something like the following code: ``` #include <stdio.h> #define _QUOTATION_MARKS " #define _SOMETHING something #define _SOMETHING_IN_QUOTATION_MARKS _QUOTATION_MARKS _SOMETHING _QUOTATION_MARKS int main() { printf(...
This will quote,stringify,bare: ``` #include <stdio.h> #define QUOTE(x) #x int main() { printf( "%s\n", QUOTE(bare) ); return 0; } ```
I have a (binary) file which has multiple entries of an array of 6 elements. So the file would be structured something like this : ``` {1 2 12 18 22 0} {11 17 20 19 20 7} {3 9 18 24 0 9}... ``` where I have put brackets around the elements that form one array. I'd like to sort the file based only on the first elemen...
Read file into 2 dimensional array. Each element on the first dimension should hold six elements.Implement comparison function forqsort.Useqsortwith your comparision function to sort the array.Write array back to file.
I have JSON returned from a server, and I would like to validate it against a JSON Schema (probably draft V3, can change though). I thought that perhapsNSDictionarywould have the functionality, but it doesn't seem to, here is my attempt: [self.dictionary ] (wheredictionaryis an NSDictionary) There weren't any meth...
Objective-C is a superset of C. JSON Schema site lists a C librarywjelement, you can adapt it. The example function call is ``` WJESchemaValidate(schema, json, schema_error, schema_load, NULL, format) ``` You'll need to supply a C string, rather thanNSString, naturally. Note: after I wrote the answer, I realised y...
I try to connect to oracle with ocilib: ``` int oraconnect() { OCI_Connection* cn; OCI_Statement* st; OCI_Resultset* rs; OCI_Initialize(NULL, NULL, OCI_ENV_DEFAULT); cn = OCI_ConnectionCreate("user", "db", "pass", OCI_SESSION_DEFAULT); st = OCI_StatementCreate(cn); OCI_ExecuteStmt(st, "...
First argument of OCI_ConnectionCreate should be the connection string (either an entry of the tnsnames.ora or an easy connect string)
I need to read/write to INI file in C. It is a little strange for me that I can't find any standard way of doing that. What is the common way of dealing with INI files in C? I prefer both - platform independent and Linux INI file parser libs.
Thislinkmay shed some light on the matter (written by the guy that authoredinihas mentioned by Zagorulkin Dmitry) - I have usedminIniand been happy with it..
I am writing a string to a file. But only the first part of the string is only inserted to file. Others are missing. For eg: If I write "I Like Flowers", "I" is only written into file. ``` #include <stdio.h> int main() { char string[50]; int marks,i,n; FILE *fptr; fptr=(fopen("string.txt","w")...
Thescanf()will stop reading at the first space: that is the problem. Thescanf("%s")only reads theIfrom standard input. To read the entire line usefgets()instead. Usestrlen()to write only what was read instead of usingsizeof(string).
Well, I am new to C. I would like to know as my title says. Suppose I declare pointers as following, ``` char *chptr1; char **chptr2; int *i; int **ii; struct somestruct *structvar1; struct somestruct **structvar2; ``` Then, Do I need to allocate memory for every variable, before storing data into them?Is there an...
Pointers point at things. It's up to you what you make them point at. You can leave them uninitialized and don't use them:int * q;That's a little silly.You can make them point to something that exists:int x; int * q = &x;You can store the address of dynamically allocated memory in them:int * q = malloc(29);
I have made customized format setting for C/C++ in Eclipse by going to ``` Window > Preferences > C/C++ > Code Style > Formatter ``` to use it within Eclipse, I use format option within source menu option or KEY BINDING (Ctrl+Shift+F). My QUESTION Can i run this format option from command line. Like calling Eclip...
Taking a look on eclipsedocumentationI thing it's possibile calling eclipse like in this way: ``` eclipse -configuration <file_name> ``` Obviously, you have to save all your configuration in a file.
I've looked around online about executing system commands through a c program, but none of them touched on executing the command after connecting to a remote host such as (this connection prompts for a user password): ``` sprintf(buffer1,"ssh -l %s %s ",userName,hostName); system((char*)buffer1); //Nothing below t...
You'll want to use the functionpopeninstead ofsystem. http://linux.die.net/man/3/popen It runs a command, returning a file object that you can write to with functions like fprintf, fwrite, etc., and those commands will go through the ssh process to the remote computer.
In this scenario, the stack starts at address 00000000 and grows down. Array access (char[6] at 00002301 and char[7] at 00002302). ebp-> 00001904 .... esp-> 00002100 (top of stack is here) You can still execute a buffer overflow if you use a bad input, my question is:- Can you use exploit that overflow to execute so...
Short answer: yes. Function A allocates buffer on the stack for variable Q.A calls B passing address of Q as a parameter.B overflows the buffer nuking the return address back to A. You also have to watch out for buffer underflows, or other attacks that could modify arbitrary memory (such as freeing an element from a...
``` int8_t a; int8_t b; int8_t result; result = (a*coeff) + b*(1-coeff); ``` Now this coeff has to be 0.5, but I cant store a float because of memory restrictions. Is there any way above operation can be performed? Thanks
It sounds as iffixed-point mathis the answer you need here. In fixed-point, you decide how much of your integer size you want to give up. Then you shift the radix point (the decimal point in base-10) that many places over (in binary, usually). So if you want to have a resolution of 0.25 you'd shift 2 bits. In a 16-bi...
I've looked around online about executing system commands through a c program, but none of them touched on executing the command after connecting to a remote host such as (this connection prompts for a user password): ``` sprintf(buffer1,"ssh -l %s %s ",userName,hostName); system((char*)buffer1); //Nothing below t...
You'll want to use the functionpopeninstead ofsystem. http://linux.die.net/man/3/popen It runs a command, returning a file object that you can write to with functions like fprintf, fwrite, etc., and those commands will go through the ssh process to the remote computer.
In this scenario, the stack starts at address 00000000 and grows down. Array access (char[6] at 00002301 and char[7] at 00002302). ebp-> 00001904 .... esp-> 00002100 (top of stack is here) You can still execute a buffer overflow if you use a bad input, my question is:- Can you use exploit that overflow to execute so...
Short answer: yes. Function A allocates buffer on the stack for variable Q.A calls B passing address of Q as a parameter.B overflows the buffer nuking the return address back to A. You also have to watch out for buffer underflows, or other attacks that could modify arbitrary memory (such as freeing an element from a...
``` int8_t a; int8_t b; int8_t result; result = (a*coeff) + b*(1-coeff); ``` Now this coeff has to be 0.5, but I cant store a float because of memory restrictions. Is there any way above operation can be performed? Thanks
It sounds as iffixed-point mathis the answer you need here. In fixed-point, you decide how much of your integer size you want to give up. Then you shift the radix point (the decimal point in base-10) that many places over (in binary, usually). So if you want to have a resolution of 0.25 you'd shift 2 bits. In a 16-bi...
I have a handle to a control that belongs to another process in the system.How can I get the process it belongs to? I've tried looking up a suitable function but haven't found much.
I suppose that by "handle to a control", you mean a HWND. Then, useGetWindowThreadProcessId ``` HWND hWndToSomeControl; [...] DWORD dwPid; GetWindowThreadProcessId( hWndToSomeControl, &dwPid ); ``` Edit: error control (Tested on Windows 7): ``` HWND hWndToSomeControl; [...] DWORD dwPid; DWORD dwTid = GetWindow...
Question is really simple. I need a tool to convertchar*to ip adress and use it in ``` sockaddr_in.s_addr ``` arpa/inet.h hasinet_addr()function, but I am not sure if I already have this file somewhere in MS VS 2010 installation or should I get it elsewhere.
Win32 provides its own implementation of the sockets API (Winsock) which uses slightly different headers. From theMSDN forinet_addr: Header Winsock2.h
AFAIK, Python, usingimport thread, (or C#) doesn't do "real" multithreading, meaning all threads run on 1 CPU core. But in C, using pthreads in linux, You get real multithreading. Is this true ? Assuming it is true, is there any difference between them when you have only 1 CPU core (I have it in a VM)?
Python uses something called a Global Interpreter Lock which means multiple python threads can only run within one native Thread. There is more documentation in the official Docs here:https://wiki.python.org/moin/GlobalInterpreterLock There shouldn't be a real performance difference on single core systems. On multic...
I'm writing simpleCprogram usingEclipse. I have several system includes. But now I have downloaded source code of library that contains one *.c and one *.h file. What is good manier to place these files? Should I place them toworkspace, or create directoryIncludenearsrcor place in/usr/local/include?
I you want to make the headers available to other users on the machine/usr/local/includewould be the place to put them. Otherwise keep them somehwere in your$HOME. Another alternative would be to put the sources to/usr/local/lib/<tool>/src/includeand link/usr/local/lib/<tools>/src/includeto/usr/local/include/<tool>...
This is part of my program; ``` double get_cpu_time(){ return (double)clock() / CLOCKS_PER_SEC; ``` But I get following error ; In function ‘get_cpu_time’: timertest.c:13:30: error: ‘CLOCKS_PER_SEC’ undeclared (first use in this function) The header files that I have included are; ``` #include<stdio.h> #inclu...
You need to include<time.h>instead of<sys/time.h>.
How we can we do addition at the left FF instead 00? For example we have a = E8, we need a = 0xFFFFFFe8 ``` 0xFFE26C02 -> 0xFFE26C02 0x000000e8 -> 0xFFFFFFe8 0x100000e8 -> 0x100000e8 0x001000e8 -> 0xFF1000e8 ``` P.S. data type int32 or int64
You can use the following to convert all leading bytes of0toFF ``` int RevLeadingZeros(int number) { if((number & 0xFF000000)==0) number |= 0xFF000000 else return number; if((number & 0x00FF0000)==0) number |= 0x00FF0000 else return number; if((number & 0x0000FF00)=...
I got a UI application which render output to an off-screen framebuffer in 16, 24 or 32 bpp respectively. I need to calculate pitch, my understanding is pitch is number of bytes in one scanline, is it equal to screenx*bitsperpixel? Though apparently it does not produce correct result. Can we have a formula (generic)...
According tothis: Buffers in video ram generally have a stride (also called pitch) associated with them. The stride is the width of the buffer in byteFor example, if you have a 1024x768 pixel buffer at 16 bits/pixel (2 bytes/pixel), your stride would be:1024 pixels * 2 bytes/pixel = 2048 bytes So the generic way to ...
I am trying to write a Macro for certain read/write functions. The functions are in the form ``` k_target_socket.write8(address,val); ``` When I tried#define Wx(add,val) k_target_socket.writex(address,val)I gotW8(0x100,0x120);forW8(0x100,0x120);then I replace the macro with#define W(x,add,val) & then gotk_target_soc...
What you need is token pasting. try the following: ``` #define W(x,ad,val) k_target_socket.write##x(ad,val) ``` The##will paste thexwith the function name. More detailshere
All, I want to executea DDL(Data Definition Language)from C code. What are the alternatives to do this?
One option is to usedynamic ESQL with PRO*C: ``` EXEC SQL EXECUTE IMMEDIATE "CREATE TABLE dyn1 (col1 VARCHAR2(4))"; ``` Another option is to usesystemto run SQL*Plus. On a Linux type system it could look something like this: ``` <write sql command(s) to sql file> system("cat mycommands.sql | sqlplus dbuser/pas...
What is the impact of freeing the struct that holds the pthread_t on the thread itself? I have a struct that represents a thread: ``` typedef struct car{ int cur_place; pthread_t car_thread; }car; ``` and i have an array that holds these cars, after some time i want to free the struct frominsidethe thread, i mean: ...
Freeingcaronly releases the memory used to store those values. The thread will still be other there somewhere possibly. Think ofpthread_tas simply holding a number or address used by the system to talk about the thread. Not the thread itself. Just don't refer to the memory ofcaranywhere after its free'd.
I'm using Wlanapi.dll in Windows (Visual Studio), the defaultWlanScanfunction always scans for wifi networks in all channels. Is there a command to nail the wireless card to one wifi-channel? The reason is to speed up the scanning and be more accurate. Filtering the results is not valid.
The reason for having multiple channels is that WiFi will change channels if a particular one is full of noise (from other 2.4Ghz sources: microwave ovens, cordless phones, Bluetooth devices, wireless video cameras, outdoor microwave links, wireless game controllers, Zigbee devices, fluorescent lights, WiMAX, and so o...
For instance: ``` void Sample_Function(char * ptr){ //Stuff } void Some_Other_Function(){ char *p; p = malloc(sizeof(char)*5); // Is this correct? Sample_Function(p); // Or this? Sample_Function(*p); } ``` Since free() takes an address and not the pointed-to byte I'm guessing the first optio...
type of p ischar*And type of *p ischar. SoSample_Function(p)is a valid call. If your function is: ``` char* Some_Other_Function(){ //things} ``` then you should returnpnot*pfor the same reason.
I wrote the following code: ``` #include <iostream> using namespace std; int main() { int a[10][10]; for (int i = 0; i < 10; i++) for (int j = 0; j < 10; j++) a[i][j] = i * j; cout << *(*(a + 3) + 4) << endl; return 0; } ``` I was expecting it to print some garbage data, or a seg...
*(a + b)=a[b]you take the address of a, move it by b and take the value at the corresponding address So*(*(a + 3) + 4)means*(a[3]+4)which meana[3][4]=12
Inspiredthisquiestion . Why does - ``` void display(int p[][SIZE]) // allowed ``` and ``` void display(int p[][]) // not allowed ``` ?
Because arraysdecayto pointers when passed to a function. If you do not provide the cardinality of the second dimension of the array, the compiler would not know how to dereference this pointer. Here is a longer explanation: when you write this ``` p[index] ``` the compiler performs some pointer arithmetic to find ...
If we havestruct Aand its instancesA1,A2,A3andstruct Bwith instancesB1,B2,B3 Is there a provision of having a 2D Array such that it can contain values: ``` ARRAY[][]={{&A1, &A2},{&B1, &B2}} ``` Is this approach vulnerable to errors?
You can make it an array ofvoid *which is valid C. But you have to keep in mind that in order to dereference a pointer the typehas to be knownat that time. ``` void * ARRAY[][]={{&A1, &A2},{&B1, &B2}}; ``` is valid, but then you have to supply the type on dereferenscing ``` *(struct A *)ARRAY[0][0] ``` A probably ...
This question already has answers here:Signed/unsigned comparisons(6 answers)Closed9 years ago. ``` main() { unsigned x=1; signed char y=-1; if(x>y) printf("x>y"); else printf("x<=y"); } ``` output is: x<=y But my question is in the statement unsigned x=1; there is no data type such ...
The default type for a "naked"unsignedisunsigned int. The comparison works thanks to C's arithmetic promotions, which will convert both arguments to>to a suitable type before doing the comparison.
I'm new to computer programming and i'm having some problems, i need help. Where am i doing wrong ? ``` if (x=='c' || x=='C') { a*1.8-32=a; printf("%f", a); } else if (x=='f' || x=='F') { (a-32)/1.8=a; printf("%f", a); } else { printf("Please enter a valid format.\n"); } return 0; ``` }
You can't write ``` a*1.8-32=a; ``` in C. the compiler tells you that the "lvalue" (left value) of an assignment needs to be actually assignable. What you probably meant is ``` a = a * 1.8 - 32; ```
Is it possible to know the details about the service (name, description, version etc), which is running behind the svchost.exe by process id in C/C++? Currently I'm going to get list of the running system services and compare their PIDs with the PID of the svchost.exe, which I already have. But I'm not completely sur...
Yes, you will have to compare PIDs. UseEnumServiceStatusEx()to get the PID of each running service. Just know that it is possible for multiple services to share the same process if they were implemented in the same executable and have theSERVICE_WIN32_SHARE_PROCESSflag enabled, so you might sometimes encounter multi...
What is the impact of freeing the struct that holds the pthread_t on the thread itself? I have a struct that represents a thread: ``` typedef struct car{ int cur_place; pthread_t car_thread; }car; ``` and i have an array that holds these cars, after some time i want to free the struct frominsidethe thread, i mean: ...
Freeingcaronly releases the memory used to store those values. The thread will still be other there somewhere possibly. Think ofpthread_tas simply holding a number or address used by the system to talk about the thread. Not the thread itself. Just don't refer to the memory ofcaranywhere after its free'd.
I'm using Wlanapi.dll in Windows (Visual Studio), the defaultWlanScanfunction always scans for wifi networks in all channels. Is there a command to nail the wireless card to one wifi-channel? The reason is to speed up the scanning and be more accurate. Filtering the results is not valid.
The reason for having multiple channels is that WiFi will change channels if a particular one is full of noise (from other 2.4Ghz sources: microwave ovens, cordless phones, Bluetooth devices, wireless video cameras, outdoor microwave links, wireless game controllers, Zigbee devices, fluorescent lights, WiMAX, and so o...
For instance: ``` void Sample_Function(char * ptr){ //Stuff } void Some_Other_Function(){ char *p; p = malloc(sizeof(char)*5); // Is this correct? Sample_Function(p); // Or this? Sample_Function(*p); } ``` Since free() takes an address and not the pointed-to byte I'm guessing the first optio...
type of p ischar*And type of *p ischar. SoSample_Function(p)is a valid call. If your function is: ``` char* Some_Other_Function(){ //things} ``` then you should returnpnot*pfor the same reason.
I wrote the following code: ``` #include <iostream> using namespace std; int main() { int a[10][10]; for (int i = 0; i < 10; i++) for (int j = 0; j < 10; j++) a[i][j] = i * j; cout << *(*(a + 3) + 4) << endl; return 0; } ``` I was expecting it to print some garbage data, or a seg...
*(a + b)=a[b]you take the address of a, move it by b and take the value at the corresponding address So*(*(a + 3) + 4)means*(a[3]+4)which meana[3][4]=12
Inspiredthisquiestion . Why does - ``` void display(int p[][SIZE]) // allowed ``` and ``` void display(int p[][]) // not allowed ``` ?
Because arraysdecayto pointers when passed to a function. If you do not provide the cardinality of the second dimension of the array, the compiler would not know how to dereference this pointer. Here is a longer explanation: when you write this ``` p[index] ``` the compiler performs some pointer arithmetic to find ...
If we havestruct Aand its instancesA1,A2,A3andstruct Bwith instancesB1,B2,B3 Is there a provision of having a 2D Array such that it can contain values: ``` ARRAY[][]={{&A1, &A2},{&B1, &B2}} ``` Is this approach vulnerable to errors?
You can make it an array ofvoid *which is valid C. But you have to keep in mind that in order to dereference a pointer the typehas to be knownat that time. ``` void * ARRAY[][]={{&A1, &A2},{&B1, &B2}}; ``` is valid, but then you have to supply the type on dereferenscing ``` *(struct A *)ARRAY[0][0] ``` A probably ...
This question already has answers here:Signed/unsigned comparisons(6 answers)Closed9 years ago. ``` main() { unsigned x=1; signed char y=-1; if(x>y) printf("x>y"); else printf("x<=y"); } ``` output is: x<=y But my question is in the statement unsigned x=1; there is no data type such ...
The default type for a "naked"unsignedisunsigned int. The comparison works thanks to C's arithmetic promotions, which will convert both arguments to>to a suitable type before doing the comparison.
I'm new to computer programming and i'm having some problems, i need help. Where am i doing wrong ? ``` if (x=='c' || x=='C') { a*1.8-32=a; printf("%f", a); } else if (x=='f' || x=='F') { (a-32)/1.8=a; printf("%f", a); } else { printf("Please enter a valid format.\n"); } return 0; ``` }
You can't write ``` a*1.8-32=a; ``` in C. the compiler tells you that the "lvalue" (left value) of an assignment needs to be actually assignable. What you probably meant is ``` a = a * 1.8 - 32; ```
Is it possible to know the details about the service (name, description, version etc), which is running behind the svchost.exe by process id in C/C++? Currently I'm going to get list of the running system services and compare their PIDs with the PID of the svchost.exe, which I already have. But I'm not completely sur...
Yes, you will have to compare PIDs. UseEnumServiceStatusEx()to get the PID of each running service. Just know that it is possible for multiple services to share the same process if they were implemented in the same executable and have theSERVICE_WIN32_SHARE_PROCESSflag enabled, so you might sometimes encounter multi...
For instance: ``` void Sample_Function(char * ptr){ //Stuff } void Some_Other_Function(){ char *p; p = malloc(sizeof(char)*5); // Is this correct? Sample_Function(p); // Or this? Sample_Function(*p); } ``` Since free() takes an address and not the pointed-to byte I'm guessing the first optio...
type of p ischar*And type of *p ischar. SoSample_Function(p)is a valid call. If your function is: ``` char* Some_Other_Function(){ //things} ``` then you should returnpnot*pfor the same reason.
I wrote the following code: ``` #include <iostream> using namespace std; int main() { int a[10][10]; for (int i = 0; i < 10; i++) for (int j = 0; j < 10; j++) a[i][j] = i * j; cout << *(*(a + 3) + 4) << endl; return 0; } ``` I was expecting it to print some garbage data, or a seg...
*(a + b)=a[b]you take the address of a, move it by b and take the value at the corresponding address So*(*(a + 3) + 4)means*(a[3]+4)which meana[3][4]=12
Inspiredthisquiestion . Why does - ``` void display(int p[][SIZE]) // allowed ``` and ``` void display(int p[][]) // not allowed ``` ?
Because arraysdecayto pointers when passed to a function. If you do not provide the cardinality of the second dimension of the array, the compiler would not know how to dereference this pointer. Here is a longer explanation: when you write this ``` p[index] ``` the compiler performs some pointer arithmetic to find ...
If we havestruct Aand its instancesA1,A2,A3andstruct Bwith instancesB1,B2,B3 Is there a provision of having a 2D Array such that it can contain values: ``` ARRAY[][]={{&A1, &A2},{&B1, &B2}} ``` Is this approach vulnerable to errors?
You can make it an array ofvoid *which is valid C. But you have to keep in mind that in order to dereference a pointer the typehas to be knownat that time. ``` void * ARRAY[][]={{&A1, &A2},{&B1, &B2}}; ``` is valid, but then you have to supply the type on dereferenscing ``` *(struct A *)ARRAY[0][0] ``` A probably ...
This question already has answers here:Signed/unsigned comparisons(6 answers)Closed9 years ago. ``` main() { unsigned x=1; signed char y=-1; if(x>y) printf("x>y"); else printf("x<=y"); } ``` output is: x<=y But my question is in the statement unsigned x=1; there is no data type such ...
The default type for a "naked"unsignedisunsigned int. The comparison works thanks to C's arithmetic promotions, which will convert both arguments to>to a suitable type before doing the comparison.
I'm new to computer programming and i'm having some problems, i need help. Where am i doing wrong ? ``` if (x=='c' || x=='C') { a*1.8-32=a; printf("%f", a); } else if (x=='f' || x=='F') { (a-32)/1.8=a; printf("%f", a); } else { printf("Please enter a valid format.\n"); } return 0; ``` }
You can't write ``` a*1.8-32=a; ``` in C. the compiler tells you that the "lvalue" (left value) of an assignment needs to be actually assignable. What you probably meant is ``` a = a * 1.8 - 32; ```
Is it possible to know the details about the service (name, description, version etc), which is running behind the svchost.exe by process id in C/C++? Currently I'm going to get list of the running system services and compare their PIDs with the PID of the svchost.exe, which I already have. But I'm not completely sur...
Yes, you will have to compare PIDs. UseEnumServiceStatusEx()to get the PID of each running service. Just know that it is possible for multiple services to share the same process if they were implemented in the same executable and have theSERVICE_WIN32_SHARE_PROCESSflag enabled, so you might sometimes encounter multi...
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question I am new to WCF,can anybody help me to know Why and where to use WCF. Recently I faced a...
ADVANTAGES OF USING WCF WCF unifies Web Services, .NET Remoting, and Enterprise Services stacks under one roof.In WCF configuration drives protocol choices, messaging formats, process allocation, etc.WCF services are loosely coupled, meaning that a WCF service is not bound to a particular protocol, encoding format, o...
I am having a problem with loop, I don't know why but loop never ends. ``` int main(int argc, char *argv[]) { int j; char s[2]; for(j=1;j<=3;j++) { sprintf(s,"s%d",j); printf("%s", s); } system("PAUSE"); return 0; } ``` I think loop should show s1s2s3 in console.
char s[2];should bechar s[3];, or else you will get a buffer overflow. Abhineetexplains why the change is necessary. However, in order to corroborate his answer, here is the relevant section from the standard. 7.19.6.6The sprintf function is equivalent to fprintf, except that the output is written into an array ...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ...
Please readdescription of function gets()! This function reads string from stdin. It returns NULL if found end of line or end of file before any characters.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question In C/C++, is there a way to write my function so that I can use format codes to print information easier? T...
Firstly, you can convert a c++ string to a char array usingmyString.c_str(). Also, you can use sprintf() with format codes to produce a string. Then you can draw that string using SDL. For example: ``` char myString[1024]; sprintf(myString, "Hello my name is %s", "foo"); draw_using_SDL(myString); ```
Can someone explain to me why the value of y here is 13? ``` #include <stdio.h> #define avg_sum(n) n * (n-1)/2 int main(){ int y; int z = 9; y = avg_sum(z+1); printf("y=%i\n",y); } ```
``` avg_sum(9+1) 9+1 * (9+1-1)/2 = 9 + 9/2 = 9+ 4 = 13 ``` macros expand each time so 9+1 is not the same as 10, it might be better with safeguarding parenthesis as follows: ``` #define avg_sum(n) ((n) * ((n)-1)/2) ``` but an equivelantfunctionwill do you much better and be more intuitive and will evaluate argument...
The following code will set x as "infinity" ``` #include <limits.h> int x = INT_MAX; ``` when I sayint x = 3;, the compiler is allocating some memory resources for variable x. Whats happening on the compiler side when I sayint x = INT_MAX;`.
That will not set the value to infinity. With integers, there is no value that can represent infinity. Instead, it will set it to the largest value that anintcan represent. Ifinthappens to be a 32-bit integer, thenINT_MAX == 2147483647.
I have to print 1,000,000 four digit numbers. I usedprintffor this purpose ``` for(i=0;i<1000000;i++) { printf("%d\n", students[i]); } ``` and it turns out to be too slow.Is there a faster way so that I can print it.
You could create an array, fill it with output data and then print out that array at once. Or if there is memory problem, just break that array to smaller chunks and print them one by one.
It doesn't matter how I exactly encrypt and decode files. I operate with file as achar massive, everything is almost fine, until I get file, which size is not divide to 8 bytes. Because I can encrypt and decode file each round 8 bytes, because of particular qualities of algorithm (size of block must be 64 bit). So th...
Do you need padding. The best way to do this would be to usePKCS#7. However GOST is not so good, better using AES-CBC. There is an ongoing similardiscussionin "python-channel".
I have function, that logs string info: ``` void Log(const char *aValue, int logLevel) { ... } ``` Very often I need to log text info that consists of several strings. In C I see only one way of doing that - create string variable, sprintf both phrases to that variable, log variable like: ``` #define VERSION "1.1.1...
IfVERSIONis a preprocessor constant expanding to a literal string, then you can concatenate them simply by placing them together: ``` Log("starting program " VERSION, INFO) ```
It's a simple one, but i'm not sure of the solution ``` int main() { c = fork(); fork(); fork(); } ``` I think 8...also is the value of c=0 ? If so, why?
The answer is: 7 processes are spawn by the fork. First you have the main processes. It forks itself, creating a new process. Let's call itchild1. Now,mainandchild1both fork themselves, creatingchild2andchild3. Now,main,child1,child2andchild3fork again.. creatingchild4,child5,child6andchild7. c is equal to 0, only...
If a is an int array,(char*) &a[1] - (char *)&a[0]is equal to 4, while&a[1] - &a[0]is equal to 1. why is that?
Pointer math operates on the size of the data structure its pointing to. This is because if I do this: ``` int array[10] ; int * p = array ; p ++ ; ``` I wantppointing at the second int, not some memory halfway in between two elements. So&a[1]is four bytes apart from&a[0]but asking it&a[1] - &a[0]asks how manyint...
In the vein ofWhich macro to wrap Mac OS X specific code in C/C++. What macro to use to identify when compiling on OSX 10.9 specifically. As opposed to other versions of OSX like 10.8, Snow Lion, Lion, Leopard, Leotard, Puma (made that one up), or Harrison Ford. __APPLE__only gives a boolean, and isn't enough inform...
``` #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_9 <Put your Mavericks specific code here..> #else <Put all other code here..> #endif ``` This works for other versions as well. For other macros relating to OSX versions, seeAvailiabilityMacros.h.
I want to declare a structure with 4 integer and each of them can only be from 0 to 255. Is there a way for it? Currently, I'm doing it by checking the input(in the input function). ``` struct { int num1; int num2; int num3; int num4; } ip; ```
Well, you can useunsigned char(or, better,uint8_t), but that doesn't mean you can just stop checking the input. It depends on your requirements. If I enter256what should happen? Is overflow ok? On a side note,sizeof(char)is defined to be 1, but one byte is not defined to be 8 bits. On most hardware you'll be fine,...
It's a simple one, but i'm not sure of the solution ``` int main() { c = fork(); fork(); fork(); } ``` I think 8...also is the value of c=0 ? If so, why?
The answer is: 7 processes are spawn by the fork. First you have the main processes. It forks itself, creating a new process. Let's call itchild1. Now,mainandchild1both fork themselves, creatingchild2andchild3. Now,main,child1,child2andchild3fork again.. creatingchild4,child5,child6andchild7. c is equal to 0, only...
If a is an int array,(char*) &a[1] - (char *)&a[0]is equal to 4, while&a[1] - &a[0]is equal to 1. why is that?
Pointer math operates on the size of the data structure its pointing to. This is because if I do this: ``` int array[10] ; int * p = array ; p ++ ; ``` I wantppointing at the second int, not some memory halfway in between two elements. So&a[1]is four bytes apart from&a[0]but asking it&a[1] - &a[0]asks how manyint...
In the vein ofWhich macro to wrap Mac OS X specific code in C/C++. What macro to use to identify when compiling on OSX 10.9 specifically. As opposed to other versions of OSX like 10.8, Snow Lion, Lion, Leopard, Leotard, Puma (made that one up), or Harrison Ford. __APPLE__only gives a boolean, and isn't enough inform...
``` #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_9 <Put your Mavericks specific code here..> #else <Put all other code here..> #endif ``` This works for other versions as well. For other macros relating to OSX versions, seeAvailiabilityMacros.h.
I want to declare a structure with 4 integer and each of them can only be from 0 to 255. Is there a way for it? Currently, I'm doing it by checking the input(in the input function). ``` struct { int num1; int num2; int num3; int num4; } ip; ```
Well, you can useunsigned char(or, better,uint8_t), but that doesn't mean you can just stop checking the input. It depends on your requirements. If I enter256what should happen? Is overflow ok? On a side note,sizeof(char)is defined to be 1, but one byte is not defined to be 8 bits. On most hardware you'll be fine,...
If a is an int array,(char*) &a[1] - (char *)&a[0]is equal to 4, while&a[1] - &a[0]is equal to 1. why is that?
Pointer math operates on the size of the data structure its pointing to. This is because if I do this: ``` int array[10] ; int * p = array ; p ++ ; ``` I wantppointing at the second int, not some memory halfway in between two elements. So&a[1]is four bytes apart from&a[0]but asking it&a[1] - &a[0]asks how manyint...
In the vein ofWhich macro to wrap Mac OS X specific code in C/C++. What macro to use to identify when compiling on OSX 10.9 specifically. As opposed to other versions of OSX like 10.8, Snow Lion, Lion, Leopard, Leotard, Puma (made that one up), or Harrison Ford. __APPLE__only gives a boolean, and isn't enough inform...
``` #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_9 <Put your Mavericks specific code here..> #else <Put all other code here..> #endif ``` This works for other versions as well. For other macros relating to OSX versions, seeAvailiabilityMacros.h.
I want to declare a structure with 4 integer and each of them can only be from 0 to 255. Is there a way for it? Currently, I'm doing it by checking the input(in the input function). ``` struct { int num1; int num2; int num3; int num4; } ip; ```
Well, you can useunsigned char(or, better,uint8_t), but that doesn't mean you can just stop checking the input. It depends on your requirements. If I enter256what should happen? Is overflow ok? On a side note,sizeof(char)is defined to be 1, but one byte is not defined to be 8 bits. On most hardware you'll be fine,...
I am new to C and I have a question regarding a problem I have. I need to get this input: AA BB CC DD But I get this all time AA BB CC00 DD The code I am using is : ``` int main(void) { unsigned int getal,temp; printf("Voer een getal in: \n"); scanf("%0X",&getal); temp = getal & 0xFF000...
You meantemp >> 24,temp >> 16, andtemp >> 8. Weird, you got the first one right, why did you suddenly do something totally different?
How do I say? ``` for (i = 0; i < arraySize; i++) { if (someArray[i + 1] !NULL) { //do this } else { //do something else } } ``` In other words, I want to check if the current index is the last index in the array. The current code is my best guess but it isn't working. EDIT: ...
Following line will give you count of items in your array: ``` count = sizeof (intMyArray)/sizeof(intMyArray[0]); ``` if you know arraySize then: ``` if(i==arraySize-1){ //last element of array } ```
``` #include <stdio.h> int main(void) { int t; long long int a[100000], n, i; scanf("%d\n", &t); while(t){ t--; scanf("%d", &n); printf("%ld\n", n); n = n * (n-1); printf("%ld\n", n); n = n/2; printf("%ld\n", n); } return 0; } ``` Can't f...
The format specifier forlong long intislld, notld. That'sespeciallyimportant in thescanfas using the wrong specifier may end up putting the data in the wrong bytes within the variable.
I have made several tests with GLib testing framework. I launch them by running "make check" in my test directory. How can I do to run only one test, for example, foobar ? Is there a command such as 'make check-foobar' ? Thank you for your help.
so you used gtester right, didn't do aman gtester? You can usegtester -p=/path/a/single/test/is/registered/to test-binary.bin If you can call it viamake check /some/pathdepends on your buildsystem (Makefile, autotools, waf, scons, CMake,.. and the associated config files, which you did not provide)
This question already has answers here:How can I get to know the IP address for interfaces in C?(7 answers)Closed9 years ago. I'm trying to implement a application that uses thegetifaddrs()function from<ifaddrs.h>across multiple platforms. My goal is to retrieve network interface related info (IP, IPv6, Netmask, Broa...
Solaris 11 and later havegetifaddrs()already in libsocket. For older Solaris releases, see the answer toSolaris: Programmatic interface to ifconfig?here on StackOverflow.
Thanks, now for some reason it's not working as intended. When I run the program it just gives an error "bst.exe has stopped working" and it happens in this function. ``` static NODE *insert_i(NODE *r, int x) { NODE *leaf; while(r) { if(r->val == x) return r; if(x < r->val &&...
You have ``` while(r) { if(r == NULL) ``` Theifcondition willneverbe true, as ifrisNULLthen the loop will end, without returning anything from the function.
I am lacking some basic understanding in bitwise '&' operator. ``` 5 = 101 4 = 100 ``` So why the output of the belowifcondition istruecause and of bits101 & 100should befalse: ``` #include <stdio.h> main() { if(5&4) printf("Yes\n"); } ```
5 is 101. 4 is 100. 5 & 4isnot0: ``` 101 100 & ↓↓↓ 100 ``` Problem solved ✓ Clarification: In C, every non-zero value satisfies theifcondition. Meaning, if you write: ``` if (-5) { if (100) { // reachable code } } ``` Whereas: ``` if (0) { destroyTheWorld(); // we are safe } ```
I want to declare a shared matrix in the global address space but not to perform any calculations by the UPC threads, but the GPU using CUDA. So is it possible to declare a UPC shared array in which the number elements in the array is NOT equal or a multiply of the number of threads (THREADS variable) ?
Assign the number of threads at the compile time using upcc flags. For more information on upcc flags checkupcc man page.
I'm trying to print Ascii symbols like a heart. The ASCII representation of this is 03, but I don't know how to implement that in my code. ``` int main(void) { printf("Heart: %c", 03); // return 0; } ``` I get an upside down question mark.. How do I use it?
The symbol that will display depends on the operating system on which you're running this code, and potentially (again depending on OS) the code page that is currently selected. The heart was something that MS-DOS added tocode page 437as a representation of that unprintable control character. ASCIIdoes not define a ...