question
stringlengths
25
894
answer
stringlengths
4
863
I'm trying to do some code stuff withinstrchrbut unfortuantly my use ofstrchrwas leading to execution bugs, it appears thatstrchrin some cases returning wrong value, here is the code: ``` int main(){ char* s="1/2/3/4/8/9/7"; char r[100]; char chunk2[100]; int i,jpos; for(i=0;i<5;i++){ strcpy...
s is a string literal, strrev() tries to change it, you cannot do that on static data. Use an array of characters ``` char s[]="1/2/3/4/8/9/7"; ```
I don't know what's the problem with this piece of code, I'm just getting a random result here: ``` #include <stdio.h> #include <conio.h> int main() { char arr[3][2] = {{'z','a'},{'e','r'},{'x','v'}}; int i; scanf("%d",&i); printf("%c",*(arr+i)); getch(); } ``` Thanks
First of all it is not clear what you are trying to do. I can only suggest to change statement ``` printf("%c",*(arr+i)); ``` the following way ``` printf("%c",**(arr+i)); ``` In this case if i will be in the range 0 - 2 then this statement will output the first character of the corresponding row. For example for ...
In the following example, can I define the size of a C element in bits? ``` #include <stdio.h> typedef enum { false = 0, true = ~0 } bool; int main(void) { bool x; printf("%d", sizeof x); return 0; } ```
In general, no. The minimum addressable unit is a byte, not a bit. You can do funny things withbitfields, such as: ``` struct { unsigned a : 31; unsigned b : 1; }; ``` That struct willlikely haveasizeof == 4,awill use 31 bits of space, andbwill use 1 bit of space.
I want to check if a library is present either in my app or the System. In java I usually do System.loadlibrary, but does anyone know a similar corresponding call in C ?
It isdlopento open a library, anddlsymto get pointer to function from loaded library. Beware, some details may vary in thisglibcdocumentation and actual android implementation. See ChrisStratton comment.
I'm trying to write a GTK+ application in C that uses gstreamer. GTK+ needsgtk_main()to execute. gstreamer needsg_main_loop_run()to execute. Both of them stall the execution flow. What can I do thatgtk_main()will also hold theGMainLoopthat I created for gstreamer? Thanks
Do not create aGMainLoop,gtk_main()internally creates one already which should suffice for anyglibbased library that uses events/signals. Seethis question which quotes thegtk_main()source
I looked atthis example from the Portaudio pageand wondered why the author uses ``` data.rBufToRTData = PaUtil_AllocateMemory(sizeof(OceanWave*) * 256); ``` instead of ``` data.rBufToRTData = malloc(sizeof(OceanWave*) * 256); ``` I could not find an answer to this on the Portaudio sites.
You should not usePaUtil_AllocateMemory(). It isn't part of the PortAudio public API. I have filed abug against the example. Thanks for raising the issue. That said, the example appears to be intended to demonstrate the use of some low-level internal data structures in PortAudio. In particular the PortAudio ring buff...
I have a problem. Suppose I have ``` char a[50]={" 99 98 100 97 101 "}; ``` and I want an another array of string that gives me values like this: ``` char b[50]={"bcdae"}; ``` then what to do? (ASCII value of a = 97 and so on)
``` #include <stdio.h> int main() { char a[50]={" 99 98 100 97 101 "}; char b[50]={0}; char *p = b; // p now points to b int i, num, pos = 0; // %d returns each number // %n returns the number of bytes consumed up to that point while(sscanf(a + pos, "%d%n", &num, &i)==1) { *...
Is it possible to to make server/client code in C/C++/Java, that can be platform independent? It should not require any additional package (like No JVM requirement) installation on system just the executable file to run (if possible on Windows/Linux/Mac). If not could you tell me any other way (maybe language) to ac...
just the executable file to run (if possible on Windows/Linux/Mac). This can be done with Qt C++ by writing portable code and using static linking to bind the DLL's. A downside to this is that you will end up with a much larger executable file. Java uses the JVM which rules it out like you stated. It should be noted...
Is it possible to to make server/client code in C/C++/Java, that can be platform independent? It should not require any additional package (like No JVM requirement) installation on system just the executable file to run (if possible on Windows/Linux/Mac). If not could you tell me any other way (maybe language) to ac...
just the executable file to run (if possible on Windows/Linux/Mac). This can be done with Qt C++ by writing portable code and using static linking to bind the DLL's. A downside to this is that you will end up with a much larger executable file. Java uses the JVM which rules it out like you stated. It should be noted...
Just trying to set up a sublime-build for my OpenGL coding on Windows 8.1. This is what I have: ``` { "cmd": [ "gcc -o \"$file\" \"$file_base_name\" -lGLU -lGL -lglut && ./\"$file_base_name\""], "working_dir": "${project_path:${folder}}", "selector": ["source.c"], "shell": true } ``` The error that I'm getting is...
Please replace ``` "cmd": [ "gcc -o \"$file\" \"$file_base_name\" -lGLU -lGL -lglut && ./\"$file_base_name\""], ``` with ``` "cmd": [ "gcc -o $file_base_name $file -lGLU -lGL -lglut && ./$file_base_name"], ``` and try again.
I know that the following is undefined because I am trying to read and write the value of variable in the same expression, which is ``` int a=5; a=a++; ``` but if it is so then why the following code snippet is not undefined ``` int a=5; a=a+1; ``` as here also I am trying to modify value ofaand write to it at the...
The reason why it is undefined is not that you read and write, it is that you write twice. a++means read a and increment it after reading, but we don't know if the ++ will happen before the assignment with=(in which case the=will overwrite with the old value of a) or after, in which case a will be incremented. Just ...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do...
There are two ways to do that: You can write your own code to write thePDFfile by learning pdf file structurePDF ReferenceYou can use an existing library likeHaru,JagPDF No. 1 is the hard way apparently but it's also fun in my opinion.
``` #include <stdio.h> #include <ctype.h> char* strcaps(char* s) { while (*s != '\0') { toupper(*s); s++; } return s; } ``` . ``` int main() { char makeCap[100]; printf("Type what you want to capitalize: "); fgets(makeCap, 100, ...
You are not printing anything! Print the return value oftoupper(). ``` printf("%c",toupper(*s)); ```
I am trying to solve an exercise of a course I'm taking and we're just in the beginning so usingrealloc,malloc, and other dynamic allocation function is not used here. First input will be euro - dollar rate, for ex.1.37. The rest of the input will be in dollars that will need to be converted to euros and in the end a...
You don't need to keep all of them. Just keep two sum values which are updated with every iteration...
I have a C file named first.c in which I define an array and call a function which is defined in a C file named second.c. This is how first.c looks: ``` int main(void) { int array[100]; myFunc(*array); } ``` second.c on the other hand looks like this: ``` void myFunc(int array) { ... } ``` But anytime ...
Your issue may lie in that the received value is not a pointer- so change voidmyFunc(int array)tovoid myFunc(int* array).
So I have an assignment that compares algorithms for allocating resources. I've implemented the algorithms and they work fine. My problem is simulating work being done on those resources. Originally, I figured just sleep for a second and that will do fine. However, that doesn't actually waste CPU time. All of the res...
The functionpthread_getcpuclockid(3)is mandated by POSIX. It's (Linux) manual page contains a short example that gives the CPU time used up by a thread. Run in a loop until you've wasted enough time, looping around doing some thumb twiddling in between checks.
I'm trying to generate a simple random number in C with the raspberry pi. The code compiles fine but when running it the number is not random, its 384 each time. Where am I going wrong? ``` #include <stdio.h> #include <stdlib.h> int main(void) { printf ("Random number generator\n") ; int x = (rand() % 100...
You need to seed the random number generator with some naturally random value like the current time. Something like: ``` srand (time(NULL)); ``` Update: note that you will need to add an include for the time library if you use the example above: ``` include <time.h> ```
I am trying to solve an exercise of a course I'm taking and we're just in the beginning so usingrealloc,malloc, and other dynamic allocation function is not used here. First input will be euro - dollar rate, for ex.1.37. The rest of the input will be in dollars that will need to be converted to euros and in the end a...
You don't need to keep all of them. Just keep two sum values which are updated with every iteration...
I have a C file named first.c in which I define an array and call a function which is defined in a C file named second.c. This is how first.c looks: ``` int main(void) { int array[100]; myFunc(*array); } ``` second.c on the other hand looks like this: ``` void myFunc(int array) { ... } ``` But anytime ...
Your issue may lie in that the received value is not a pointer- so change voidmyFunc(int array)tovoid myFunc(int* array).
So I have an assignment that compares algorithms for allocating resources. I've implemented the algorithms and they work fine. My problem is simulating work being done on those resources. Originally, I figured just sleep for a second and that will do fine. However, that doesn't actually waste CPU time. All of the res...
The functionpthread_getcpuclockid(3)is mandated by POSIX. It's (Linux) manual page contains a short example that gives the CPU time used up by a thread. Run in a loop until you've wasted enough time, looping around doing some thumb twiddling in between checks.
I'm trying to generate a simple random number in C with the raspberry pi. The code compiles fine but when running it the number is not random, its 384 each time. Where am I going wrong? ``` #include <stdio.h> #include <stdlib.h> int main(void) { printf ("Random number generator\n") ; int x = (rand() % 100...
You need to seed the random number generator with some naturally random value like the current time. Something like: ``` srand (time(NULL)); ``` Update: note that you will need to add an include for the time library if you use the example above: ``` include <time.h> ```
I know there is the strcmp but it just let me compare two strings, And I need to compare a lot of them This one doesn't work: ``` if(strcmp (resposta, "S" || "s" || "N" || "n")== 0) printf("Resposta = S"); else printf("Resposta != S"); printf("\nfim"); ```
Your method isn't working as you expected because the expression"S" || "s" || "N" || "n"is the same as"S"because of short circuit. You have to compare it with the candidate strings one by one: ``` if (strcmp(resposta, "S") == 0 || strcmp(resposta, "s") == 0 || strcmp(resposta, "N") == 0 || strcmp(respost...
I could use following code to get the /proc entry, but how to get the /proc entry directly? Any function in the kernel to do this directly(without creating one dummy sub-entry)? ``` new_proc = proc_create("dummy", 0644, 0, &fileops_struct); root = new_proc->parent; ```
I haven't found a function, but you might accessproc_rootdirectly. It is located infs/proc/root.cand should be accessible from outside.
I'm making a stack based virtual machine in RPython using the PyPy toolchain to convert the RPython to C. So far I have 4 instructions. EOP - End of ProgramEOI - End of InstructionPUSH - Push item onto the stackPRINT - Print the top of the stack My question is, how do you push a String to the top of the stack. Is it...
That depends. Do you want to push thestring, or apointer to a string? If it's the former, you have a problem, because the string will have variable length, unlike a pointer or a number. If it's the latter, you have to consider memory management aside from your stack.
Using C, I want to convert a UNIX Timestamp number to several usual date data. How do I convert a UNIX timestamp like 12997424 to different numbers representing seconds, minutes, hours and days while using C?
Usegmtimeorlocaltimefrom standard library. Prototypes are defined in time.h. ADDED & EDITED: So for example, the following code prints current timestamp, hour and minute: ``` #include <stdio.h> #include <time.h> void main() { time_t t; struct tm ttm; t = time(NULL); printf("Current timestam...
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question The first parameter of execl is the path of the executable file, my question is that what if there is a spa...
what if there is a space in the path? It does not matter, as theexec*()functions do not involve a shell or any kind of command interpreter which might choke on the space, or any other special character. My program fails when space exists. Doesexec()return? Which value do you find inerrnoor what doesperror()print? ...
Does the main thread for the process start executing right after creation, or does it begin after the completion of the call back routine?
This doesn't appear to be documented, which implies that there is no guarantee that the thread will not start executing before the callback routine returns. However, the documentation for theCreateProcessNotifyExroutine says: For a new process, the CreateProcessNotifyEx routine is called after the initial thread is ...
The following html link contains all the relevant bash command line records of the installation process. Thank you for help! That was a bad question I didn't use XCode through I know Xcode will make it easier! I use an Air, memory of 4GB currently. If this won't work easily I probably will quit learning C or run and...
You command-line output indicates rather clearly that you aren't tellinggccwhat to compile, so it's throwing its hands up in exasperation: ``` $ gcc i686-apple-darwin10-gcc-4.2.1: no input files ``` You'll need to specify the file you're compiling. Better yet, use an IDE, like Xcode.
I am a beginner with the programming language C. I am working from example code online and am trying to analyze the following, ``` int x = 0, y = 16; *x_ptr = &x ``` It's the second line that I want to make sure I'm understanding syntactically. I have only just encountered the concept of pointers and am trying to cr...
The code you posted doesn't include a declaration ofx_ptr, but for the code to be valid, the type ofx_ptrmust beint**: a pointer to a pointer to an integer. The expression*x_ptrmeans the thing thatx_ptrpoints to. Sincex_ptris a pointer to a pointer to an integer,*x_ptris a pointer to an integer. Sincexis an integer...
I'm writing a Gtk+3 application in C. The user interface is built with glade. I created an independentGtkBoxthat should be used in several places in my application. When I try to use thatGtkBoxmore then once I get the following error: ``` (tuxmusicstudio:27491): Gtk-WARNING **: Attempting to add a widget with type ...
You can't clone a widget as such. Either put your reusable widget into its own Glade file and load it more than once using GtkBuilder; or create a class for the widget you want and instantiate it more than once.
``` #include<stdio.h> int main() { int i,j; int array[2][2]; for(i=0;i<2;i++){ for (j=0;j<2;j++){ scanf("%d ",&array[i][j]); } } for(i=0;i<2;i++){ for (j=0;j<2;j++){ printf("%d ",array[i][j]); } } return(0); } ``` I want to get array...
A space in a format specifier can skip any number of white-spaces.Change ``` scanf("%d ",&array[i][j]); ``` to ``` scanf("%d",&array[i][j]); ```
The chip is an Energy Micro EFM32380f1024 ARM microcontroller and I am using IAR ARM Embedded Workbench. I am aware of the __ramfunc directive however accomplishing initialising and accessing USB completely in RAM (as the flash is going to be completely erased) requires all USB libraries that will be used to be placed...
as the flash is going to be completely erased Not a good idea. In case the update process fails to write the new program completely and the power is lost, your device will bebricked. Using a bootloader is strongly recommended when you want the flash to be updatable by a user.
Why for functions suchprintfstandard output is specified as the destination where data goes? I mean that there are many IO functions in C standard library which write data to standard output and usually there are corresponding functions likefprintfwhere you can specify where your data goes. Why are there placed these ...
printfandscanfexist because of the widespread use of stdout and stdin (like in console programs). So yes, it is more or less just for convenience. Generally speaking you would usefprintfandfscanffor user defined streams.
This question already has answers here:How do I print the percent sign(%) in C? [duplicate](4 answers)Closed9 years ago. ``` int main(void) { int a=12,b=3; printf("\n a+b = %i\n",a+b); printf("\n a-b = %i\n",a-b); printf("\n a*b = %i\n",a*b); printf("\n a/b = %i\n",a/b); printf("\n a%b = %i\n"...
It isprintfgiving the warning, scape the modulus character with another modulus: ``` printf("\n a%%b = %i\n",a%b); ``` As you may see in the manual:printf(3)there's nobflag character, so whenprintffind your%bin your string it doesn't know what to do. Since you don't want any formatting in that case, just include the...
I know that the _T(x) macro converts a string literal to a unicode/multibyte string based on a define, however I find it very annoying that I must make a underscore and the parenthesis, it really confuses me, I'm not quiet fluent with macros so I don't know, is there a way to detect all string literals and convert th...
No, there isn't a way to avoid the macro completely if you want your code to be portable on Windows. You can of course define your own macro like#define t(x) whatever_T_doesif you want to save yourself some keystrokes, but this will probably anger future maintainers of your code.
Just confused, why is not mL = 1?
Visual studio treatsint mL = 400/400as two step process. First step would be allocating memory in stack. So, you see a garbage value. Press F10/F11 (step once more) you should see 1. -858993460 translates to 0xCCCCCCCC which is a bit pattern used by Microsoft compilers to detect buffer overruns and to initialize an ...
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question My Professor uses the termkey comparisonwhen talking aboutquicksort, but didn't explain what exactly the ke...
The key is whatever you're sorting on. If you're just doing a typical sort of an array of numbers, then the key is a number. If you're sorting, for example, objects describing people, and you're sorting this by their surname, then the key would be the surname.
``` main() { FILE *fin; char line[50]; char exp[SIZE]; fin=fopen("prefix.txt","r"); if(fin==NULL) { printf("\nFile Cannot be Opened\n"); } else { printf("\nfile opened\n"); while(fgets(line, sizeof(line), fin)!=NULL) { sscanf(line,...
Yeah, becausesscanf()(along with all thescanf()functions) uses the%sspecifier to read a stringup to the first whitespace character.So you explicitly truncate your line with that one call. It seems to me that you want to process the entire line, so that sscanf is just useless -- remove it.
I came across this snippet of code which appeared in the guts of setting up a socket: ``` #define PORT xxxx struct sockaddr_in self; self.sin_family = PF_INET; self.sin_port = htons(PORT); ``` I understand that we need to convert byte order of the data that we are transmitting over a network toNetwork Byte Orderbut...
I think let's assume you are using TCP. The port number is going to be in the packet header. That is going to be transmitted. So it will be in Network Byte Order.
I want to access data from a struct used in file1.c and access the data in file2.c I have declared ``` in file1.c struct value { unsigned char time[6]; unsigned char date[6]; unsigned char number[6]; } entry; ``` where the struct gets filled by values and then want to use the s...
You can use theexternkeyword and declare thestructvariable in the new file also. ``` extern struct value entry; ```
I've created a simple window to receive messages: ``` CreateWindow(L"MyClass", 0, 0, 0, 0, 0, 0, HWND_MESSAGE, 0, 0, 0); ``` I'm intrested inWM_DISPLAYCHANGEto detect when monitors are plugged in/removed, but I never receive the message. My window receives other messages, but neverWM_DISPLAYCHANGE. Why?
This might have something to do with it: Message-only windows Amessage-onlywindow enables you to send and receive messages. It is not visible, has no z-order, cannot be enumerated,and does not receive broadcast messages. The window simply dispatches messages.
I'm writing a kernel driver, which should read (and in some cases, also write) some memory addresses in kernel session space (win32k.sys). I've read in another topic that for example in Windbg I should change the context to a random user process to read the memory of kernel session space (with .process /p). How can I ...
Session space are not mapped in system address space (that drivers share, if not attached to any process). Those why you getting BSOD while accessing win32k. You need to be attached to EPROCESS via KeStackAttachProcess to perform this operation. You can get session id with ZwQueryInformationProcess(ProcessSessionInfo...
I know it's a simple question but not getting why it's giving error. Please help me in getting this very simple prog work. It's giving error and seg fault as shown below in comments. ``` #include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct msgclient { int msglen; int msgtype; char cp[10...
Your problem is ``` M1* m; ``` m is not initialised and will point to a random memory address. You need to do ``` M1* m = malloc(sizeof(M1)); ... strncpy(m->cp, "hi how are you", 15); free(m); ```
This question already has answers here:Type of integer literals not int by default?(3 answers)Closed5 years ago. If there is some positive integer literal in my code, say 50, does the compiler consider it as type unsigned int or int?
A decimal integer literal is of the first type where it can be represented inint,longorlong long. 50is of typeint. unsigned literals can be specified using theuorUsuffix. A decimal integer literal suffixed withuorUis of the first type where it can be represented inunsigned int,unsigned longorunsigned long long. 50U...
I want to convert some bytes to an int. This is my code so far: ``` unsigned char *bytePtr = (unsigned char *)[aNSDataFrame]; ``` I want to take 4 bytes from this unsigned char:myFrame[10],myFrame[11],myFrame[12]andmyFrame[13]and convert them to an integer.
``` int val = *(const int*)&myFrame[10]; ```
How can I get rid of the potential overflow check if I use signed integers? ``` unsigned long ticks1 = GetTickCount(); if (SemaphoreTake(_sema, to)) // taken { unsigned long ticks2 = GetTickCount(); // take care of potential overflow unsigned long elapsed = ticks2 > ticks1 ? (ticks2 - ticks1) : (ticks1 - ...
No need for the overflow check. Shouldticks2 < ticks1, unsigned math subtraction is well defined in C with the result mathematically the same aselapsed = (ULONG_MAX + 1) + ticks2 - ticks1. Certainly donotwantticks1 - ticks2. ``` // unsigned long elapsed = ticks2 > ticks1 ? (ticks2 - ticks1):(ticks1 - ticks2); unsig...
This is my code for the searching part and it's not working. Can you give me a little help on this? I'm newbie on programming and I really just suck at pointers. Thanks. ``` typedef struct Dictionary_Entry{ int index; char character[100]; struct Dictionary_Entry *link; }Dictionary_Entry; typedef struct D...
Thebreakkeyword leaves the loop, so yourreturn runner->indexline doesn't get executed. Swap the two lines (or removebreak, sincereturnwillalsoleave the loop, in its way), and you should be fine.
I came across this C program ina blog post: ``` main() { int n; n = 151; f(n); } f(x) int x; { printf("%d.\n", x); } ``` The post doesn't explain it. Can anybody explain what this weird function definition means?
This is the K&R style of C code, it's still valid C syntax, but I suggest you not using it in new-written code. ``` f(x) int x; ``` is equivalent to ANSI C: ``` void f(int x) ``` K&R Cis the C language described in the first edition of the bookC programming languageby Brian Kernighan and Dennis Ritchie, and name...
I always feel lots of problem while taking char or string inputs in C linux. And see this prog. It's not taking input from the user. Please help. ``` #include<stdio.h> #include<string.h> #include<stdlib.h> int main() { char *buf; int msglen; printf("\nEnter message length\t"); scanf("%d",&msglen); ...
fflush()is used to flush theoutput streamsand not clear the remaining characters fromstdin. usegets()orgetchar()first to remove theEOFfromstdin
Say I have this: ``` #define CAKE , something ``` and the result I want is", something". Can it be done? The following doesn't work in gcc: ``` #define MAKE_STRING(x) #x #define STRING(x) MAKE_STRING(x) STRING(CAKE) ``` The compiler thinks I'm passing two arguments into MAKE_STRING() and balks.
If your preprocessor supports variadic macros,__VA_ARGS__will do the trick: ``` #define CAKE , something #define MAKE_STRING(...) #__VA_ARGS__ #define STRING(x) MAKE_STRING(x) #include <stdio.h> int main() { printf("%s\n", STRING(CAKE) ); } ```
I need help with a screening question (in C) asked by a company. The question is to find out issues with the below code. ``` short test() { short a,b,c; b=10; c = a + b; return c; } ``` Also, what if the signature is changed to short test(short a) and a is removed from the stack? I cannot seem to find...
The value ofais indeterminate because it is uninitialized. Readingaresults in undefined behavior. Ifawere passed into the function and it was also uninitialized the same problem would occur, only sooner.
I know I am supposed to use mutexes but the way I currently use pthreads it would overly complicate the program... anyway I basically have a variable which I use to denote if a thread is currently performing work or not. in the main thread I run over it in a while loop the check what threads are no longer busy. Now o...
In general, NO. The following article explains why: http://www.domaigne.com/blog/computing/mutex-and-memory-visibility/ Here is a list of API functions that act as memory barriers: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_11
I have the following code ``` // global array a[100][10] char a[100][10]; main(){ printf("%s\n", a[0]); strcpy(a[0], "test") printf("%s\n", a[0]); if (some condition){ // attempt to re-initialize a[100][10] char a[100][10]; printf("%s\n", a[0]); } } ``` The outputs of the printf's a...
In the if you are not "reinitializing"a, you are shadowing the global variable and using uninitialized memory. The first time around you only get a newline printed because the globalahas static storage duration and is thus 0-initialized. The innerahas automatic storage and is not zero-initialized. Depending on wha...
In C, we can initialize astructon the stack in the following way. ``` struct Foo { int bar; int bar2; }; int main(){ struct Foo myFoo = { .bar = 1, .bar2 = 2 }; } ``` However, when, I try this kind of thing theheap, the compiler refused it. ``` struct Foo* myFooPtr = malloc(sizeof(...
Yes: ``` struct Foo *myFooPtr = malloc(sizeof(struct Foo)); *myFooPtr = (struct Foo) { .bar = 1, .bar2 = 2 }; ``` (although formally this an initialisation of an anonymous compound literal object followed by anassignmentto the heap object, rather than a direct initialisation).
I am using perl debugger in Eclipse (via EPIC plugin). Is there any feature to automate the steps until an event occurs. For example can I make it run until $args->{some_arg} is set? If not, what is the best known workaround? This feature or workaround may be similar to debugging some other C-like languages.
In the normal perl debugger, setting$DB::single = 1;will drop you to the debugger. So you could have the following: ``` $DB::single = 1 if $args->{some_arg}; ``` I have no idea if this works in Eclipse.
Say I have this: ``` #define CAKE , something ``` and the result I want is", something". Can it be done? The following doesn't work in gcc: ``` #define MAKE_STRING(x) #x #define STRING(x) MAKE_STRING(x) STRING(CAKE) ``` The compiler thinks I'm passing two arguments into MAKE_STRING() and balks.
If your preprocessor supports variadic macros,__VA_ARGS__will do the trick: ``` #define CAKE , something #define MAKE_STRING(...) #__VA_ARGS__ #define STRING(x) MAKE_STRING(x) #include <stdio.h> int main() { printf("%s\n", STRING(CAKE) ); } ```
I need help with a screening question (in C) asked by a company. The question is to find out issues with the below code. ``` short test() { short a,b,c; b=10; c = a + b; return c; } ``` Also, what if the signature is changed to short test(short a) and a is removed from the stack? I cannot seem to find...
The value ofais indeterminate because it is uninitialized. Readingaresults in undefined behavior. Ifawere passed into the function and it was also uninitialized the same problem would occur, only sooner.
I know I am supposed to use mutexes but the way I currently use pthreads it would overly complicate the program... anyway I basically have a variable which I use to denote if a thread is currently performing work or not. in the main thread I run over it in a while loop the check what threads are no longer busy. Now o...
In general, NO. The following article explains why: http://www.domaigne.com/blog/computing/mutex-and-memory-visibility/ Here is a list of API functions that act as memory barriers: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_11
I have the following code ``` // global array a[100][10] char a[100][10]; main(){ printf("%s\n", a[0]); strcpy(a[0], "test") printf("%s\n", a[0]); if (some condition){ // attempt to re-initialize a[100][10] char a[100][10]; printf("%s\n", a[0]); } } ``` The outputs of the printf's a...
In the if you are not "reinitializing"a, you are shadowing the global variable and using uninitialized memory. The first time around you only get a newline printed because the globalahas static storage duration and is thus 0-initialized. The innerahas automatic storage and is not zero-initialized. Depending on wha...
In C, we can initialize astructon the stack in the following way. ``` struct Foo { int bar; int bar2; }; int main(){ struct Foo myFoo = { .bar = 1, .bar2 = 2 }; } ``` However, when, I try this kind of thing theheap, the compiler refused it. ``` struct Foo* myFooPtr = malloc(sizeof(...
Yes: ``` struct Foo *myFooPtr = malloc(sizeof(struct Foo)); *myFooPtr = (struct Foo) { .bar = 1, .bar2 = 2 }; ``` (although formally this an initialisation of an anonymous compound literal object followed by anassignmentto the heap object, rather than a direct initialisation).
I am using perl debugger in Eclipse (via EPIC plugin). Is there any feature to automate the steps until an event occurs. For example can I make it run until $args->{some_arg} is set? If not, what is the best known workaround? This feature or workaround may be similar to debugging some other C-like languages.
In the normal perl debugger, setting$DB::single = 1;will drop you to the debugger. So you could have the following: ``` $DB::single = 1 if $args->{some_arg}; ``` I have no idea if this works in Eclipse.
I found the declaration of functionstrcpyin string.h ``` /* Copy SRC to DEST. */ extern char *strcpy (char *__restrict __dest, __const char *__restrict __src) __THROW __nonnull ((1, 2)); ``` but where can I find the definition and body for this function?
It's the declaration, not the definition. "How this works" resides in the library implementation. The implementation of, for example, GNU C Library can befound online. For this particular function,an SO question has been asked, too.
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 answer...
You can useOpenCVlibrary, which contains similarMat::reshape()routines to do transforms and permutations.
How can I usesched_setschedulerexplained in thistopic? It seems that I have to write a C code and run it on shell?
To change the policy of a process from the shell you need to usechrt. To choose real time priorities you must be root. Beware that this is dangerous, raising priorities higher than the kernel interrupts will definitely have strange side effects!
I've got incoming data in Big Endian format ``` uint8_t u8DataA[] = {0x40, 0xAD, 0x70, 0xB8}; ``` which needs to get unpacked tofloat. The result should be3768.36. No mater how I stuff bytes into float I don't get this result. How do I do this?
You got the first four bytes of a 64-bitdoublerepresentation, not the four bytes of a 32-byte representation. According to the IEEE 754 calculator, 64-bit representation of3768.36is ``` 0x40, 0xAD, 0x70, 0xB8, 0x51, 0xEB, 0x85, 0x1F ^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^ This is what you have This part is ...
A symbol happens to be defined in two third party libraries, namely, in my case, zlib somehow got its copyright string into both. I checked this copyright string, and it is a harmless global static string with the copyright notice. However, I can't link due to this. Is there an easy way to remove it in one of those...
A somewhat dirty but effective method is by modifying manually the symbol in one of the .lib files with a binaray editor (e.g.PsPad). Just change_deflate_copyrightinto e.g._deflate_copyrigXX. The characters must not beremovedbut they must bereplaced. Don't replace the characters at thestartof the symbol name (e.g. r...
I want to use C-functions in my python program and the obvious way is to implement the libraries with "ctypes". But there is a problem. In C I include different header files that the linker will link with the right libraries. But I only know the name of the header files, but for python I need to know the name of the ...
ctypesdynamically loads the shared object or the DLL, so you need some how the shared object name. You may have a look atctypes.util.find_library(name). For example: ``` >>> from ctypes.util import find_library >>> >>> find_library('pthread') 'libpthread.so.0' >>> >>> find_library('ssl') 'libssl.so.0.9.8' >>> >>> ...
I am binding to socket in a kernel module. I get the IP in string format from another socket. How should I pass this IP to htonl(). I tried typecasting it to (long int). But, obviously it won't work. How to achieve this?
``` unsigned int inet_addr(char *str) { int a, b, c, d; char arr[4]; sscanf(str, "%d.%d.%d.%d", &a, &b, &c, &d); arr[0] = a; arr[1] = b; arr[2] = c; arr[3] = d; return *(unsigned int *)arr; } //use it as follows: //inet_addr() returns address in Network Byte Order, so no need of htonl() thesockad...
I'm trying to make a snake in the command line when the snake itself is created with O's and the apples are dots "."'s. Now... I know hot to get arrow keys and I know the algorithm but the snake needs to move (using Sleep and animations) and also have getch() on all the time. How do I do that ? Isn't that multithreadi...
You can usekbhit(or_getchand_kbhit) to peek and see if there are some keys pressed. And only if there are some, get it withgetch. Also seethisquestion and answer for an example.
I want to use C-functions in my python program and the obvious way is to implement the libraries with "ctypes". But there is a problem. In C I include different header files that the linker will link with the right libraries. But I only know the name of the header files, but for python I need to know the name of the ...
ctypesdynamically loads the shared object or the DLL, so you need some how the shared object name. You may have a look atctypes.util.find_library(name). For example: ``` >>> from ctypes.util import find_library >>> >>> find_library('pthread') 'libpthread.so.0' >>> >>> find_library('ssl') 'libssl.so.0.9.8' >>> >>> ...
I am binding to socket in a kernel module. I get the IP in string format from another socket. How should I pass this IP to htonl(). I tried typecasting it to (long int). But, obviously it won't work. How to achieve this?
``` unsigned int inet_addr(char *str) { int a, b, c, d; char arr[4]; sscanf(str, "%d.%d.%d.%d", &a, &b, &c, &d); arr[0] = a; arr[1] = b; arr[2] = c; arr[3] = d; return *(unsigned int *)arr; } //use it as follows: //inet_addr() returns address in Network Byte Order, so no need of htonl() thesockad...
I'm trying to make a snake in the command line when the snake itself is created with O's and the apples are dots "."'s. Now... I know hot to get arrow keys and I know the algorithm but the snake needs to move (using Sleep and animations) and also have getch() on all the time. How do I do that ? Isn't that multithreadi...
You can usekbhit(or_getchand_kbhit) to peek and see if there are some keys pressed. And only if there are some, get it withgetch. Also seethisquestion and answer for an example.
I'm trying to make a snake in the command line when the snake itself is created with O's and the apples are dots "."'s. Now... I know hot to get arrow keys and I know the algorithm but the snake needs to move (using Sleep and animations) and also have getch() on all the time. How do I do that ? Isn't that multithreadi...
You can usekbhit(or_getchand_kbhit) to peek and see if there are some keys pressed. And only if there are some, get it withgetch. Also seethisquestion and answer for an example.
I am using aLinux operating systemand the library functions I am talking about C programming language.
Those functions are part of the system's C library, which on most GNU/Linux systems isGNU libc, also known as "glibc". Since glibc is open-source free software, you can download its source code and read whatever parts you're interested in. Thedownload pageis the place to start.
I'm getting this error when trying to compile this simple program. The psinfo struct is in procfs.h. It's erroring on the definition line. Why would it not know the size of psinfo? ``` #include <sys/procfs.h> int main(int argc, char *argv[]) { struct psinfo p; } $ /usr/sfw/bin/gcc little.c little.c: In fu...
Adding "#define _STRUCTURED_PROC 1" to the header fixed the problem. It needs to be defined before including sys/procfs.h. The problem is that procfs.h sources sys/old_procfs.h unless _STRUCTURED_PROC does not equal 0 (apparently the default). ``` #if !defined(_KERNEL) && _STRUCTURED_PROC == 0 #include <sys/old_proc...
How do I test to see if an identifier is a character ? I'm trying to test to see if an identifier namedcode == I, or ifcode == D, or ifcode == C. This is what I have done so far. ``` char code; double amount, service, balance; double amtCheck, amtDeposit, openBalance, closeBalance; int numCheck, numDeposit; inp = fo...
Use single quotes'C'for character literals.
I just want to assign the value ofpowto a variable, I've used this ``` #include<stdio.h> #include<math.h> int main( void ) { int x; int y; int z; x=10; y=2; z = pow(x,y); printf ("%d" , &z); return 0; } ``` but in output I get -1076813284 , I am sorry, but I just started learning C and in every tutorial everyone ...
``` printf ("%d" , &z); ``` prints the address ofz(*), not its value.printf("%d", z)prints the value. (*) Actually, the behavior is undefined and on a 64-bit CPU it will likely print half of the address.
I am using curses to create a menu in C. I have been using the following resources:ncurses man pagesand thetldp how-to. While the former provides a great reference for curses.h functions, and the latter has a nice introductory section on the menu library, I am unable to find a good reference for it. I have examined ...
Yes, the reference is: online here,located atdoc/html/man/menu.3x.htmlin the source download,man menushould work as well if you have ncurses man pages installed (sudo apt-get install ncurses-docon Debian/Ubuntu).
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.Closed9 years ago.Improve...
You wrote a dash–instead of a hyphen-. Spot the difference: ``` ... 3*2 – 5; ... 3*2 - 5; ```
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question ``` print 10**1000 % 7 ``` In C I get a syntax error because it exceeds the memory limit I guess. Can I so...
In addition to that not being valid syntax in C/C++, it's bad practice in python. If you do ``` pow(10,1000,7) ``` It will use modular exponentiation so it will be much faster than doing ``` 10 ** 1000 % 7 ```
This might sound too crazy but I just had a thought. In C why ``` char *pc = 'H'; // single character char *ps = "hello"; // a string ``` both are valid? I mean why achar*can hold/refer a character as well as a null terminated string? Why there are no guard clause or compiler error generated for*pcas thatchar...
Itcanhold acharbecause there is an implicit conversion fromchartochar *(viaint), and becausesizeof(char *) >= sizeof(char). Youshouldn'tdo this, though (technically it is undefined behavior because the literal numeric value of a character is not likely to be a valid pointer address to achartype). And in many/most com...
This question already has answers here:Can I assume (bool)true == (int)1 for any C++ compiler?(5 answers)Closed9 years ago. Consider the code ``` bool f() { return 42; } if (f() == 1) printf("hello"); ``` Does C (C99+ with stdbool.h) and C++ standards guarantee that "hello" will printed? Does ``` bool a = x; ...
Yes. You are missing a step though. "0" is false and every other int is true, but f() always returns true ("1"). It doesn't return 42, the casting occurs in "return 42;".
I know that the title is not clear at all , but i use this code to tell what i want to ask assume the following simple code : ``` void example(int *a) { for(i = 0 ; i < 20 ; i++) { printf(" %d number is %d \n " , i , a[i]); } } int main() { int a[20] ; // assume that the array is filled ...
The simple rule is thatarrays are not pointers. Array names are converted to pointer (in most cases) to its first element when they passed as arguments to a function.
I have an array of six random numbers from 1-49 so far but some repeat eg, 12 15 43 43 22 15 is there a way around this problem? so far I have... ``` int* get_numbers() { int Array[6], i; printf("\n\n Your numbers are : "); for (i = 0; i < 6; i++) { Array[i] = ((rand() ...
You could simply throw out duplicates. Another option would be to create an array of numbers 1-49,shuffle them, and take the first 6.
I want to redesign the UI for a pre-existing, working C project. It's not Visual Studio, it's plain .c and .h files. The changes I intend on making will require WPF (Windows Presentation Foundation). I'm wondering if this is possible, and if so, how difficult it would be. Any links to tutorials, etc. would be fantast...
Typically, the best approach for this type of work is to: Decouple the logic from the UI in the existing code base.Make a P/Invoke (C API) or C++/CLI wrapper for the logicUse C# to build the WPF front end for this.
I just want to assign the value ofpowto a variable, I've used this ``` #include<stdio.h> #include<math.h> int main( void ) { int x; int y; int z; x=10; y=2; z = pow(x,y); printf ("%d" , &z); return 0; } ``` but in output I get -1076813284 , I am sorry, but I just started learning C and in every tutorial everyone ...
``` printf ("%d" , &z); ``` prints the address ofz(*), not its value.printf("%d", z)prints the value. (*) Actually, the behavior is undefined and on a 64-bit CPU it will likely print half of the address.
I am using curses to create a menu in C. I have been using the following resources:ncurses man pagesand thetldp how-to. While the former provides a great reference for curses.h functions, and the latter has a nice introductory section on the menu library, I am unable to find a good reference for it. I have examined ...
Yes, the reference is: online here,located atdoc/html/man/menu.3x.htmlin the source download,man menushould work as well if you have ncurses man pages installed (sudo apt-get install ncurses-docon Debian/Ubuntu).
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.Closed9 years ago.Improve...
You wrote a dash–instead of a hyphen-. Spot the difference: ``` ... 3*2 – 5; ... 3*2 - 5; ```
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question ``` print 10**1000 % 7 ``` In C I get a syntax error because it exceeds the memory limit I guess. Can I so...
In addition to that not being valid syntax in C/C++, it's bad practice in python. If you do ``` pow(10,1000,7) ``` It will use modular exponentiation so it will be much faster than doing ``` 10 ** 1000 % 7 ```
This might sound too crazy but I just had a thought. In C why ``` char *pc = 'H'; // single character char *ps = "hello"; // a string ``` both are valid? I mean why achar*can hold/refer a character as well as a null terminated string? Why there are no guard clause or compiler error generated for*pcas thatchar...
Itcanhold acharbecause there is an implicit conversion fromchartochar *(viaint), and becausesizeof(char *) >= sizeof(char). Youshouldn'tdo this, though (technically it is undefined behavior because the literal numeric value of a character is not likely to be a valid pointer address to achartype). And in many/most com...
This question already has answers here:Can I assume (bool)true == (int)1 for any C++ compiler?(5 answers)Closed9 years ago. Consider the code ``` bool f() { return 42; } if (f() == 1) printf("hello"); ``` Does C (C99+ with stdbool.h) and C++ standards guarantee that "hello" will printed? Does ``` bool a = x; ...
Yes. You are missing a step though. "0" is false and every other int is true, but f() always returns true ("1"). It doesn't return 42, the casting occurs in "return 42;".
I know that the title is not clear at all , but i use this code to tell what i want to ask assume the following simple code : ``` void example(int *a) { for(i = 0 ; i < 20 ; i++) { printf(" %d number is %d \n " , i , a[i]); } } int main() { int a[20] ; // assume that the array is filled ...
The simple rule is thatarrays are not pointers. Array names are converted to pointer (in most cases) to its first element when they passed as arguments to a function.
I have an array of six random numbers from 1-49 so far but some repeat eg, 12 15 43 43 22 15 is there a way around this problem? so far I have... ``` int* get_numbers() { int Array[6], i; printf("\n\n Your numbers are : "); for (i = 0; i < 6; i++) { Array[i] = ((rand() ...
You could simply throw out duplicates. Another option would be to create an array of numbers 1-49,shuffle them, and take the first 6.
I want to redesign the UI for a pre-existing, working C project. It's not Visual Studio, it's plain .c and .h files. The changes I intend on making will require WPF (Windows Presentation Foundation). I'm wondering if this is possible, and if so, how difficult it would be. Any links to tutorials, etc. would be fantast...
Typically, the best approach for this type of work is to: Decouple the logic from the UI in the existing code base.Make a P/Invoke (C API) or C++/CLI wrapper for the logicUse C# to build the WPF front end for this.
I wonder if we use vfork , how we know child process or parent process , since the resources are shared . to be more specific , assume the following code : ``` int main() { int pid = vfork(); if(pid == 0) { // code for child } else { // code for parent } return 0; } `...
vfork()suspends the parent until the child either callsexec*()or_exit(). usingvfork()in this format as we usefork()results in program run in infinite loop. it doesn't end.read thisdiscussionto get better idea about usingvfork().
I am confused about the role of '\n' in fprintf. I understand that it copies characters into an array and the \n character signals when to stop reading the character in the current buffer. But then, when does it know to make the system call write. for example, fprintf(stdout,"hello") prints but I never gave the \n ch...
The system call is made when the channel is synced/flushed. This can be when the buffer is full (try writing a LOT without a\nand you'll see output at some point), when a\nis seen (IF you have line buffering configured for the channel, which is the default for tty devices), or when a call tofflush()is made. When the ...
I wish to read and write to a.csvfile using this format:~83474\t>wed 19 march 2014\n When reading, I need to ignore the~, the tab and the>. They are just there to remind my program of what the values that follow are used for. So far I figured out how to write to file using that format, however, I do not know how to r...
Read the whole line as a string using fgets and process it.
The question is to input two strings: S1 and S2. The objective is to find whether there exist a substring, and I knowstrstrcan be used. If there exists a substring, print the index at S1 at which there is a match, else print -1 . Though I know if there is substringstrstrreturns the first index value, but I don't know ...
Thexneeds to be a pointer: ``` char *x; ``` Then: ``` x=strstr(s1,s2); ``` points to the location withins1ofs2, or NULL. If you need the index, you can write: ``` int indx = x ? x - s1 : -1; // ... printf("%d\n", indx); ``` And by the way, as standard advice, you should usefgets()rather thangets().
Thescanfstatement is giving me trouble. I have tried&arr[i][j]and(arr+i)+jin place of*(arr+i)+j. However, this statement is still giving problems. Here is my code: ``` int **arr, m, n, i, j; scanf("%d%d", &m, &n); arr = (int **) malloc( m * sizeof(int *) ); for (i = 0; i < m; i++) arr[m] = (int *) malloc(n*sizeof(...
There is a severe typo: ``` arr[m] = (int *) malloc(n*sizeof(int)); ``` Should be ``` arr[i] = malloc(n * sizeof(int)); ```
Should there be any errors, if a.hfile contains a signature, which has no implementation in a.cfile?
If you use the function, and it isn't implemented, you will get a link error. Otherwise, no errors or warnings will occur.