question
stringlengths
25
894
answer
stringlengths
4
863
I am currently trying to use Google Protocol Buffers for C language. I am a little unsure as to how to create a C union using GPB. For example, with a proto file as follows: ``` message msgToSend { required Type msg_type=1; //Type is a predefined enum to determine message type optional ReqMsg1 msg1=2; optional ReqMsg2 msg2=3; } ``` I expect above to generate aunionupon compilation but a structure is generated as follows: ``` struct _msgToSend { ProtobufCMessage base; Type msg_type; ReqMsg1 msg1; ReqMsg2 msg2; } ```
In protobuf there is a dedicated structure for that (I'm using it in C++ though, not sure if it will work in pure C): ``` message MyUnion { oneof MyUnionOneof { bool booleanValue = 1; string stringValue = 2; } } ``` Check out this link:https://developers.google.com/protocol-buffers/docs/proto#oneof
``` int* p; printf("%d", sizeof(p)); ``` The answer would be 4 bytes! I am using C How to declare a pointer of a size (2 byte)? Does it depend on the compiler? As far as I know, C and ansi C are the same .. would this differ in ansi C?
The C standard intentionally doesn't specify sizes for pointers. Itevenallows for pointer sizes to be different for different types:sizeof(type1*)is not necessarily the same assizeof(type2*)! This allows for C to target the most regular to the most exotic architectures. Lastly, your program behaviour isundefined: you should use%zuas the formatter for asizeofreturn. (Note thatsizeof(p)isdefined despitepbeing uninitialised - that's becausesizeof(p)is evaluated atcompiletime.)
Is there a way to know whether CPU is 32 bit or 64 bit without the use of sizeOf operator? Can any other code be written for this?
In this questionHow to determine whether a given Linux is 32 bit or 64 bit? To check if system is 32 or 64 bit kernel, you can call ``` system("getconf LONG_BIT") ``` And check it's return. If it says 64 it's a 64bit kernel, if it's 32 it's 32bit one. To check if the cpu supports 64bits, you can check it in the file /proc/cpuinfo if it has the flag "lm" (Long Mode) ``` system("grep flags /proc/cpuinfo | grep -c lm") ``` If the return is 1 then lm flag is present (64 bit), if it's 0 it's not (32 bit) This is linux only though. Other options are in the question linked at the begining. Some includes checkinglimits.hfor example.
What is Linux or POSIX equivalent ofVirtualAllocwith MEM_TOP_DOWN, if there's any?
POSIX does not seem to have anything when it comes tommap. The GNU C Library version ofmmap(BSD libc also has these flags) extends its functionality though, with aMAP_FIXED(allocate at specific address) andMAP_GROWSDOWN(which is named similarly butMEM_TOP_DOWNactually has nothing to do with this option). Both GNU and BSD's manpages discourage use of these functions, because of portability issues (you're bound to the specific C library, and not fully OS independent anymore). You'd need to determine a way to find the topmost address. I suggest trying to allocate at the top, and moving the passed address down until it does succeed. The step size and "search" algorithm will depend on your need of precision and performance.
I am currently trying to use Google Protocol Buffers for C language. I am a little unsure as to how to create a C union using GPB. For example, with a proto file as follows: ``` message msgToSend { required Type msg_type=1; //Type is a predefined enum to determine message type optional ReqMsg1 msg1=2; optional ReqMsg2 msg2=3; } ``` I expect above to generate aunionupon compilation but a structure is generated as follows: ``` struct _msgToSend { ProtobufCMessage base; Type msg_type; ReqMsg1 msg1; ReqMsg2 msg2; } ```
In protobuf there is a dedicated structure for that (I'm using it in C++ though, not sure if it will work in pure C): ``` message MyUnion { oneof MyUnionOneof { bool booleanValue = 1; string stringValue = 2; } } ``` Check out this link:https://developers.google.com/protocol-buffers/docs/proto#oneof
``` int* p; printf("%d", sizeof(p)); ``` The answer would be 4 bytes! I am using C How to declare a pointer of a size (2 byte)? Does it depend on the compiler? As far as I know, C and ansi C are the same .. would this differ in ansi C?
The C standard intentionally doesn't specify sizes for pointers. Itevenallows for pointer sizes to be different for different types:sizeof(type1*)is not necessarily the same assizeof(type2*)! This allows for C to target the most regular to the most exotic architectures. Lastly, your program behaviour isundefined: you should use%zuas the formatter for asizeofreturn. (Note thatsizeof(p)isdefined despitepbeing uninitialised - that's becausesizeof(p)is evaluated atcompiletime.)
How can I pass strings from a C function to function in ADA (C-ADA binding)? Any examples would be appreciated.
Basically, you would create a subprogram on the Ada side that maps you C function: ``` procedure Foo (C : Interfaces.C.Strings.chars_ptr); pragma import (C, Foo, "foo"); ``` so that from Ada you have access tofoo(). The custom is to then provide a more Ada friendly version, with: ``` procedure Foo (C : String) is S : Interfaces.C.Strings.chars_ptr := New_String (C); begin Foo (S); Free (S); end Foo; ``` If on the other hand the procedure is written in Ada and you want to call it from C, you would use: ``` procedure Foo (C : Interfaces.C.Strings.chars_ptr); pragma Export (C, Foo, "foo"); ``` and from C you can then call: ``` extern void foo(char* c); foo("bar"); ```
Given the short notation to declare arrays, how do I specify the type of myArray to be arrays? ``` [] myArray = { //here [] should be array type {"obj1, "obj2"}, {"obj1, "obj2"} } ```
Assuming you want a two-dimensional array of character strings: ``` const char *myArray[][2] = { {"obj1", "obj2"}, {"obj1", "obj2"} /* any other elements */ }; ```
Can I add a C array into a objective-C NSArray? ``` NSArray * testArray = [NSArray arrayWithObjects: @"obj1", {"C array obj1", "C array obj2"}, nil]; ``` gives meExpected Expressionmessage error.
You cannot add plain C arrays toNSArray. But as storing a C array means storing a pointer, you can wrap that pointer into anNSValueand store that instead: ``` char *someCArray = ...; NSArray *array = @[[NSValue valueWithPointer:someCArrray]]; ``` Keep in mind that you are only storing the pointer - and memory management is still up to you. Or you could wrap the memory of the array into some Objective-C object, likeNSData, but there should be very good reasons to go to such lengths. My guess in the wild is - without knowing the concrete use case - that you're better of converting the C data into objects themselves and store them "the Objective-C" way.
I know how to find duplicate elements in array but recently in an interview question, I was asked to find duplicate elements in array in a single pass meaning without using nested loops and recursion. I tried but failed. The interviewer wasn't kind enough to even give me a hint. So I came here to ask, Is it possible to find duplicate elements in array without nested loops/recursion? If yes can anybody give an example code? Also Library functions are not allowed P.SI would also like to know what impact does it have if we don't use loops or recursion. Is it related to complexity?
You can keep a hash table/dictionary with item counts for each item value.
In a multi-source file C application, which is the best place to put constant values, source file itself or in its header file? Provided that constant will be used in that source file only.Is it a good way to keepstatic constin header files?
Don't expose information you don't need to. If constant is an implementation detail of single compilation unit, there is no need to pollute global namespace. You can always add it to header later if needed.Depends on the nature of constant.staticcreates new constant for each compilation unit header is included in. If constant is huge, it's better to define it once in source file, and declare it withexternin the header.
It takes a lot of time to compile, and some random number shows up, apparently thescanf()doesn't ask for the input ``` #include <stdio.h> int main() { int a; //a = 1472464; scanf ("%d", &a); if ((a % 6) && (a %4) == 0) { printf("Input %d is divisible by 6 and 4\n", a); } else { printf(" Input %d is not divisible by 6 and 4\n", a); } printf("Hello, World!\n"); return 0; } ```
This line is wrong: ``` if ((a % 6) && (a %4) == 0) ``` It should be: ``` if ((a % 6) == 0 && (a %4) == 0) ``` I don't see any other obvious problem with the code.
I am wondering if any problems may arise, when implementing a XBee point to point link using API mode if one is programmed using the Java XBee libraries and the other Ansi C libraries on a microcontroller. An API frame is an API frame but still.. I only need API mode to use the ACK and encryption.
No problems will arise, and you can even operate each XBee at a different baud rate. A module in API mode can communicate with a module running in "AT mode" (or transparent serial). A module in API mode 1 communicates just fine with API mode 2. DifferentATAOsettings affect local communications only. The options you select are solely for local communication between host and XBee module. That module then communicates with remote modules over the 802.15.4 network, and the receiving module sends data out to the host in whatever format is dictated by the local configuration.
I need some help with accessing a 2D array with pointers. I have 8 global char arrays declared like this: ``` char s1[4][16], s2[4][16], ... , s8[4][16]; ``` Their values are set later in main function. I have an array of 8 pointers to these arrays, ``` char (*s[8])[4][16]; ``` Each pointer in this array is assigned like this: ``` s[0] = &s1; s[1] = &s2; .. .. s[7] = &s3; ``` Now to access elements of s1, I do*s[0][i][j], however I do not get the same values as those ofs1. Same is the case fors2,s3etc. Can someone please tell what is going wrong?
Index operator[]have higher precedence than indirect operator*, so you have to use parenthesis to dereference the pointer to the array. Try doing(*s[0])[i][j].
I have a question on this string . for example: ``` char ex1[20]="Hello hi"; int choose; scanf("%d",&choose); ``` What should I do to make it print "hi" when user enters1and "hello" would be printed if he enters0? Thank you for your help.
The simplest solution would be: ``` if(choose == 1) printf("Hello\n"); else if(choose == 0) printf("hi\n"); else printf("Please enter 1 or 0.\n"); ``` You don't needex1here.
I am wondering what the best way to Determine how much stack space a program is using, are there any techniques or tools to generate the statistics, rather than counting by hand? The program is hoping to analyze is a C program in code composer, if that makes a difference. Thank you
You can fill the stack ram with some pattern (0xDEADBEEF for example) and then run for a while then examine the stack to see how much was used. You would still have to do the analysis to find the deepest paths, and then generate the deepest nested interrupts on top of that if it is ever possible in the application.
This question already has answers here:What are the implications of the linux __user macro?(3 answers)Closed7 years ago. Can you explain me this piece of code ? what does __user here mean ? ``` int create(struct mystruct __user *arg) { void __user *user_config; } ``` (I only post part of the function) Any reply is much appreciated. Thank you.
It tells the kernel developers that the pointer is user supplied, so it shouldn't be trusted and needs to be validated before operating on. There are many such definitions in Linux kernel. https://en.wikipedia.org/wiki/Sparse#Linux_kernel_definitions
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed7 years ago.Improve this question I have a source code that included"pbmpak.h"and I need the implementation of this header(pbmpak.c) to run the program. I found the header and downloaded that but I can't find the implementation.
I believe you should be able to get everything fromnetpbm. That is the suite that contains all the relevant conversion routines and looking at pbmpak.h, probably contains all the function definitions. Notice thatnetpbmreplacedpbmplussuite.
I am a newbie in C. Now I let my server create two threads listening to two different ports, both of them will callbind a port->listen()->accept(). Then there are two clients connecting to these two ports respectively. Then these two threads willaccept()and generate two file descriptors. What I am curious is that is it possible that the generated file descriptors can be the same integers?
A file descriptor is something that you are not expected to interpret - So it is actually "not your business" to know this ;) Within a process, file descriptors returned from system calls are guaranteed to beunique. So the two threads will receive two different integers (actually, multi-threading does not affect this question at all. The result is the same as if both sockets would have been opened in the main thread).
I am currently learning to use SDL2 in C and encountered a problem from which I couldn't find a solution so far I am trying to run a simple 2 frames animation loop in the middle of the screen, but after a seemingly set amount of loops the window stops responding ``` while (1) { SDL_RenderClear(window->renderer); test->o_update(sheet, test); SDL_RenderCopy(window->renderer, sheet->texture, &test->frame, &test->pos); SDL_RenderPresent(window->renderer); SDL_Delay(16); } ``` The update function updates the coordinates on the sheet of the SDL_rect named "frame" in the test structure, so that it switches to the next frame every 30 frame. Every frame I SDL_RenderCopy, and SDL_RenderPresent to update the screen. Is there something blatantly wrong in my way of doing things ?
The issue came from the lack of wait/poll on SDL events, the process eventually stops responding in those cases.
This question already has answers here:Function declaration: K&R vs ANSI [duplicate](3 answers)Closed7 years ago. i recently saw the following code in C which is said to be valid but I'm not sure. ``` int max(x,y) int x,y; { return (x>y)?x:y; } ``` Is this kind of function prototype valid? If so please give some reference to learn more about that.
This is the old-style "K&R" way of defining functions. The new way is better, so don't write code like this yourself.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed7 years ago.Improve this question I have a source code that included"pbmpak.h"and I need the implementation of this header(pbmpak.c) to run the program. I found the header and downloaded that but I can't find the implementation.
I believe you should be able to get everything fromnetpbm. That is the suite that contains all the relevant conversion routines and looking at pbmpak.h, probably contains all the function definitions. Notice thatnetpbmreplacedpbmplussuite.
I am a newbie in C. Now I let my server create two threads listening to two different ports, both of them will callbind a port->listen()->accept(). Then there are two clients connecting to these two ports respectively. Then these two threads willaccept()and generate two file descriptors. What I am curious is that is it possible that the generated file descriptors can be the same integers?
A file descriptor is something that you are not expected to interpret - So it is actually "not your business" to know this ;) Within a process, file descriptors returned from system calls are guaranteed to beunique. So the two threads will receive two different integers (actually, multi-threading does not affect this question at all. The result is the same as if both sockets would have been opened in the main thread).
I am currently learning to use SDL2 in C and encountered a problem from which I couldn't find a solution so far I am trying to run a simple 2 frames animation loop in the middle of the screen, but after a seemingly set amount of loops the window stops responding ``` while (1) { SDL_RenderClear(window->renderer); test->o_update(sheet, test); SDL_RenderCopy(window->renderer, sheet->texture, &test->frame, &test->pos); SDL_RenderPresent(window->renderer); SDL_Delay(16); } ``` The update function updates the coordinates on the sheet of the SDL_rect named "frame" in the test structure, so that it switches to the next frame every 30 frame. Every frame I SDL_RenderCopy, and SDL_RenderPresent to update the screen. Is there something blatantly wrong in my way of doing things ?
The issue came from the lack of wait/poll on SDL events, the process eventually stops responding in those cases.
This question already has answers here:Function declaration: K&R vs ANSI [duplicate](3 answers)Closed7 years ago. i recently saw the following code in C which is said to be valid but I'm not sure. ``` int max(x,y) int x,y; { return (x>y)?x:y; } ``` Is this kind of function prototype valid? If so please give some reference to learn more about that.
This is the old-style "K&R" way of defining functions. The new way is better, so don't write code like this yourself.
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed7 years ago.Improve this question The function:int atexit (void (*function) (void))allows us to call the same exit handling functions more than once. Why would you call the exit handlers more than once? Could you give me an example where it makes sense to call the same exit handler more than once.
I would reverse the diagnostic: the functionatexithas no simple way to know if a handling function has already been registered, so it does not even try to identify that. For that reason it does not forbid it. But I agree with you I cannot find a real user case for registering the same handler more than once.
I have written code like follow: ``` int a = -1; unsigned int b = 0xffffffff; if (a == b) printf("a == b\n"); else printf("a != b\n"); printf("a = %x b = %x\n", a, b); return 0; ``` And the result is as follow: It shows that a and b are equal. So I want to know how the computer make this judgement?
In any arithmetic operation with a signed integeraand unsigned integerbas operands,awill be implicitly cast to unsigned. Since-1signedin this caseis0xffffffffunsigned,aandbcompares equal.
I have a "standard " project in eclipse with source and header files included. Although all the source files within the project are compiled, despite of the fact that these source files are not included by themain.cwhere is the main routine. What I want is only one compilation unit (one source file to be compiled) and the other source files to be included#include "some-folder/some-file.c"directly. Not to be compiled separately as it is now. I tried to remove the path to those files from theBuild variablesbut they are still compiled individually. Please guide me how to achieve what I want.
I'm not familiar with the C tools and, like others, don't know why you would do this but can you put the other source files in a separate folder that isn't marked as a source folder? The source files in the "non source" folder shouldn't be compiled automatically.
what have i done wrong (or didn't do) thatgdbis not working properly for me? ``` root@6be3d60ab7c6:/# cat minimal.c int main() { int i = 1337; return 0; } root@6be3d60ab7c6:/# gcc -g minimal.c -o minimal root@6be3d60ab7c6:/# gdb minimal GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1 . . . Reading symbols from minimal...done. (gdb) break main Breakpoint 1 at 0x4004f1: file minimal.c, line 3. (gdb) run Starting program: /minimal warning: Error disabling address space randomization: Operation not permitted During startup program exited normally. (gdb) (gdb) print i No symbol "i" in current context. ```
If you're using Docker, you probably need the--security-opt seccomp=unconfinedoption (as well as enabling ptrace): ``` docker run --cap-add=SYS_PTRACE --security-opt seccomp=unconfined ```
what have i done wrong (or didn't do) thatgdbis not working properly for me? ``` root@6be3d60ab7c6:/# cat minimal.c int main() { int i = 1337; return 0; } root@6be3d60ab7c6:/# gcc -g minimal.c -o minimal root@6be3d60ab7c6:/# gdb minimal GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1 . . . Reading symbols from minimal...done. (gdb) break main Breakpoint 1 at 0x4004f1: file minimal.c, line 3. (gdb) run Starting program: /minimal warning: Error disabling address space randomization: Operation not permitted During startup program exited normally. (gdb) (gdb) print i No symbol "i" in current context. ```
If you're using Docker, you probably need the--security-opt seccomp=unconfinedoption (as well as enabling ptrace): ``` docker run --cap-add=SYS_PTRACE --security-opt seccomp=unconfined ```
``` typedef void *STACK_ENTRY; STACK_ENTRY *create_stack_entry(void *value) { STACK_ENTRY *entry = malloc(sizeof(*value)); *entry = *value; return entry; } ``` I tried to make a universal function to create aSTACK_ENTRYthat should be able to have any type. So I use a void pointer as a parameter. I allocate memory with the size of the type of the value and then I would like to give the value to the pointee of theSTACK_ENTRY. But I get the following error: ``` prog.c:34:9: error: void value not ignored as it ought to be *entry = *value; ^ ``` How can I fix that?
Code needs to cope with size. Pass in size when callingcreate_stack_entry(). No cast needed. ``` // STACK_ENTRY *create_stack_entry(void *value) STACK_ENTRY *create_stack_entry(void *value, size_t size) { STACK_ENTRY *entry = malloc(size); if (entry) memcpy(entry, value, size); return entry; } ```
I have to read data from a device which is 4 bytes long so that I have declared array like ``` char data[4] = {0}; ``` I will parse this as per index and guarantee to stop at index 3. data[0]..data[3] In this case there is no room for NUL('\0'). I want to know is this considered safe or I should declare array as ``` char data[5] = {0}; ``` This array will not be used in str* series of functions.
If the data to be read is a string of4bytes or if it is greater than4bytes and you are usingcharas a character array instead of string then no need to worry. Otherwise you have to care about'\0'.
Is it good practice to use the weak attribute in production code so that for test code one can override functions?
I don't know if it isgood practice, but there are ways to override functions in test code that do not interfere with production code: using macros that redefine the function names you wish to overrideusingLD_PRELOADusing macros that expand to__weakin debug mode and to nothing in production mode.
Is there a way for the user to enter nothing as input(for character array) in C? I tried the following: Using a'\n'character as delimiter:scanf("%[^\n]s",str);it gave me junk.Used a custom delimiter like ' ` '. But additional task was required as in case if it was entered in between, etc.Tried using command line arguments for input string (as we know no input givesOne argument expected)Tried enteringnullbyalt+space. Did not work either. Please suggest me a new way or correct me if I am doing any of the above steps wrong. Note: I am using Windows.
If you take your input from command line arguments, you can specify an empty string with: ``` C:\>myprogram "" ``` argcwill be2andargv[1]will be a pointer to an empty string.
I am trying to modify the apache source code in order to let it read the files inside a zip file instead of getting it directly from www folder. example: instead of having www/index.htm I want to have a zip file that contains the index.htm I've been working on this for days. Is it possible or I am just wasting my time?
You may indeed be wasting your time, but that doesn't mean it's not possible. Apache certainly doesn't have any native capacity to treat a zipfile as a filesystem, but there are solutions you can pursue. The simplest option would be to use something likearchivemountto expose the archive as a filesystem on the host. This will let Apache -- and anything else -- treat it like a directory tree.
I have to read data from a device which is 4 bytes long so that I have declared array like ``` char data[4] = {0}; ``` I will parse this as per index and guarantee to stop at index 3. data[0]..data[3] In this case there is no room for NUL('\0'). I want to know is this considered safe or I should declare array as ``` char data[5] = {0}; ``` This array will not be used in str* series of functions.
If the data to be read is a string of4bytes or if it is greater than4bytes and you are usingcharas a character array instead of string then no need to worry. Otherwise you have to care about'\0'.
Is it good practice to use the weak attribute in production code so that for test code one can override functions?
I don't know if it isgood practice, but there are ways to override functions in test code that do not interfere with production code: using macros that redefine the function names you wish to overrideusingLD_PRELOADusing macros that expand to__weakin debug mode and to nothing in production mode.
Is there a way for the user to enter nothing as input(for character array) in C? I tried the following: Using a'\n'character as delimiter:scanf("%[^\n]s",str);it gave me junk.Used a custom delimiter like ' ` '. But additional task was required as in case if it was entered in between, etc.Tried using command line arguments for input string (as we know no input givesOne argument expected)Tried enteringnullbyalt+space. Did not work either. Please suggest me a new way or correct me if I am doing any of the above steps wrong. Note: I am using Windows.
If you take your input from command line arguments, you can specify an empty string with: ``` C:\>myprogram "" ``` argcwill be2andargv[1]will be a pointer to an empty string.
I am trying to modify the apache source code in order to let it read the files inside a zip file instead of getting it directly from www folder. example: instead of having www/index.htm I want to have a zip file that contains the index.htm I've been working on this for days. Is it possible or I am just wasting my time?
You may indeed be wasting your time, but that doesn't mean it's not possible. Apache certainly doesn't have any native capacity to treat a zipfile as a filesystem, but there are solutions you can pursue. The simplest option would be to use something likearchivemountto expose the archive as a filesystem on the host. This will let Apache -- and anything else -- treat it like a directory tree.
The output of following code piece is 0.000000. Please tell me why. ``` #include <stdio.h> main() { printf("%f\n",123.456789l); } ``` I am using GCC 4.9 in Linux (Debian 8.3).
printf's%fformat expects a plain double. For long double you need%Lf. (And that's a capital L.) It's hard to say exactly why you got 0.000, but when you pass one type (long double) to a format specifier that expects something else (%f, plain double), you almost never get what you want. This is one thing newer compilers can be really helpful about. When I tried your code, my copy of gcc (4.6.3) was as silent as yours, but clang said "warning: format specifies type 'double' but the argument has type 'long double'", and I'm pretty sure newer versions of gcc would complain, too.
This question already has answers here:What is the '-->' operator in C/C++?(28 answers)Closed7 years ago. I am very new to programming. I know about numerical and logical operators. But I have never seen this-<--operator. I searched over internet but got nothing helpful. Here is the code: ``` int i=5; while(0 <-- i){ printf("%d\n", i); } ``` The output is: ``` 4 3 2 1 ``` What is this operator? What does it do? Edit: I also wish to know about other confusingcomposite operatorslike this.
<--is not an operator, it is<and--written without space. Just to make it clear, I rewrite the code like this- ``` while(0 < --i) ``` First the value ofiis decreased, and then compared if it is greater than0. Similar question was askedhere.
I am using the following macro successfully. ``` #define SECTION(a) __attribute__ ((section(#a))) ``` Now in the same file I defined a new macro, and I tried using it in my code: ``` #define GP_RAM_DATA_1 SECTION(".gp_ram1.data") GP_RAM_DATA_1 int foo = 5; ``` The code compiles and runs fine, without compiler warnings or errors, however Eclipse marks the line I use the macro yellow, with a note for syntax error. Is there anything wrong with my code? Is it an Eclipse bug, or should I change anything?
It is an Eclipse bug. If the compiler is happy (and you do not disable warnings), all is good.
I am trying to write a program that accesses a MYSQL database. The database is used by a PHP Script and the C program. My C program is in a sleep mode most of the time and needs to be informed if something is changed by the PHP script in the database. Therefor I wanted to call a little process which sends an interrupt to my C program, which then connects to the database and downloads the changes. The database connection and everything else is working fine. But I have no idea how to realize this interrupt, and I dont want to simply poll my database. Has anyone an advice for me?
You probably want to use a signal which you send withposix_killfrom php and receive it with a signal handler installed withsignalfrom your C code. However, you will probably have to run you C program as the same user running your web server for php being allowed to send signals to your C process.
So I have this struct ``` struct cell { int downwall; int rightwall; }; ``` I have dynamically allocated memory for a 2d array of struct cell (struct cell ** array) However when I try to access a certain cell with the command ``` array[i][j] -> downwall = 0; ``` I get this error: invalid type argument of '->' (have 'struct cell')
Use ``` array[i][j].downwall = 0; ``` instead. You would have used->ifarrray[i][j]had typestruct cell*which it doesn't have. It has typestruct cell.
Is there a way to check if pointer was initialized? I have a struct that cointain array of pointers ``` typedef struct foo { int* ptr1; int* ptr2; int* ptr2; ... int* ptr100; } ``` and then my code is assigning adresses to those pointers (inside loop). But before adress is assigned i want to check if pointer is already containing adress. I know that i can initliazie every pointer withNULLand then check this with: ``` if(ptr1 == NULL) do something ``` But is there way to write something similiar but without initialization ofptr?
An uninitialized variable can contain any value. Therefore, it is not possible to find out if a variable is uninitialized as it can look just like an already initialized variable. The only way to make sure that a variable is initialized is to explicitly write a value (for example,NULL) to it as you already noted in your question.
I am trying to print a parenthesis using: printf("\)"); However, it is giving me the following warning: warning: unknown escape sequence '\)' I can't seem to find a clear explanation anywhere on how to fix this. I realize it's just a warning, but since it's still treating that as a parenthesis it's throwing off all my other parentheses and giving me errors so that the code does not compile. EDIT: Treating it as a regular character and just saying printf(")") is not working. It's still mismatching all the parentheses and I have gone through multiple times to make sure I'm not actually missing any.
The warning is coming from the C compiler. It is telling you that\is not a known escape sequence in C. You need to double-escape the slash, like so:\\ Edit:if you just want to print the parenthesis, i.e. the)then drop the slash altogether and use: ``` printf(")"); ```
Will this function cause memory leak? The function is : ``` double list(double *list2){ double *list3=(double *)malloc(sizeof(double)); some operations... return *list3; } ``` update: could this help? ``` int main(){ operations... double list4; list4=list(&list4); free(&list4); return 0; } ```
Yes, it does: it is returning a copy of the value of what is stored in the allocated memory, but the allocated memory itself is leaked (because the address has been "lost").
I have a problem in which I need to declare some variables as natural numbers. Which is the propper fundamental type that I should use for variables that should be natural numbers ? Like for integers is int ...
The following types resemble natural numbers set with 0 included in C++: unsigned charunsigned short intunsigned intunsigned long intunsigned long long int, since C++11. Each one differs with the other in the range of values it can represent.
I'm returning0all over the place in a python script but would prefer something more semantic, something more readable. I don't like that magic number. Is there an idea in python similar to how inCyou can returnEXIT_SUCCESSinstead of just 0? I was unable to find it here:https://docs.python.org/3.5/library/errno.html
I'm returning0 returnis not how you set your script's exit code in Python. If you want to exit with an exit code of 0, just let your script complete normally. The exit code will automatically be set to 0. If you want to exit with a different exit code,sys.exitis the tool to use. If you're using return values of 0 or 1 within your code to indicate whether functions succeeded or failed, this is a bad idea. You should raise an appropriate exception if something goes wrong.
I have a problem in which I need to declare some variables as natural numbers. Which is the propper fundamental type that I should use for variables that should be natural numbers ? Like for integers is int ...
The following types resemble natural numbers set with 0 included in C++: unsigned charunsigned short intunsigned intunsigned long intunsigned long long int, since C++11. Each one differs with the other in the range of values it can represent.
I'm returning0all over the place in a python script but would prefer something more semantic, something more readable. I don't like that magic number. Is there an idea in python similar to how inCyou can returnEXIT_SUCCESSinstead of just 0? I was unable to find it here:https://docs.python.org/3.5/library/errno.html
I'm returning0 returnis not how you set your script's exit code in Python. If you want to exit with an exit code of 0, just let your script complete normally. The exit code will automatically be set to 0. If you want to exit with a different exit code,sys.exitis the tool to use. If you're using return values of 0 or 1 within your code to indicate whether functions succeeded or failed, this is a bad idea. You should raise an appropriate exception if something goes wrong.
I have written the following code to print only one space if there are more than one space. ``` #include<stdio.h> void main() { int c; while((c=getchar())!=EOF) { if(c==' '||c=='\t') { while(c==' '||c=='\t') c=getchar(); putchar(' '); putchar(c); } else putchar(c); } } ```
You need to typeCtrl+Don a line, on its own, after aEnter,or twoCtrl+Din a row. ``` ./a.out foo bar<ENTER> <Ctrl+D> ``` or ``` ./a.out foo bar<Ctrl+D><Ctrl+D> ```
There's something that I don't get with the binary search code on C. ``` int binarySearch(int a[], int n, int x) { int low=0, mid, high=n-1; while(low <= high) { mid = (low + high) / 2; if (x < a[mid]) high = mid - 1; else if (x > a[mid]) low = mid + 1; else return mid; } return -1; } ``` Why does the while loopwhile(left<=right)can't be written:while(left<right)? Will this change effect things?
Take a simple case of ``` int a[1] = {5}; printf("%d\n", binarySearch(a, 1, 5)); ``` Withwhile(low < high), code prints -1 (did not find - wrong answer). Withwhile(low <= high), code prints 0 (found - right answer).
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.Closed7 years ago.Improve this question I tried to experiment with bit manipulations on a byte. At first I tried to say that I have1111 1111(256) and1000 0000(128). So I do this: ``` printf("%u\n", 256 & 128); ``` I expect to get128but I get0. So I tried: ``` printf("%u\n", ((unsigned char) 256) & ((unsigned char) 128)); ``` But that gives me the same result. What is wrong with that?
1111 1111is255 So try ``` printf("%u\n", 255 & 128); ^^^ ``` Take into account that the type of the integer constants255and128isint.
There's something that I don't get with the binary search code on C. ``` int binarySearch(int a[], int n, int x) { int low=0, mid, high=n-1; while(low <= high) { mid = (low + high) / 2; if (x < a[mid]) high = mid - 1; else if (x > a[mid]) low = mid + 1; else return mid; } return -1; } ``` Why does the while loopwhile(left<=right)can't be written:while(left<right)? Will this change effect things?
Take a simple case of ``` int a[1] = {5}; printf("%d\n", binarySearch(a, 1, 5)); ``` Withwhile(low < high), code prints -1 (did not find - wrong answer). Withwhile(low <= high), code prints 0 (found - right answer).
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.Closed7 years ago.Improve this question I tried to experiment with bit manipulations on a byte. At first I tried to say that I have1111 1111(256) and1000 0000(128). So I do this: ``` printf("%u\n", 256 & 128); ``` I expect to get128but I get0. So I tried: ``` printf("%u\n", ((unsigned char) 256) & ((unsigned char) 128)); ``` But that gives me the same result. What is wrong with that?
1111 1111is255 So try ``` printf("%u\n", 255 & 128); ^^^ ``` Take into account that the type of the integer constants255and128isint.
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed7 years ago.Improve this question ``` double *p; p = malloc(sizeof(p)); if (p != NULL) { *p = 5.15; } ``` For some reason,p = malloc(sizeof(p));doesn't work. I try to allocate as much memory aspneeds. What is wrong with that?
I try to allocate as much memory aspneeds. pitself (as a variable) has got the (own) memory allocated, what you're trying is basically allocate the memory for whichpwill be pointing to. Here,ppoints to adouble, so it needs to have a memory area to be able to store adoublevalue. So, the allocation should be equal to the size of adouble, i.e, ``` p = malloc(sizeof*p); ```
I called apthread_mutex_lock(&th)in a thread then I want to unlock the mutex in another threadpthread_mutex_unlock(&th) Is it possible to do that? Or the mutex should be unlocked in the same thread ?
It should be unlocked in the same thread. From the man page: "If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, undefined behavior results." (http://pubs.opengroup.org/onlinepubs/009604499/functions/pthread_mutex_lock.html)
I use Ubuntu 15.10 64 bit. gcc-5-multilib, g++-5-multilib, libc6-i386, kernel headers and all build toolchain are installed. When I try to compile 32 bit library (for linux) like: ``` gcc -m32 -fPIC -shared -Wl,-soname,mylib.so -o mylib.so mylib.c ``` I get an error: ``` /usr/include/bits/socket.h:345:24: fatal error: asm/socket.h: No such file or directory ``` What can I do to compile a code with#include <sys/socket.h>on 64 bit for 32 bit linux?
You need to provide the path of asm. Just check the path and link like this. Depending on system path may vary. Most of the time downloadinggcc-multilibsolve this issue. ``` $cd /usr/include $sudo ln -s asm-generic/ asm ``` OR ``` $cd /usr/include $sudo ln -s x86_64-linux-gnu/asm asm ```
I am using a 64bit machine When using the structure ``` typedef struct node{ unsigned int p; //4 bytes struct node* next;//8bytes }Node; //sizeof(Node) is 16 bytes ``` I know that this is due to structure padding. If I use structure packing using ``` typedef struct __attribute__((__packed__)) //sizeof(Node) is 12 bytes ``` Should I expect any performance degradation using packing or is it system dependent? Compiler isgcc (GCC) 4.4.7 I have tested my code with packed and unpacked structure and there doesn't seem to be any difference in the performance.
That's not a lot of information. The answer will also depends on your Node allocation strategy, on whether you embed the node in your data or store it separately, on how big your cache lines are, what kind of work you do, etc. Measure your runtime with and without packing (in your specific application) - you'll have the answer.
I want to calculate a mask to perform logical right shift, this is my code: ``` int mask; int arl = x >> n; mask = ~((~0) << (32 - n)); return arl & mask; ``` whennequals to0, I think mask should be0xFFFFFFFF, but it didn't work. I used gdb to debug, and got this: ``` (gdb) p/t ~((~0) << (32 - n)) $2 = 11111111111111111111111111111111 (gdb) p/t mask $3 = 0 ``` Why mask is0?
You invokedundefined behaviorifintis 32-bit long or shorter. Quote fronN12566.5.7 Bitwise shift operators If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined. Try this:mask = n >= 32 ? ~0 : ~((~0) << (32 - n));
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed7 years ago.Improve this question ``` double *p; p = malloc(sizeof(p)); if (p != NULL) { *p = 5.15; } ``` For some reason,p = malloc(sizeof(p));doesn't work. I try to allocate as much memory aspneeds. What is wrong with that?
I try to allocate as much memory aspneeds. pitself (as a variable) has got the (own) memory allocated, what you're trying is basically allocate the memory for whichpwill be pointing to. Here,ppoints to adouble, so it needs to have a memory area to be able to store adoublevalue. So, the allocation should be equal to the size of adouble, i.e, ``` p = malloc(sizeof*p); ```
I called apthread_mutex_lock(&th)in a thread then I want to unlock the mutex in another threadpthread_mutex_unlock(&th) Is it possible to do that? Or the mutex should be unlocked in the same thread ?
It should be unlocked in the same thread. From the man page: "If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, undefined behavior results." (http://pubs.opengroup.org/onlinepubs/009604499/functions/pthread_mutex_lock.html)
I use Ubuntu 15.10 64 bit. gcc-5-multilib, g++-5-multilib, libc6-i386, kernel headers and all build toolchain are installed. When I try to compile 32 bit library (for linux) like: ``` gcc -m32 -fPIC -shared -Wl,-soname,mylib.so -o mylib.so mylib.c ``` I get an error: ``` /usr/include/bits/socket.h:345:24: fatal error: asm/socket.h: No such file or directory ``` What can I do to compile a code with#include <sys/socket.h>on 64 bit for 32 bit linux?
You need to provide the path of asm. Just check the path and link like this. Depending on system path may vary. Most of the time downloadinggcc-multilibsolve this issue. ``` $cd /usr/include $sudo ln -s asm-generic/ asm ``` OR ``` $cd /usr/include $sudo ln -s x86_64-linux-gnu/asm asm ```
I am using a 64bit machine When using the structure ``` typedef struct node{ unsigned int p; //4 bytes struct node* next;//8bytes }Node; //sizeof(Node) is 16 bytes ``` I know that this is due to structure padding. If I use structure packing using ``` typedef struct __attribute__((__packed__)) //sizeof(Node) is 12 bytes ``` Should I expect any performance degradation using packing or is it system dependent? Compiler isgcc (GCC) 4.4.7 I have tested my code with packed and unpacked structure and there doesn't seem to be any difference in the performance.
That's not a lot of information. The answer will also depends on your Node allocation strategy, on whether you embed the node in your data or store it separately, on how big your cache lines are, what kind of work you do, etc. Measure your runtime with and without packing (in your specific application) - you'll have the answer.
I want to calculate a mask to perform logical right shift, this is my code: ``` int mask; int arl = x >> n; mask = ~((~0) << (32 - n)); return arl & mask; ``` whennequals to0, I think mask should be0xFFFFFFFF, but it didn't work. I used gdb to debug, and got this: ``` (gdb) p/t ~((~0) << (32 - n)) $2 = 11111111111111111111111111111111 (gdb) p/t mask $3 = 0 ``` Why mask is0?
You invokedundefined behaviorifintis 32-bit long or shorter. Quote fronN12566.5.7 Bitwise shift operators If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined. Try this:mask = n >= 32 ? ~0 : ~((~0) << (32 - n));
I have this method in C, where I delete a row from a table. I want to pass a parameter which is the primary key and then delete that row. Here is my method: ``` void eliminarAlumno(char *mat) { abrirBD(); error = sqlite3_exec(conexion, "delete from alumnos WHERE matricula='<mat>'", 0, 0, &msjError); comprobarError(error, msjError); cerrarBD(); } ``` Where<mat>is the parameter. How can I do this?
You cannot do this directly. You need to first take an array, populate the required string andprintit into the array usingsprintf()/snprintf()and use the array as the argument tosqlite3_exec(). Something like ``` char argument[128] = {0}; //make sure the final array fits in here sprintf(argument, "delete from alumnos WHERE matricula='%s'", mat); error = sqlite3_exec(conexion, argument, 0, 0, &msjError); ``` should do the job.
How can I declare atypedef structin othertypedef struct? ``` typedef struct { char* type; char* destination; float price; typedef struct { int date; int month; int year; }date; }Offer; ``` I tried something like this but I don't know if its correctly. I want to declare in typedef struct another typedef struct for date format.
Try this: ``` typedef struct { char* type; char* destination; float price; struct { int day; int month; int year; } date; } Offer; ``` This definesdateas being of an anonymous struct. If you need to have this struct available elsewhere useShark's approach.
If I need to null-terminate a String, should I rather use\0or is a simple0also enough? Is there any difference between using ``` char a[5]; a[0] = 0; ``` and ``` char a[5]; a[0] = '\0'; ``` Or is\0just preferred to make it clear that I'm null-terminating here, but for the compiler it is the same?
'\0'is anescape sequencefor anoctal literalwith the value of 0. So there is no difference between them Side note: if you are dealing with strings than you should use astd::string.
I wish to create the following: ``` int amount[i]; ``` As a global variable (to practice using threads and mutexes) but the variableiis defined at launch of the program: ``` ./a.out 10 ``` How may I take the value through the main (argv[1]) and create the global accordingly?
You can use global pointer variable and then allocate memory based on argv[1]. ``` int *amount; int main(int argc, char *argv[]) { int count = atoi(argv[1]); amount = malloc(count * sizeof(int)); ... free(amount); return 0; } ```
If I need to null-terminate a String, should I rather use\0or is a simple0also enough? Is there any difference between using ``` char a[5]; a[0] = 0; ``` and ``` char a[5]; a[0] = '\0'; ``` Or is\0just preferred to make it clear that I'm null-terminating here, but for the compiler it is the same?
'\0'is anescape sequencefor anoctal literalwith the value of 0. So there is no difference between them Side note: if you are dealing with strings than you should use astd::string.
I wish to create the following: ``` int amount[i]; ``` As a global variable (to practice using threads and mutexes) but the variableiis defined at launch of the program: ``` ./a.out 10 ``` How may I take the value through the main (argv[1]) and create the global accordingly?
You can use global pointer variable and then allocate memory based on argv[1]. ``` int *amount; int main(int argc, char *argv[]) { int count = atoi(argv[1]); amount = malloc(count * sizeof(int)); ... free(amount); return 0; } ```
I want to measure the execution time of peace of code.I'm doing it with clock() function.Here the example: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> int main(void) { clock_t begin=0, end=0; begin = clock(); printf("hello world!!\n"); end = clock(); printf("Begin %E\n",begin); printf("End %E\n",end); printf("Clocks %E\n",end-begin); printf("Clocks per second %E\n", CLOCKS_PER_SEC); printf("Time %E\n", (end-begin)/CLOCKS_PER_SEC); return 0; } ``` Here the output: ``` hello world!! Begin 2.529616E-320 End 2.535545E-320 Clocks 5.928788E-323 Clocks per second 4.940656E-318 Time 0.000000E+00 ``` Time is 0!What I'm doing wrong? Is the output correct? Thanks a lot
%E needs floating point (floatordouble). You are sending integer values To divide ensure number is floating (end-begin+0.0)/CLOCKS_PER_SEC);
I want to inflate Microsoft office files using the zlib library. From what I have read, office files are just zip files with extensions like docx,xlsx etc. The unzip utility can actually decompress the files. Can I do the same with the zlib library?
zlibprovides the basic machinery needed to decompress deflate data and to compute CRCs, which is most of what you need to decode zip files. However zlib does not provide zip file format decoding, i.e. decoding the headers, which you would need to wrap around the zlib calls for decompression and check value computation. zlib does come withminizip, which is in the contrib directory of the source distribution, to do that job. You can also look atlibziporlibarchive, which use zlib and which provide zip file functions.
I would like to better understand floating point values and the imprecisions associated. Following are two snippets with slight modifications Snippet 1 ``` #include <stdio.h> int main(void) { float a = 12.59; printf("%.100f\n", a); } ``` Output: 12.5900001525878906250000000000000000000000000000000000000000000000000000000000000000000000000000000000 Snippet 2: ``` #include <stdio.h> int main(void) { printf("%.100f\n", 12.59); } ``` Output: 12.589999999999999857891452847979962825775146484375000000000000000000000000000000000000000000000000000 Why is there a difference in both the outputs? I'm unable to understand the catch.
In first case you have defined variable as a float and in second case you directly given the number. System might be consider direct number as a double and not float. So,I think may be it is because of system definition of float and double.
I have a question that might save a lot of debugging time for many people... Given a function: ``` void my_func(double value) ``` Is there any difference between the 2 following code lines? ``` double my_value = 1 - value; ``` and ``` double my_value = 1.0 - value; ``` I.e. given thatvalueisdouble, if I use1 - value, can I feel safe that the result will be the correct real number, like when using1.0 - value?
There is no difference. To subtract adoublefrom anint, theinthas to be promoted to adouble. I personally prefer to use1.0because I think that makes it clearer that it's not integer subtraction. But it's purely a style issue.
Why does C tell me this is unsafe even when I try to give the correct input? ``` #include <stdio.h> #include <stdlib.h> int main(void) { char id[8]; printf("Your ID:"); scanf("%s", id); printf("%s", id); return 0; } ``` I'm assuming because it could be exploited? How so?
scanf()doesn't set any bounds on what it takes as input, so it's easy to overflow youid[]buffer. Modern compilers will likely have stack smashing detection enabled, so if you compile viagccwithout setting the-fno-stack-protectorflag, the program will deliberately crash early rather than run with such a nasty bug going without being noticed. You're best off usingfgets()and thensscanf()or some other mechanism to parse the input so you can guarantee extra input is discarded.
I have read thistutorialand I wonder why memory is allocated forroot: ``` struct node { int x; struct node *next; }; struct node *root; root = malloc( sizeof(struct node) ); ``` I would say thatstruct node *root;guarantees that memory is loaded in the stack no? There is no unknown size here. Moreover, we use this node in the same frame.
I would say that struct node *root; guarantees that memory is loaded in the stack no? There is no unknown size here. Moreover, we use this node in the same frame. Not quite.struct node *root;guarantees that there is memory to hold apointerto astruct node, but not memory to hold the node itself.malloc()is allocating enough space for the node, and the address of that node is placed intoroot.
This question already has answers here:How to read program arguments [closed](3 answers)Closed7 years ago. I'm not sure exactly if the title made it clear, but I want to save the text typed in the same line while executing a program in C. For example, if I type: ./myprogram samplestring I want to save samplestring as a variable in the C program. Not sure if this is possible or not, and sorry if I'm not being clear, I'm a bit confused.
Fromhere: ``` #include <stdio.h> int main (int argc, char *argv[]) { int count; printf ("This program was called with \"%s\".\n",argv[0]); if (argc > 1) { for (count = 1; count < argc; count++) { printf("argv[%d] = %s\n", count, argv[count]); } } else { printf("The command had no other arguments.\n"); } return 0; } ```
Consider the following code: ``` int f(int a, int b, int *c) { *c = a + b; return *c > 0; } void check(int a, int b) { int c; if(f(a, b, &c) && c < 10) { puts("sum is in range [1, 9]"); } } ``` If the second part of&&is ever evaluated, iscguaranteed to hold the value assigned to it by function callf(a, b, &c)? Does this behavior changes from C to C++?
It is safe if a sequence point occurs that controls the order of evaluation. ``` // bad: evaluation order of f() and (c < 10) is not specified by C if(f(a, b, &c) & c < 10) { // OK, left half of && must occur first. if(f(a, b, &c) && c < 10) { ``` With simple&&expressions, there is no C,C++ difference. With C/C++ the left side is evaluated and the right is evaluated if the left is not false. Behavior on this point is more complex when in C++, the&&operator can be overloaded and then both sides of&&are always evaluated.
How to execute a shell script using CMake? The command that should be run ismy_scriptthat should be executed after build. TheCMakeLists.txt ``` cmake_minimum_required(VERSION 3.0) project(abc) include_directories("/usr/lib/avr/include") set(CMAKE_CURRENT_SOURCE_DIR /home/user/Desktop) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -mmcu=atmega8") set(SOURCE_FILES main.c) add_executable(abc ${SOURCE_FILES}) #not working -----> add_custom_command(TARGET abc POST_BUILD COMMAND ${CMAKE_COMMAND} -E my_script ) ``` DISCLAIMER Yes, there are similar questions in SOhere,here,here, etc; however, they don't give me a clear vision how this can be achieved.
You are invoking CMake with it'scommand-line tool modewhich doesn't execute generic scripts or commands. Instead do e.g. ``` add_custom_command(TARGET abc POST_BUILD COMMAND /bin/sh /path/to/my_script ) ```
Is it1&0are prime numbers ? because when i Input1&0it says that it is a PRIME ``` #include <stdio.h> int main(){ int num, i,y = 0; printf("Enter a Number: "); scanf("%d",&num); for(i = 2; i <= num /2; ++i){ if(num % i == 0){ y=1; } } printf("the number %d is a ",num); if (y == 0){ printf("(PRIME)"); } if(num % 2 == 0){ printf("(EVEN)"); }else printf("(ODD)"); printf(" Number."); } ``` can anybody help me with my code
No, neither 0 nor 1 are considered to be prime numbers, that is, the lowest prime number is 2. You need to change the code into, for instance: ``` if (y == 0 && n >= 2) ``` this covers both 0 and 1 along with negative integers (thanks to @MikeCAT)
``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int args, char *argv[]) { int i = 0; for (i = 0; i < args; i++) printf("\n%s", argv[i]); return 0; } ``` As of now this program prints out whatever is written on the command line. How would I make it do this in reverse? For example, if I input "dog" it should say "god".
Try the following code: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { int i = 0; for (i = 1; i < argc; i++) { char *tmp = argv[i]; int len = strlen(argv[i]); for(int j = len-1; j > -1; --j) printf("%c",tmp[j]); printf("\n"); } return 0; } ```
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.Closed7 years ago.Improve this question I'm curious to know what happens when heap memory is full and we callnewoperator inc++ormallocinc? Is there any way to clear the whole heap memory?
From"New and delete (C++)" on Wikipedia: If not enough memory is available in the free store for an object of typeT, thenewrequest indicates failure by throwing an exception of typestd::bad_alloc.This removes the need to explicitly check the result of an allocation.
what is the right way to free an allocated memory after executing function in C (via malloc)? I need to alloc memory, use it somehow and return it back, than I have to free it. ``` char* someFunction(char* a, char* b) { char* result = (char*)malloc(la + 2 * sizeof(char)); ... return result; } ```
Usefree. In your case, it will be: ``` char* result = malloc(la + 2 * sizeof(char)); ... free (result); ``` Also, if you're returning allocated memory, likestrdupdoes, the caller of your function has to free the memory. Like: ``` result = somefunction (); ... free (result); ``` If you're thinking of freeing it after returning it, that is not possible. Once youreturnsomething from the function, it automatically gets terminated.
When creating an OpenGL context in C, it seems that I must declare a typedef forGLXContextsuch as the one below: ``` typedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, Bool, const int*); ``` What exactly does this typedef do and why is it necessary?
You don't typedefGLXContextyou typedef a pointer to a function that returns a GLXContext and takes the parameters(Display*, GLXFBConfig, GLXContext, Bool, const int*). This typedef then can be used to actually define a pointer variable to such a function, which subsequently can be used to store the function pointer to said function queried using glXGetProcAddress. This function in turn is required for creating OpenGL contexts with a specific version.
I don't understand why am I getting runtime error when I uses[j]!='\0'but when I use*temp!='\0'it works perfectly fine. Can anyone explain? ``` void reverseWords(char *s) { char *word_begin = s; char *temp = s; /* temp is for word boundry */ int i=0,j=0; while( s[j]!='\0' ) { j++; if (s[j] == '\0') { reverse(s, i, j-1); } else if(s[j] == ' ') { reverse(s, i, j-1); i = j+1; } } } ```
The error is not in that function. If you check yourreversefunction, you never incrementior decrementjso it will run forever. A debugger is a helpful tool and would have shown this immediately.
I was bored, so I started to study something new, in this case, C. I was trying to do a basic script in c but I'm having this error, and i don't know what is wrong. ``` //Tablas #include <stdio.h> int main() { double i, j, p; int x, y; printf ("Tablas del: "); scanf ("%i", &x); printf ("Hasta el: "); scanf ("%i", &y); FILE *f; f = fopen("Tablas.txt", "w"); if (f == NULL) { printf("No se ha podido abrir/crear/reemplazar el archivo\n\a"); exit(1); } printf ("Espere mientras se calcula los resulatdos.\n"); system ("del tablas.txt"); for (i = x ; i <= y ; i++) { for (j = x ; j <= 10 ; j++) { fprinf(f, "%f x %f = %f\n", i, j, i*j); } } printf ("\nFin\n\a"); system ("pause"); return 0; } ```
You need#include <stdlib.h>forexitto work.
``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int args, char *argv[]) { int i = 0; for (i = 0; i < args; i++) printf("\n%s", argv[i]); return 0; } ``` As of now this program prints out whatever is written on the command line. How would I make it do this in reverse? For example, if I input "dog" it should say "god".
Try the following code: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { int i = 0; for (i = 1; i < argc; i++) { char *tmp = argv[i]; int len = strlen(argv[i]); for(int j = len-1; j > -1; --j) printf("%c",tmp[j]); printf("\n"); } return 0; } ```
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.Closed7 years ago.Improve this question I'm curious to know what happens when heap memory is full and we callnewoperator inc++ormallocinc? Is there any way to clear the whole heap memory?
From"New and delete (C++)" on Wikipedia: If not enough memory is available in the free store for an object of typeT, thenewrequest indicates failure by throwing an exception of typestd::bad_alloc.This removes the need to explicitly check the result of an allocation.
I was given a piece of code in C, and the question asked about it is whats wrong with it? I would be fine answering, but the asterisk in front of the malloc casting is confusing the heck out of me! ``` char f() { return *(char*)malloc(10); } ```
The function returns an indeterminate value and has a memory leak because the dynamically allocated memory is not freed.
I am trying in C to get the name of the variable used when the call to the function was made, as below: ``` func(varA, varB) ``` I would like to know the names of the arguments(varA, varB) I am printing the contents of several matrices, and I was wonderign if there is any easy way to distinguish between them without having to actually send the name as a string. Thank you
This is not possible without changing the function definition. You can pass the names manually or use a macro: ``` #define func( a , b ) func2( a , b , #a , #b ) func2( type a , type b , const char* namea , const char* nameb ){ ... ``` When preprocessing the code, operator # will transform the variable into a string.
int arr[100],temp1[n1],temp2[n2]; temp1 = arr[l];temp2 = arr[j]; i am supposed to assign some part of an array of length 100 to two arrays using pointers without using any loops ex:- l=10,j=43,n1=12,n2=13 now 12 elements from array have to be given to temp1 starting from 10th element and 13 elements have to be given to temp2 starting from 43 But using the above gives an error and assume that l,j,n1,n2 are given correctly before the declaration of the arrays . So suggest me a code to do this without loops and using pointers .
You cannotassignarrays in C, let alone assigning ranges from them. Instead, you copy memory of these arrays to new locations: This is done usingmemcpyfunction. Use&array[firstIndex]orarray+firstIndexto compute the initial address of the block to be copied and the initial address in the destination array. Usen*sizeof(array[0])to determine the number of bytes to be copied.
I have been writing programs in C/C++ that make use of the Linux API and make system calls like fork(),read(),write() etc. Now, I am beginning to wonder if these library functions are actually system calls, or are they some kind of wrapper functions. What really happens when a program makes a call to write() ? How does this function interact with the kernel ? If this is a wrapper then why do we need it ?
All such functions are real userspace functions inlibc.sothat your binary is linked against. But most of them are just tiny wrappers for syscalls which are the interface between the userspace and the kernel (see alsosyscall(2)). Note that functions that are purely userspace (likefmod(3)) or do some things in userspace in addition to calling the kernel (likeexecl(3)) have their manpages in the section 3 while functions that just call the kernel (likeread(2)) have them in the section 2.
``` #include<> int calc(int,int,char); void main() { int a,b; char c; printf("enter 2 nos"); scanf("%d%d",&a,&b); printf("enter op"); scanf("%s",&c); printf("the ans is %d\n",calc(a,b,c)); } int calc(int a,int b,char c) { int ans; switch(c) { case'+':ans=a+b;break; case'-':ans=a-b;break; } return ans; } ``` why does this program give the output as b...it works when i give a, b and c as global variables...what change should i do if i want them as local variables...using functions
scanf("%s",&c);causesundefined behavior. You are storing at least two characters['+', '\0']and you have only allocated space for one. You might considerscanf(" %c", &c);. Note that I intentionally added a space in the format string to eat any whitespace that the user might include.
int arr[100],temp1[n1],temp2[n2]; temp1 = arr[l];temp2 = arr[j]; i am supposed to assign some part of an array of length 100 to two arrays using pointers without using any loops ex:- l=10,j=43,n1=12,n2=13 now 12 elements from array have to be given to temp1 starting from 10th element and 13 elements have to be given to temp2 starting from 43 But using the above gives an error and assume that l,j,n1,n2 are given correctly before the declaration of the arrays . So suggest me a code to do this without loops and using pointers .
You cannotassignarrays in C, let alone assigning ranges from them. Instead, you copy memory of these arrays to new locations: This is done usingmemcpyfunction. Use&array[firstIndex]orarray+firstIndexto compute the initial address of the block to be copied and the initial address in the destination array. Usen*sizeof(array[0])to determine the number of bytes to be copied.
I have been writing programs in C/C++ that make use of the Linux API and make system calls like fork(),read(),write() etc. Now, I am beginning to wonder if these library functions are actually system calls, or are they some kind of wrapper functions. What really happens when a program makes a call to write() ? How does this function interact with the kernel ? If this is a wrapper then why do we need it ?
All such functions are real userspace functions inlibc.sothat your binary is linked against. But most of them are just tiny wrappers for syscalls which are the interface between the userspace and the kernel (see alsosyscall(2)). Note that functions that are purely userspace (likefmod(3)) or do some things in userspace in addition to calling the kernel (likeexecl(3)) have their manpages in the section 3 while functions that just call the kernel (likeread(2)) have them in the section 2.
``` #include<> int calc(int,int,char); void main() { int a,b; char c; printf("enter 2 nos"); scanf("%d%d",&a,&b); printf("enter op"); scanf("%s",&c); printf("the ans is %d\n",calc(a,b,c)); } int calc(int a,int b,char c) { int ans; switch(c) { case'+':ans=a+b;break; case'-':ans=a-b;break; } return ans; } ``` why does this program give the output as b...it works when i give a, b and c as global variables...what change should i do if i want them as local variables...using functions
scanf("%s",&c);causesundefined behavior. You are storing at least two characters['+', '\0']and you have only allocated space for one. You might considerscanf(" %c", &c);. Note that I intentionally added a space in the format string to eat any whitespace that the user might include.
I am trying to come up with a regex expression that can ignore any character in a line (after I read my relevant input). In a way, its treating the characters after a certain point in the txt file as a comment, but the comment is 'anything' but the relevant information I need. Here's what I have and its worked, but am wondering if there's a more elegant way to handle this: fscanf(input_file, "%*[a-zA-Z .^$*+?()[{\'\" \t]", temp_char) temp_charis a char* buffer. Thanks
If you want to consume every character different from\nand the final\n, use these statements: ``` fscanf(input_file, "%*[^\n]"); fscanf(input_file, "%*c"); ``` The first ignores all characters different from\n, but fails if there are none. The second consumes the\ncharacter.
I have a bidimentional array, And I wanna sum the values of the second value of row. Example, my array is ``` 1 1 2 2 3 3 4 4 5 5 ``` I want this output, the value I want to sum to the second value of row is 5 ``` 1 6 2 7 3 8 4 9 5 10 ``` I try this but sum the two values: ``` for(i=0; i<5; i++) { for(j=0; j<2; j++) { bolax[i][j]=bolax[i][j]+suma; } } ```
This addssumato the second value of each row: ``` for(i=0; i<5; i++) { bolax[i][1] += suma; } ``` Since the array index starts with 0, the second value is index 1.