question
stringlengths
25
894
answer
stringlengths
4
863
This question already has answers here:Const correctness in C vs C++(3 answers)Closed10 years ago. The following snippet of code is completely valid in C++ (at least gets compiled): my_file.cxx: ``` static const int MY_CONST_ONE = 1; static const int MY_CONST_TWO = MY_CONST_ONE; ``` On the other hand, compilation ...
Basically,constvariables in C are not considered compile-time constants. Places where compile-time constants are needed can thusnotget their values fromconstvariables.
I have the code fromGTK tutorialinbase.c. I am working onUbuntuand when I compile using ``` $ gcc base.c -o base `pkg-config --cflags --libs gtk+-2.0` ``` I get the followingerror ``` Package gtk+-2.0 was not found in the pkg-config search path. Perhaps you should add the directory containing `gtk+-2.0.pc' to the ...
``` $ sudo apt-get install libgtk2.0-dev ``` Generally speaking to build things based onlibfoo, you needlibfoo-dev. In addition, to install anything that is needed to build a package, saygedit, you can run: ``` $ sudo apt-get build-dep gedit ``` Searchinghttp://packages.ubuntu.com/or Synaptic can help.
I'm new to JNI, I'm trying to call a c function in java. The C program uses a .a library. However, in order to create the object file which used for generate the .so library. I can't link the c pragram to the .a library. The command I used is gcc -I./toolkithdir/ -I/usr/lib/jvm/java-6-openjdk-i386/include/ -c -fPIC...
Try this: ``` gcc -shared JNIFitnessPart.o libtoolkit.a -lm \ -o libJNIFitness.so -Wl,-soname,libJNIFitness.so ``` GCC can be (and should be) used a linker wrapper, so it can easily assemble your binary.
I am referring Sara Golemon "Extending and Embedding PHP". I am confused regarding the following snippet ``` zval **fooval; if (zend_hash_find(EG(active_symbol_table), "foo", sizeof("foo"), (void**)&fooval) == SUCCESS) ``` Why is&fooval, which would evaluate to azval***, cast to avoid**?
The function is assigning a pointer to the value of a pointer to a pointer. It doesn't care what type of pointer it is assigning, just that it is getting a pointer.voidmore-or-less, then, means "generic". I will admit that this is a gross over-simplification, but would be the same as having this in PHP: ``` function...
I like to ask that what happens if we pass a fractional number when dereferencing an array in C or C++. An example of what I mean: ``` int arr1[],arr2[]; for (i = 0; i < 5; ++i) { if (i % 2 == 0) arr1[i]=i; else arr2[i/2]=i; } ``` What would be the compiler do when it seesarr2[3/2]?
i/2is integer division. The result of this division will again be an integer, namely the result of the division truncated towards 0. (3/2==1; -5/2==-2;) (As a side note, the division and truncation are all a single operation: integer division. Most compilers will execute this in a single clock cycle.) So you will not ...
I am making a steerable derivative line filter. I want to be able to rotate it by an arbitrary angle. The desired situation will be the following: ``` cvMat myMat; ``` contains: 0, 0, 0 0, 0, 1 0, 0, 0 ``` float angle = radians(45); UnknownRotateMethod(myMat, angle); ``` myMat desired result: 0, 0, 0 0, 0, 0 0, 0,...
Solved: ``` cv2DRotationMatrix(pivot,angleDegrees,scale,outRotationMat); cvWarpAffine(myMat,myMat,outRotationMat); ```
I have quite a big structure which has inside of it other structures, then I want to pass this structure of structures as an argument of a function. Anyone knows how to do it or may give me an example please!
``` struct B { //your struct.. }; struct A { B b; }; void foo(struct A a) { a.b + ???.... //you function } ```
This question already has answers here:What REALLY happens when you don't free after malloc before program termination?(20 answers)When you exit a C application, is the malloc-ed memory automatically freed?(9 answers)Closed10 years ago. ``` int main() { char *a = malloc(1024); return 0; } ``` Does the progra...
The program itself has a leak. Whether the operating system cleans this up or not is a different matter. I suppose it's better to ask 'could this program potentially cause a problem on any system?' and the answer is absolutely yes. The C standard nowhere says that memory allocated withmallocwill be freed at program t...
It seems to me that both have the potential to overflow the buffer. Yet I'm adviced to never use gets() but still encouraged to use scanf(). Is it just because of the formatting arguments allowed in scanf() or is there any other reason?
Thegetsfunction is not protected against buffer overflows. With thescanfformat string you can define the maximal length of the string to read from standard input and store in the given memory buffer. For example withscanf("%10s\n", str);a maximum of 10 characters will be read. Thestrbuffer should be of 11 bytes to st...
This question already has answers here:Const correctness in C vs C++(3 answers)Closed10 years ago. The following snippet of code is completely valid in C++ (at least gets compiled): my_file.cxx: ``` static const int MY_CONST_ONE = 1; static const int MY_CONST_TWO = MY_CONST_ONE; ``` On the other hand, compilation ...
Basically,constvariables in C are not considered compile-time constants. Places where compile-time constants are needed can thusnotget their values fromconstvariables.
I have the code fromGTK tutorialinbase.c. I am working onUbuntuand when I compile using ``` $ gcc base.c -o base `pkg-config --cflags --libs gtk+-2.0` ``` I get the followingerror ``` Package gtk+-2.0 was not found in the pkg-config search path. Perhaps you should add the directory containing `gtk+-2.0.pc' to the ...
``` $ sudo apt-get install libgtk2.0-dev ``` Generally speaking to build things based onlibfoo, you needlibfoo-dev. In addition, to install anything that is needed to build a package, saygedit, you can run: ``` $ sudo apt-get build-dep gedit ``` Searchinghttp://packages.ubuntu.com/or Synaptic can help.
I'm new to JNI, I'm trying to call a c function in java. The C program uses a .a library. However, in order to create the object file which used for generate the .so library. I can't link the c pragram to the .a library. The command I used is gcc -I./toolkithdir/ -I/usr/lib/jvm/java-6-openjdk-i386/include/ -c -fPIC...
Try this: ``` gcc -shared JNIFitnessPart.o libtoolkit.a -lm \ -o libJNIFitness.so -Wl,-soname,libJNIFitness.so ``` GCC can be (and should be) used a linker wrapper, so it can easily assemble your binary.
I am referring Sara Golemon "Extending and Embedding PHP". I am confused regarding the following snippet ``` zval **fooval; if (zend_hash_find(EG(active_symbol_table), "foo", sizeof("foo"), (void**)&fooval) == SUCCESS) ``` Why is&fooval, which would evaluate to azval***, cast to avoid**?
The function is assigning a pointer to the value of a pointer to a pointer. It doesn't care what type of pointer it is assigning, just that it is getting a pointer.voidmore-or-less, then, means "generic". I will admit that this is a gross over-simplification, but would be the same as having this in PHP: ``` function...
I like to ask that what happens if we pass a fractional number when dereferencing an array in C or C++. An example of what I mean: ``` int arr1[],arr2[]; for (i = 0; i < 5; ++i) { if (i % 2 == 0) arr1[i]=i; else arr2[i/2]=i; } ``` What would be the compiler do when it seesarr2[3/2]?
i/2is integer division. The result of this division will again be an integer, namely the result of the division truncated towards 0. (3/2==1; -5/2==-2;) (As a side note, the division and truncation are all a single operation: integer division. Most compilers will execute this in a single clock cycle.) So you will not ...
I am making a steerable derivative line filter. I want to be able to rotate it by an arbitrary angle. The desired situation will be the following: ``` cvMat myMat; ``` contains: 0, 0, 0 0, 0, 1 0, 0, 0 ``` float angle = radians(45); UnknownRotateMethod(myMat, angle); ``` myMat desired result: 0, 0, 0 0, 0, 0 0, 0,...
Solved: ``` cv2DRotationMatrix(pivot,angleDegrees,scale,outRotationMat); cvWarpAffine(myMat,myMat,outRotationMat); ```
I have quite a big structure which has inside of it other structures, then I want to pass this structure of structures as an argument of a function. Anyone knows how to do it or may give me an example please!
``` struct B { //your struct.. }; struct A { B b; }; void foo(struct A a) { a.b + ???.... //you function } ```
This question already has answers here:What REALLY happens when you don't free after malloc before program termination?(20 answers)When you exit a C application, is the malloc-ed memory automatically freed?(9 answers)Closed10 years ago. ``` int main() { char *a = malloc(1024); return 0; } ``` Does the progra...
The program itself has a leak. Whether the operating system cleans this up or not is a different matter. I suppose it's better to ask 'could this program potentially cause a problem on any system?' and the answer is absolutely yes. The C standard nowhere says that memory allocated withmallocwill be freed at program t...
I noticed that during a fd leak, while the upper limit of file descriptors was reached a rename call failed. Unfortunately I don't have an error code. Is it possible that the lack of file descriptors is related to the failing of the rename? As far as I can see in the implementation of rename() a link() system call i...
I compiled this program: ``` #include <stdio.h> int main() { rename("a", "a1"); } ``` and ranstraceon the executable. Once the initialisation code is complete, all that happens is: ``` rename("a", "a1") = 0 exit_group(0) = ? ``` i.e. there are no system calls to...
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed10 years ago.Improve this question I wanted to adjust volume of a particular application(Not the entire system volume) in Linux using my c code. Please sugg...
First, you need to know what audio system your desktop is using. If it's PulseAudio (a popular choice, these days), then some API documentation can be found here: http://freedesktop.org/software/pulseaudio/doxygen/ I'm not totally sure if that's the right API for your needs (controllingotherapplications) but it's a...
I am searching for gcc command that can compile multiple files in different folders at a time. prg1.c prg1.h are in C:\folder. prg2.c which is in c:/folder/sub includes "prg1.h" So, I need to compile prg1.c and prg2.c at atime... and need to save generated .exe in c:/folder/sub I am trying ``` cd C:\folder gcc -o ...
You are dropping off the top of the windows file system with../../, perhaps that is the problem? try ``` gcc -o sub/prg2.exe prg1.c sub/prg2.c ```
``` (void)sprintf(Thermo_Buff,"%s\xC2\xB0""",a); //to add to buffer ```
In string literals, a backslash\is used as a prefix for special characters. I'm sure you know about newline ("\n") for example. If the special character after the backslash is anxthen it means that the next two characters are hexadecimal digits, and those two digits are the translated by the compiler into a character...
I want to get data with Objective C from my meteor project but it returns always this: ``` ... <head> <body> </body> </html> ``` Why between body tags is empty? And how do I get meteor datas from anywhere (curl, php, Objective C, iOS etc?
Meteor renders the output on the browser. In essence it does this: Load a html file that tells the browser how to create the pageUsing javascript the browser will create the pageFetch collections from server and fill the templates up with this If you want to fetch data from the collections use an Objective C ddp cli...
I have compiler warning in code while setting 32nd bit. Code works but this warning annoys me. Compiler is Keil C, processor is 32 bit ARM. Code is as following ``` PINSEL0 |= PINSEL_AD15; ``` wherePINSEL0is 32 bit register, defined as ``` #define PINSEL0 (*((volatile unsigned long *) 0xE002C000)) ``` and...
The literal1is asignedinteger, so when you shift by 31, you're going out of range. Try using an unsigned integer: ``` (1U << 31) ```
Basically I want to do the following: ``` #define TYPE float int main() { if (TYPE==float)...; } ``` Of course it wont' work, and not sure how to achieve it.
You can use the C preprocessor'sstringificationoperator. ``` #define xstr(s) str(s) #define str(s) #s if (strcmp(xstr(TYPE), "float") == 0) ... ``` For an explanation of this, seehere
Why does this print out "test"?: ``` char *str; str = (char *)malloc(1); str[0] = 't'; str[1] = 'e'; str[2] = 's'; str[3] = 't'; ``` I'm trying to dynamically expand a string and trying to understand how malloc/realloc works and the above behavior is confusing me as to malloc()/realloc() is advis...
Undefined Behavior means anything could happen. Including appearing to "work", nothing at all, OR a segmentation fault. Your sample code is indeed bad, but the C Standard doesn't guarantee that it will do anything "useful", nor that anything "bad" will necessarily happen at compile time or at run time.
I have a binary. I want to set limit to the resources available to that binary when executed.
I'm not sure I understand exactly what you want, but you can set the amount of memory available tomalloclike this: ``` struct rlimit s; int ret = getrlimit(RLIMIT_DATA, &s); // 0 on success s.rlim_cur = s.rlim_max; ret = setrlimit(RLIMIT_DATA, &s); ``` That would allow the process its maximum memory for...
I have data for which using cin/in is too slow. There are three integers per line : ``` 1 2 2 3 4 1 5 6 122 6 4 7 ``` How to read-in each line in loop, to achive result (for first iteration) : ``` x==1; y==2; z==2; etc. ``` ? How to to do it using cstdio::scanf ?
Use this: ``` while(scanf("%d %d %d", &a, &b, &c) != EOF) { ... do stuff ... } ```
This question already has answers here:What does "%.*s" mean as a format specifier in printf?(7 answers)Closed10 years ago. This might be a very basic question to many of you, but I am not able to understand what %.*s doing? ``` void substring(int i, int j, char *ch) { printf("The substring is: %.*s\n", j - ...
The*is taking the length limit for the string from the argument before the string. So the printf will output (at most)j - icharacters from&ch[i]tostdout. If the string is shorter, then the entire string will be printed, but it will not be blank padded.
This question already has answers here:Why is “while( !feof(file) )” always wrong?(5 answers)Closed10 years ago. I have a problem using the functionfeof, this is my code: ``` while(!feof(archlog)) { if(!fgets(line,MAXLINE,archlog)) printf("\nERROR: Can't read on: %s\n", ARCHTXT); else printf("%s",line)...
The loop will enter once more if the file ends with a new line. A warkaround whould be: ``` while(!feof(archlog)) { if(!fgets(line,MAXLINE,archlog)) printf("\nERROR: Can't read on: %s\n", ARCHTXT); else printf("%s",line); if ( (c=fgetc(archlog)) == EOF) break; ungetc(c, archlog); } ```
I can parse input, traverse up and down in the history but my backspace does not work. Why is that? ``` void printPrompt(void) { // prints working directory prompt char cwd[256]; getcwd(cwd, 255); printf("%s> ", cwd); fflush(stdout); } ```
You're trying to print out aDEL(dec 127) when you should be sending aBS(dec 8). You'll also probably then want to send a space and anotherBSto clear out that character (BSjust moves the cursor). So, when you getbuf[0] == 8, print out8,32,8. ``` else if (buf[0] == 8) { // Backspace if (charsRead > 0) { ...
I am using CUDA to accelerate some parts of a C program. This program makes use of some C++ keywords as identifiers, so it doesn't compile as C++. Now that I changed it with CUDA, how can I compile it with NVCC? For instance, I get the error: ``` table.h(65): error: expected an identifier ``` when compiling the cod...
NVCC compiles C++ code, not C code. Even if it pretends to consume C code in reality you just get a more C-like behavior, not a C compiler (see this post). For this reasonprivateis a keyword and can't be used as identifier (like any other C++ keyword). Actually--host-compilation Cisdeprecated(it shouldn't be used wit...
I have a binary. I want to set limit to the resources available to that binary when executed.
I'm not sure I understand exactly what you want, but you can set the amount of memory available tomalloclike this: ``` struct rlimit s; int ret = getrlimit(RLIMIT_DATA, &s); // 0 on success s.rlim_cur = s.rlim_max; ret = setrlimit(RLIMIT_DATA, &s); ``` That would allow the process its maximum memory for...
I have data for which using cin/in is too slow. There are three integers per line : ``` 1 2 2 3 4 1 5 6 122 6 4 7 ``` How to read-in each line in loop, to achive result (for first iteration) : ``` x==1; y==2; z==2; etc. ``` ? How to to do it using cstdio::scanf ?
Use this: ``` while(scanf("%d %d %d", &a, &b, &c) != EOF) { ... do stuff ... } ```
This question already has answers here:What does "%.*s" mean as a format specifier in printf?(7 answers)Closed10 years ago. This might be a very basic question to many of you, but I am not able to understand what %.*s doing? ``` void substring(int i, int j, char *ch) { printf("The substring is: %.*s\n", j - ...
The*is taking the length limit for the string from the argument before the string. So the printf will output (at most)j - icharacters from&ch[i]tostdout. If the string is shorter, then the entire string will be printed, but it will not be blank padded.
This question already has answers here:Why is “while( !feof(file) )” always wrong?(5 answers)Closed10 years ago. I have a problem using the functionfeof, this is my code: ``` while(!feof(archlog)) { if(!fgets(line,MAXLINE,archlog)) printf("\nERROR: Can't read on: %s\n", ARCHTXT); else printf("%s",line)...
The loop will enter once more if the file ends with a new line. A warkaround whould be: ``` while(!feof(archlog)) { if(!fgets(line,MAXLINE,archlog)) printf("\nERROR: Can't read on: %s\n", ARCHTXT); else printf("%s",line); if ( (c=fgetc(archlog)) == EOF) break; ungetc(c, archlog); } ```
I can parse input, traverse up and down in the history but my backspace does not work. Why is that? ``` void printPrompt(void) { // prints working directory prompt char cwd[256]; getcwd(cwd, 255); printf("%s> ", cwd); fflush(stdout); } ```
You're trying to print out aDEL(dec 127) when you should be sending aBS(dec 8). You'll also probably then want to send a space and anotherBSto clear out that character (BSjust moves the cursor). So, when you getbuf[0] == 8, print out8,32,8. ``` else if (buf[0] == 8) { // Backspace if (charsRead > 0) { ...
I am using CUDA to accelerate some parts of a C program. This program makes use of some C++ keywords as identifiers, so it doesn't compile as C++. Now that I changed it with CUDA, how can I compile it with NVCC? For instance, I get the error: ``` table.h(65): error: expected an identifier ``` when compiling the cod...
NVCC compiles C++ code, not C code. Even if it pretends to consume C code in reality you just get a more C-like behavior, not a C compiler (see this post). For this reasonprivateis a keyword and can't be used as identifier (like any other C++ keyword). Actually--host-compilation Cisdeprecated(it shouldn't be used wit...
Like C , does ruby have signed and unsigned integers and if it does then does that mean length method of String class return signed integer ? (Since in C integer if not specified implies signed)
Ruby implements integers in such a way that the distinction signed/unsigned is irrelevant, as Ruby integers extend automatically into BigNum (arbitrary length integers) when applicable. This effectively prevents integer overflow, which is IMHO the main reason why people care about signedness in languages with fixed-s...
I would like to know if there's a real difference between this: ``` c = (struct_t *) malloc(sizeof(struct_t)); ``` and this ``` c = malloc(sizeof(struct_t *)); ``` Besides avoid the cast, is the compiler takes any advantage in the second form respect the first? Or the two ways are completely the same and is just a...
The first allocatessizeof(struct_t)bytes, the secondsizeof(struct_t*)bytes. Apart from that, there is no difference in whatmallocdoes, whether you cast the result or not. Casting the result makes the code acceptable to C++ compilers, but it can hide the mistake of not includingstdlib.h, therefore it is widely preferr...
``` FILE * pFile; pFile = fopen ("myfile.txt","r"); if (pFile == NULL) { some code } pFile = fopen ("myfile.txt","r") ``` in this case what will be assigned topFile? sincepFileis a pointer which only stores address of another variable. I wonder "myfile.txt" is a string right? So is it that pFile = address of array ...
It points to aFILEobject. The details are implementation-dependent, and don't affect user code. But it will typically be a structure that includes various references to OS-specific file-handling mechanisms. This is an example of anopaque pointer.
I am currently working in C multi-threading on server having multiple hexa-core cpus. I want to set affinity of some of my threads to respective cores of a single CPU. I have used pthread_setaffinity_np() and also sched_setaffinity() but i guess the set affinity on the cpus not the cores. am I right?
pthread_setaffinity_np()et al operate in terms of logical CPUs (i.e. cores), not physical ones (i.e. CPU sockets).
I have this part of code in C class: ``` int i; for (i=0;i<val;i++) mdl_print ("%u ", rec->payload[i]); mdl_print ("\n"); ``` Variable rec->payload is uint8_t type. I would print it in hexadecimal notation. How can I do? Thanks.
Quick and easy: ``` print("%x", (int)(rec->payload[i])); ``` To display in the format 0x05 then use: ``` print("0x%02x", ...) ``` instead.
Here's the code: ``` #include <stdio.h> #include <stdio.h> #define VAL1(a,b) a*b #define VAL2(a,b) a/b #define VAL3(a,b) ++a%b int main() { int a = 1; int b = 2; int c = 3; int d = 3; int e = 5; int result = VAL2(a,d)/VAL1(e,b)+VAL3(c,d); // result = 1 //int result = a/d/e*b+++c...
In one case you have+ ++and in the other case you have++ +.+ ++and++ +are different streams oftokens. Macro pasting doesn't change tokenization because it's tokens that are pasted. If you punch your program into a C pre-processor, you'll get this out for that line: ``` int result = a/d/e*b+ ++c%d; ``` Notice that t...
Typingman strptimeit sais that this function needs to have declared _XOPEN_SOURCE and included time.h header. I did it. But, when I try to compile my code I get: ./check.c:56: warning: implicit declaration of function ‘strptime’ Look at my code: ``` int lockExpired(const char *date, const char *format, time_t curre...
I've found that I needed to define__USE_XOPENand also_GNU_SOURCEto get it to be happy.
This is outside the main: ``` char message_ecran[NUMBER_OF_STRINGS][STRING_LENGTH+1]; ``` And this is my function ``` int main(void) { Init(); int i; char texte7[] = "io"; for (i=0;i<=NUMBER_OF_STRINGS;i++) { message_ecran[i] = texte7; } ...
strcpy(), implemented in your program. ``` #include <string.h> #include <stdio.h> #define NUMBER_OF_STRINGS 3 #define STRING_LENGTH 80 char message_ecran[NUMBER_OF_STRINGS][STRING_LENGTH+1]; int main(void) { int i; char texte7[] = "io"; for (i=0;i<=NUMBER_OF_STRINGS;i++) { strcpy(message_...
This question already has answers here:Lightweight SQL database which doesn't require installation [closed](7 answers)Closed10 years ago. I would like to use the advatages of a database, instead of a flat file managed by myself. I would like to use QSL queries, etc, but without having a database management server as ...
You can try SQLite. It does not need a separate server instance yet you can write SQL queries.
I have defined a "car" struct with a model (char *model) and the year of the model (int year). I have a function that will create a new car struct; however, it is seg faulting when copying the char pointers. This is supposed to create a new node for a linked list. ``` Car *newCar(char *model, int year){ Car *ne...
For future reference this function fixed my issue... ``` Car *createCar(char *model, int year){ Car *new = malloc(sizeof(Car)); new->year = year; new->model = malloc(strlen(model)+1); strcpy(new->model, model); new->next = NULL; return new; } ```
When I read the TCPL by K&R, I just couldn't understand two expressions: ``` *p++ = val; /*push val onto stack */ ``` Here is my idea: dereference and postfix has the same precedence, and associativity is right to left,so*p++ = valmaybe the same with*(p++) = val, because the pointer usually is the next position t...
The prefix increment/decrement and dereference operators are equal precedence, but the postfix operator is higher, so*p++is the same as*(p++), which is like writing*p = val; p++; If you wrote(*p)++ = val, it wouldn't compile, as you'd be trying to assign a value to a number.
I have a ready made external static library (.a) that I want to link to my executable. How exactly can I do it with cmake?
You should use theTARGET_LINK_LIBRARIEScommand. But before that you might want to make sure CMake looks into correct directories by usingFIND_LIBRARYorLINK_DIRECTORIES. All are documented in detail here: (CMake help: TARGET_LINK_LIBRARIES) (CMake help: LINK_DIRECTORIES) (CMake help: FIND_LIBRARY) According to the com...
I have this part of code in C class: ``` int i; for (i=0;i<val;i++) mdl_print ("%u ", rec->payload[i]); mdl_print ("\n"); ``` Variable rec->payload is uint8_t type. I would print it in hexadecimal notation. How can I do? Thanks.
Quick and easy: ``` print("%x", (int)(rec->payload[i])); ``` To display in the format 0x05 then use: ``` print("0x%02x", ...) ``` instead.
Here's the code: ``` #include <stdio.h> #include <stdio.h> #define VAL1(a,b) a*b #define VAL2(a,b) a/b #define VAL3(a,b) ++a%b int main() { int a = 1; int b = 2; int c = 3; int d = 3; int e = 5; int result = VAL2(a,d)/VAL1(e,b)+VAL3(c,d); // result = 1 //int result = a/d/e*b+++c...
In one case you have+ ++and in the other case you have++ +.+ ++and++ +are different streams oftokens. Macro pasting doesn't change tokenization because it's tokens that are pasted. If you punch your program into a C pre-processor, you'll get this out for that line: ``` int result = a/d/e*b+ ++c%d; ``` Notice that t...
Typingman strptimeit sais that this function needs to have declared _XOPEN_SOURCE and included time.h header. I did it. But, when I try to compile my code I get: ./check.c:56: warning: implicit declaration of function ‘strptime’ Look at my code: ``` int lockExpired(const char *date, const char *format, time_t curre...
I've found that I needed to define__USE_XOPENand also_GNU_SOURCEto get it to be happy.
This is outside the main: ``` char message_ecran[NUMBER_OF_STRINGS][STRING_LENGTH+1]; ``` And this is my function ``` int main(void) { Init(); int i; char texte7[] = "io"; for (i=0;i<=NUMBER_OF_STRINGS;i++) { message_ecran[i] = texte7; } ...
strcpy(), implemented in your program. ``` #include <string.h> #include <stdio.h> #define NUMBER_OF_STRINGS 3 #define STRING_LENGTH 80 char message_ecran[NUMBER_OF_STRINGS][STRING_LENGTH+1]; int main(void) { int i; char texte7[] = "io"; for (i=0;i<=NUMBER_OF_STRINGS;i++) { strcpy(message_...
This question already has answers here:Lightweight SQL database which doesn't require installation [closed](7 answers)Closed10 years ago. I would like to use the advatages of a database, instead of a flat file managed by myself. I would like to use QSL queries, etc, but without having a database management server as ...
You can try SQLite. It does not need a separate server instance yet you can write SQL queries.
I have defined a "car" struct with a model (char *model) and the year of the model (int year). I have a function that will create a new car struct; however, it is seg faulting when copying the char pointers. This is supposed to create a new node for a linked list. ``` Car *newCar(char *model, int year){ Car *ne...
For future reference this function fixed my issue... ``` Car *createCar(char *model, int year){ Car *new = malloc(sizeof(Car)); new->year = year; new->model = malloc(strlen(model)+1); strcpy(new->model, model); new->next = NULL; return new; } ```
It's said that when including C header files in C++, the ".h" suffix should be removed and then add "c" at the beginning. For example,#include <cstdio>instead of#include <stdio.h>. But when I usesleep()in my code,#include <cunistd>does not work, but#include <unistd.h>works. Why not<cunistd>?
Your algorithm is correct for most (all?) standard C headers, butunistd.his not part of standard C so standard C++ in turn doesn't include it with the otherc...headers.
There is a struct like this: ``` struct sdshdr { int len; int free; char buf[]; }; ``` And the result ofprintf ("%d\n", sizeof(struct sdshdr));is 8. If I changechar buf[]tochar *, the result would be 16. Why ischar buf[]taking no space here(sizeof(int)is 4)? When shoud I choosechar buf[]overchar *buf?
The construct with the empty brackets[]is allowed as the last element of thestruct. It lets you allocate additional space beyondsizeof(sdshdr)for the elements of the array, letting you embed the array data with the array itself. Pointers, on the other hand, store the data in a separately managed segment of memory, an...
In the classic swap function, when we pass in two pointers, the values the pointers point to will swap. However in this simple function ``` int leng (char *a) { int n; for (n=0; *a!='\0'; a++) n++; return n; } ``` After the function is called, the pointer still points to the first element of the ...
A pointer is itself an object. In this case, you are passing the pointer by value, not by reference, so any changes to the pointer itself will not be reflected outside the function. If you were to change the object the pointer points to in the function, those changes would persist outside the function. Try: ``` int ...
I am supposed to work out this code to tell the output for my homework. Could somebody help me out? I'm not looking for the answer but, step by step instructions of how to understand this. ``` int main() { int pid; int val = 5; pid = fork(); if (pid == 0) val += 3; if (val == 5) val...
The code will print one of the three following options: ``` val=6 ``` ``` val=8 val=6 ``` ``` val=6 val=8 ``` It depends on whichwrite()syscall completes first: child or parent, and whether the child process is successfully created (it might fail).
This question already has an answer here:how refer to a local variable share same name of a global variable in C? [duplicate](1 answer)Closed10 years ago. Code : ``` int a = 33; int main() { int a = 40; // local variables always win when there is a conflict between local and global. // Here how can i access glob...
How about this old trick: ``` int main() { int a = 40; // local variables always win when there is a conflict between local and global. { extern int a; printf("%d\n", a); } } ```
C code : ``` int a; printf("\n\t %d",a); // It'll print some garbage value; ``` So how does thesegarbagevalues are assigned to uninitialized variables behind the curtains in C? Does it mean C first allocates memory to variable 'a' and then what ever there is at that memory location becomes value of 'a'? or somethin...
Does it mean C first allocates memory to variable 'a' and then what ever there is at that memory location becomes value of 'a'? Exactly! Basically, C doesn't doanythingyou don't tell it to. That's both its strength and its weakness.
So I am working with some matlab code converting to c code by hand. I am just wondering if there is a c equivalent to the sind and cosd functions I'm seeing in the matlab code. I guess this returns the answer in degrees rather than the c sin and cos function that gives the result in radians. I guess I could just mu...
H2CO3's solution will have catastrophic loss of precision for large arguments due to the imprecision ofM_PI. The general, safe version for any argument is: ``` #define sind(x) (sin(fmod((x),360) * M_PI / 180)) ```
I am reading buffer bytes from a socket but I don't know how to initialize the buffer array with the length info. ``` uint32_t len; int lengthbytes = 0; int databytes = 0; // receive the length info of an image data lengthbytes = recv(clientSocket, (char *)&len, sizeof(len), 0); // convert hexadecimal data to lengt...
``` len = ntohl(len); char buf[len]; //----> this is illegal in C ``` This is valid in C99 and it is called avariable length array. If you are not using C99 usemallocto allocate the array (and declarebufas achar *).
``` int main(int argc, char **argv){ char *str = argv[1]; size_t len = strlen(str); char *dst = calloc(len+1, sizeof(char)); int i; for(i=len-1; i>=0; i--){ memcpy(dst, str+i, 1); dst++; } *(++dst) = '\0'; printf("%s\n", dst); free(dst); return 0; } ``` Error ch...
You have: ``` char *dst = calloc(len+1, sizeof(char)); /* ... */ *(++dst) = '\0'; /* ... */ free(dst); ``` You mustfreethe pointer that was allocated bymalloc/calloc. Here you modified it. Make a copy of it so you canfreeit after.
I don't understand why but I'm failing to compile supersimple C code in two files when there are some references between them. I'm using Visual Studio 2010, opening Empy C++ project Here it is: main.c: ``` extern void putc(char c); int main() { char c = ' '; putc(c); return; } ``` anotherfile.c: ``` void putc(char...
In the VC2012 project, pleasedisablethePrecompiled Headersoption. This should resolve the compilation issues faced by you.
Scenario:I want to provide a isolated foo in some foo.h/foo.c module. This function should be capable of executing in a thread-safe manner. ProblemHow can I initialise a mutex (or any other lock abstraction) safely inside the function. I thought that I could have something like this: ``` foo(){ static pthread_mut...
You are thinking too complicated ``` static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; ``` is meant to do what you want to achieve. If you just need the lock in that function place the static variable in there. If you need it in several functions, place it as global variable in the .c file.
Is it possible to make a data type which can take integer values from 0 to 9 only? If yes, please tell How?
No, it is not possible to make a custom-ranged integer in C. You'll have to maintain such an invariant yourself.
I have a 16 bit address and I need to split this into 15-8 for page number and 7-0 for offset. So, I am guessing I could do bitwise ops on it? Let's say0xBEEFis address that needs to be split. Page Number:0xBEEF & 0xFF80= 1011 1110 1110 1111 & 1111 1111 1000 0000 = 1011 1110 1000 0000 = 0xBE80 Offset:0xBEEF & 0x00...
You can use the bitshift operator in most programs. top8 = 0xABCD >> 8; bottom8 = 0xABCD & 0x00FF; This will give youtop8 = 0x00ABandbottom8 = 0x00CD. Note that you don't have to shift them by 8 bits, it can be anything.
When defining an axiom for string length, I need to use the reads clause. ``` /*@ predicate Length_of_str_is{L}(char *s, integer n) = (0 <= n) && \valid(s+(0..n)) && s[n] == 0 && \forall integer i; 0 <= i < n ==> s[i] != 0; axiomatic LengthAxiomatic{ logic integer Length{L}(char *s) reads s[..]; axiom str_...
Under Oxygen version of Frama-C/Wp, it is safe (although incorrect from ACSL point of view) to usereads *sinstead ofreads s[..]in such a situation. The next incoming release of Frama-C will enable general read clauses.
How can I change the font size of a printed font using c? ``` printf ("%c", map[x][y]); ``` I want to print an array larger than all the other text in the program. Is there a way to just make that statement print larger?
Althoughteppic's answerto usesystem()will work, it is rather intensively heavy-handed to call an external program just to do that. As forDavid RF' answer, it is hard-coded for a specific type of terminal (probably a VT100-compatible terminal type) and won't support the user's actual terminal type. In C, you should us...
Why wont the array print I'm using c not c++. what am I doing wrong? I would also like to know what characters you can use in a char variable. ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int map[4][4] = {1,1,1,1,1,1,11,1,1,1,1,1,1,1,1}; int x, y; for (x = 0; x < 4; x++); ...
Get rid of the ';' on both the for lines :) ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int map[4][4] = {1,1,1,1,1,1,11,1,1,1,1,1,1,1,1}; int x, y; for (x = 0; x < 4; x++) { for (y = 0; y < 4; y++) { printf ("%i ", map[x][y]); } printf ("\n"); } ...
I'm having small problems with getting my system working, so I decided to ask question if is it possible to make virtual address corresponding to file offset. So if virtual address of my.textsection is0x1000, I want linker to fill "padding" space to position with zeroes. Is it possible?
You're mentioningyour system, so I assume that it's related to hobby OS development and that youknowwhat you're trying to do and why. If the image is a PE file, you can make the file alignment equal to the section alignment. In GNU ld you can do that by passing--file-alignment 4096(as the default section alignment is...
Is there native support for a data type for storing Unicode strings in C. I'm writing a toy compiler and would like to parse Unicode strings.
Is there native support for a data type for storing Unicode strings in C. Yes. Since Unicode strings can bestoredas sequences of bytes using an encoding scheme, one can use arrays ofcharfor this purpose. Note that supporting storage says nothing about the ability to interpret or manipulate the data.
Is it possible to make an array of arrays in C? More specifically, is it possible to make a list (array) of adjacency lists (arrays)? And if so, how? My textbook uses a list of adjacency lists for Dijkstra's algorithm (and in a lot of other algorithms) instead of using an adjacency matrix, though the book is in pseu...
Did you mean a multidimensional array? ``` int mdarr[10][20]; ```
Why is the value of n changing to garbage inside the for-loop? (I'm new to C language, I come from a C++ background) ``` float n = 3.0; printf ("%f\n", n); for (; n <= 99.0; n += 2) printf ("%f\n", &n); ```
You are printing the address of n (&n) inside the for-loop. Get rid of the&
Say we are working in C. if I go ahead and do this: ``` char *word; word = "Hello friends"; printf(word); ``` then XCode tells me that because I'm not using a string literal, that I might have something that is potentially insecure. Does that mean an opening for something to hack my program? If so, how could that h...
The first argument toprintfis not the string you want to print. It's a format string. It can contain formatting instructions which results in the string that is printed once it is combined with further arguments. Your first example isan uncontrolled format string vulnerability.
I have a simple question. The code is really short so I just post it here ``` #include <stdio.h> int main(int argc, const char * argv[]) { long int p; printf("FYI: address of first local varaible of main() on the function stack:%p\n",&p); printf("Enter start address <hex notation> of dump:"); scanf(...
To print the least-significant byte of*qin hex you could use: ``` printf("%02x", *q & 0xFF); ``` This of course assumes thatqcan be dereferenced.
when trying to use a variable defined in a preprocessor directive: ``` #define TIME_CONST 20; ``` in a while condition: ``` while(i<TIME_CONST){...} ``` I get an error complaining about parantheses... when i use: ``` while(i<20) ``` everything works fine. what am I doing wrong? Thank you in advance!
``` #define TIME_CONST 20; ``` Remove;from the end. Because of;, the following: ``` while(i<TIME_CONST){...} ``` becomes this: ``` while(i< 20;){...} ``` which is wrong, isn't it? In C++ (and C), macros aretext-replacementmechanism, so any usage ofTIME_CONSTwill be replaced by20;because that is how it has been ...
``` int main() { int c; while ( (c = getchar()) != EOF) putchar(c); } ``` Now ,running the above program produces $./a.out thisisthelinewhosestoragelocationisamysterytome-- LINE1thisisthelinewhosestoragelocationisamysterytome-- LINE2 When i entered the characters ofLINE1, i think the functions getchar() an...
Your program doesn't receive input from the shell until you've entered a whole line.
Each time I step withnit prints out the next statement to be executed. How do I see the next statement to be executed, as if I had typedn, but without actually stepping the code? Currently I am usingwhere, and this gives me the line number of the next statement and I can uselistto see some source code. Does it requi...
Try "frame" command. You will see something like this: ``` (gdb) frame #0 main () at dummy.c:11 11 FILE*f = fopen("somefile","r"); (gdb) ```
I know that arrays may fully exploit the caching mechanisms on a x86_64 architecture by fitting into cache lines and because of their sequential nature. A linked list is a series of structs/objects linked together by pointers, is it possible to take advantage of the caching system with such a structure? Linked list's ...
It's true that linked list entriescanbe anywhere, but they don'thaveto be "just anywhere". For instance, you can allocate them out of a "zone". Allocate a bunch of contiguous entries at one time, string them together into a list of "free entries that are contiguous", and then parcel them out. Allocate another zone-...
I am trying to call a function, which appeared not to be working. So i added a few printf() and this is the result. ``` if (rc > 0) { bzero(buffer,256); n = read(sockfd,buffer,255); if (n < 0) error("ERROR reading from socket"); printf("ListenPort() go...
By default stdout is line-buffered. Addfflush(stdout);at the end of theifblock.
I wrote a small rgrep function and I'll have another text file with words that I am checking a pattern against. My text file will be in the following format. ``` a because cat 7.* ``` How do i write a loop that will call a function for each of those words in the file? Thanks!
Make a state machine for that pattern first, then every char drives that state machine to next state. Check state to check pattern match.
``` #include<stdio.h> #include<malloc.h> void my_strcpy(char *sour,char *dest){ if(sour == NULL || dest == NULL){ return; } dest = sour; } int main(){ char *d = NULL; char *s = "Angus Declan R"; //d = malloc(sizeof(strlen(s)+1)); //my_strcpy(s,d); d = s; printf("\n %s \n",d); return 0; } ``` In this i'm t...
C is a pass-by-value language.This questionof the C FAQ can answer your question. Note that even if you fix your function prototype, your algorithm isn't copying a string at all - just a pointer. You can just replace that call with: ``` d = s; ``` In yourmainfunction. Themallocis unnecessary, too - you're just le...
I'm making a c function and using it with a mac app for testing and learning purposes. When I try to print text to a file using this: ``` FILE *f = fopen("text.txt", "w+"); fflush(f); if (f==NULL) { f = fopen("text.txt", "w+"); saveToFile(text); printf("null\n"); return 0; } else{ int i = fprintf(...
You're callingreturnno matter what before your program can ever reach thefclose. So your program is holding off writing to the file until it's closed (because of buffering). When you terminate the program, the files are being closed for you.
Below is the snippet of the code: ``` int main(void) { char sizing[] = "manshcanshcnams cndhan sndhcna snshans"; char *xyz = malloc(sizeof(char)); printf("%ld\n",sizeof(xyz)); xyz = sizing; // IT SHOULD FAIL HERE printf("Fail %s\n",xyz ); return 0; ``` } As you can see that I am trying t...
You can't copy strings with=.xyz = sizingjust modifies the variablexyzso that it points to the arraysizing, instead of pointing to the memory you malloced. So, your memory is leaked but there is no undefined behavior (except that you forgot to include<stdio.h>and<stdlib.h>).
So, basically, I have two different structures defined in two different .h files (vcard.h and bst.h), both of which are included in the current file. Here are the structure definitions: ``` struct bst { vcard *c; bst *lsub; bst *rsub; }; struct vcard { char *cnet; char *email; char *fname; char *lname;...
c is a pointer, you need t->c->cnet
I have this example on how to convert from a base 10 number to IEEE 754 float representation ``` Number: 45.25 (base 10) = 101101.01 (base 2) Sign: 0 Normalized form N = 1.0110101 * 2^5 Exponent esp = 5 E = 5 + 127 = 132 (base 10) = 10000100 (base 2) IEEE 754: 0 10000100 01101010000000000000000 ``` This makes sense...
Simple place value. In base 10, you have these places: ... 103102101100.10-110-210-3...... thousands, hundreds, tens, ones . tenths, hundredths, thousandths ... Similarly, in binary (base 2) you have: ... 23222120.2-12-22-3...... eights, fours, twos, ones . halves, quarters, eighths ... So the second place after ...
I'm a little confused about the correct syntax for assigning a function pointer to a variable. If I have a function foo ``` int foo(); ``` and I am assigning a pointer to foo to variable bar ``` void * bar; ``` it does not seem to matter if I use ``` bar = foo; // or bar = &foo; ``` It seems to me that only on...
fooand&foovalues are equivalent in C and have same type. The&operator here is correct but redundant. Note that assigning a function pointer to avoid *is not valid in C. ``` void *fp1 = foo; // invalid int (*fp2)() = foo; // valid int (*fp3)() = &foo; // valid ``` (These are actually declarations but the constr...
I have a nanosleep function in while loop. This is an example I found in book "Linux System Programming: Talking Directly to the Kernel and C Library" ``` while(nanosleep(a, b) && errno==EINTR){ struct timespec *tmp =a; a=b; b=tmp; } ``` Works perfect but I am not sure how can I check for...
You can simply store the return value in the loop condition: ``` int ret; while((ret = nanosleep(a, b)) && errno==EINTR){ struct timespec *tmp =a; a=b; b=tmp; } if (ret) { perror("nanosleep"); exit(1); } ```
In the C++ standard 18.4 it specifies: ``` typedef 'signed integer type' intmax_t; ``` By the standard(s) on a platform with a 64-bitlong intand a 64-bitlong long intwhich should this "signed integer type" be? Note thatlong intandlong long intaredistinctfundamental types. The C++ standard says: The header defines...
Yes, your reasoning is correct. Most real-world implementations choose the lowest-rank type satisfying the conditions.
I have this function declaration: ``` void gaussian_blur ( const unsigned char* const inputChannel, unsigned char* const outputChannel, const float* const filter ) {..} ``` I'm new to C. I've gone through basic tutorials and understand the concept of pointers and constants, but I can't make sense what i...
``` const unsigned char* const inputChannel; ``` Input channel is a constant pointer to a constant unsigned char. ``` unsigned char* const outputChannel; ``` OutputChannel is a constant pointer to a unsigned char. ``` const float* const filter ``` filter is a constant pointer to a constant float. Constant pointe...
I need read the stdin in Linux, although my program will receive only messages without new line. I tried this code, but is not working: ``` int main ( void ) { char p_char[48]; memset( p_char, 0, sizeof(p_char) ); fcntl( STDIN_FILENO, F_SETFL, FNDELAY ); read( STDIN_FILENO, p_char, sizeof(p_char) );...
You'd need to change the terminal settings so that each character is sent immediately. You can do it by manipulatingtermios(the man page has details). Essentially it just involves creating twotermiosstructures, initialising one with the current settings withtcgetattr, copying the struct to the other structure, modify...
I have an Win32 application with no window written in C. My question is: is there any way to handle the termination of my application. Ex. closing it from the task manager or via the console.
It is unclear from the question, but if this is a console mode application then you can callSetConsoleCtrlHandlerto install a callback that Windows will call just before it terminates your app. Beware that this callback runs on a separate thread and that you have to complete the callback function quickly. If it is a...
``` int main(){ char a[80] = "Angus Declan R"; char b[80]; char *p,*q; p = a; q = b; while(*p != '\0'){ *q++ = *p++; } *q = '\0'; printf("\n p:%s q:%s \n",p,q); puts(p); //prints the string puts(q); //doesnt print the string return 0; } ``` why the strings are not copied from p to q? when trying to prin...
add ``` p = a; q = b; ``` again before ``` printf("\n p:%s q:%s \n",p,q); puts(p); //prints the string puts(q); //doesnt print the string ``` Because thepandqpointers are incremented in thewhileloop and they are not pointing any more in the beginning of theaandbchar arrays BTWand Just as remark: You can replac...
I know that you can tell C to interpret a value as hex using printf("\xab"). If you input "\xab" to a C program as input it will interpret it as the characters -x-a-b. Is there any way to embed printf-style formatting information into raw input?
No, it all depends on how the code that reads the characters interpret them. You can't magically force a program to do something else from the outside, by giving it text. I guess a buffer overrun attack is a bit of a counter-example, but that's rather extreme. Many programs that use e.g.strtol()automatically support0...
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he...
Yes, you can use C programming language on Mac. The main programming language on Mac OS X is Objective-C, which is based on C language. You can download Xcode from the AppStore and start developing your own application. C is perfectly fine, as it is subset of Objective-C. I suggest you to start here:http://www.cocoa...
How much space a character takes when saving it to file in binary mode [8 bits or 12 bits]? ``` fprintf(f,"%ld",ch); ``` also if I save a long [say 5] then how much space it gonna take 3bits [101] or 8bits[00000101]
``` fprintf(f,"%ld",...) ``` will convert your number to a decimal number and will take log_10(ch) bytes to store. When you store it withfwriteit will take as much bytes as you specify. ``` fwrite (buffer , 1 , sizeof(buffer) , f ) ``` Also attention as you will never store single bits to a file as the read write ...
How to kill/close application/process by PID or name? I tried to use C function but it doesn't work. (E.g. try to kill LinkedIn application/process). ``` pid_t pid = 3696; //GetProcessPIDForLinkedIn(); kill(pid, SIGQUIT); ``` I don't plan to deploy it on App Store but it should work for non jailbroken devices
Unless you are root and on a jailbroken device, you cannot kill other apps programmatically. Apps live in a sandbox and are unable to affect other apps or their documents or data. THe only exception is launching an app and passing data to it. If all these apps are your own then you could use this as by passing them s...
Below is the snippet of the code: ``` int main(void) { char sizing[] = "manshcanshcnams cndhan sndhcna snshans"; char *xyz = malloc(sizeof(char)); printf("%ld\n",sizeof(xyz)); xyz = sizing; // IT SHOULD FAIL HERE printf("Fail %s\n",xyz ); return 0; ``` } As you can see that I am trying t...
You can't copy strings with=.xyz = sizingjust modifies the variablexyzso that it points to the arraysizing, instead of pointing to the memory you malloced. So, your memory is leaked but there is no undefined behavior (except that you forgot to include<stdio.h>and<stdlib.h>).