question
stringlengths
25
894
answer
stringlengths
4
863
i have a project where in the user can be the client or server. if he use the program first, he will serve as the server then the other one will be the client and vice versa. is there a possible way to do this ?
Maybe not the best way, but you can try to bind a server socket to some port and assume that if you can, then you are the server. otherwise, you are the client.
Suppose we have a struct "message_t": ``` message_t *msg; ``` If a function returns a void pointer can we simply assign the address to msg, or do we need to cast the pointer?: ``` void *data; msg = data; ``` I've seen cases where "data" would be cast tomessage_t, however this doesn't seem entirely necessary, so in...
You do not need to cast a void pointer, but you can if you want to, i.e., for clarity. The following simple sample illustrates this: ``` void* data = malloc(32); char* msg = data; strcpy(msg, "Testing."); ```
I used the code in below link: Readline Library And I defined a struct like this ``` typedef struct { char *name; /* User printable name of the function. */ Function *func; /* Function to call to do the job. */ char *doc; /* Documentation for this function. */ } COMMAND; ``` When ...
Functionis atypedef(an alias of a pointer to function returningint) marked as deprecated by thelibrary: ``` typedef int Function () __attribute__ ((deprecated)); ``` Just use: ``` typedef struct { char *name; /* User printable name of the function. */ int (*func)(); /* Function to call to do ...
i have a project where in the user can be the client or server. if he use the program first, he will serve as the server then the other one will be the client and vice versa. is there a possible way to do this ?
Maybe not the best way, but you can try to bind a server socket to some port and assume that if you can, then you are the server. otherwise, you are the client.
Suppose we have a struct "message_t": ``` message_t *msg; ``` If a function returns a void pointer can we simply assign the address to msg, or do we need to cast the pointer?: ``` void *data; msg = data; ``` I've seen cases where "data" would be cast tomessage_t, however this doesn't seem entirely necessary, so in...
You do not need to cast a void pointer, but you can if you want to, i.e., for clarity. The following simple sample illustrates this: ``` void* data = malloc(32); char* msg = data; strcpy(msg, "Testing."); ```
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.Closed6 years ago.Improve...
Because you left off the()when declaringmain, the compiler thinks you are declaring a variable, hence the confusion expressed in the error message.
This question already has answers here:Accepting any number of inputs from scanf function(6 answers)Closed6 years ago. If I want to get input 3 numbers, I can write code like this: ``` scanf("%d %d %d", &a, &b, &c); ``` buthow can I dynamically get the number of inputs from one line? For example, if user entersN(n...
Sincescanfreturns the amount of variables filled you can loop untilscanfhas no more value to read or the count is matched: ``` int count = 0; printf("how many do you want to enter: "); scanf("%d", &count); int val = 0; int sum = 0; int i = 0; while(scanf("%d ", &val) == 1 && i++ < count) sum += val; ```
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.Closed6 years ago.Improve...
Because you left off the()when declaringmain, the compiler thinks you are declaring a variable, hence the confusion expressed in the error message.
This question already has answers here:Accepting any number of inputs from scanf function(6 answers)Closed6 years ago. If I want to get input 3 numbers, I can write code like this: ``` scanf("%d %d %d", &a, &b, &c); ``` buthow can I dynamically get the number of inputs from one line? For example, if user entersN(n...
Sincescanfreturns the amount of variables filled you can loop untilscanfhas no more value to read or the count is matched: ``` int count = 0; printf("how many do you want to enter: "); scanf("%d", &count); int val = 0; int sum = 0; int i = 0; while(scanf("%d ", &val) == 1 && i++ < count) sum += val; ```
I'm currently trying to make my own version of getopt() function. But I do not know how it returns a character type as an int type. Is there any way I can have a look into the source code of the getopt() function?
The source code ofgetopt()inglibcis here:https://github.com/lattera/glibc/blob/master/posix/getopt.c Of course there are more implementations you might look at, but this is probably the most popular one. Here's another, from FreeBSD:https://github.com/lattera/freebsd/blob/master/lib/libc/stdlib/getopt.c
I need something like uint16_t but for floating point numbers instead of integer. I need to be able to convert a float to it so I can transfer it and convert back to float later (obviously I will lose some precision). Is there a simple solution for this or should I do it manually?
There is no such thing in the C standard.Some compilers do have __fp16. You can useQ numbers, but these are limited in a fixed range. If you really needfloatingpoint, with the exponent, then you should implement theieee standard half precision. Regular artimetics work on the Q numbers. You should write your own ari...
I have this macro and this main function. ``` #define DEBUG_INFO(format, args...) \ fprintf(stdout, "%12s: %3d: %s ", __FILE__, __LINE__, green), \ fprintf(stdout, format, ##args) int32_t main() { if (server_init()) { DEBUG_INFO("Child process wasnt created"); } return 0; } ...
You can callsetbuf(stdout, NULL)to disable output buffering onstdout, or you can simply output a\nto flush the output buffer. The second option is preferable.
I need something like uint16_t but for floating point numbers instead of integer. I need to be able to convert a float to it so I can transfer it and convert back to float later (obviously I will lose some precision). Is there a simple solution for this or should I do it manually?
There is no such thing in the C standard.Some compilers do have __fp16. You can useQ numbers, but these are limited in a fixed range. If you really needfloatingpoint, with the exponent, then you should implement theieee standard half precision. Regular artimetics work on the Q numbers. You should write your own ari...
I have this macro and this main function. ``` #define DEBUG_INFO(format, args...) \ fprintf(stdout, "%12s: %3d: %s ", __FILE__, __LINE__, green), \ fprintf(stdout, format, ##args) int32_t main() { if (server_init()) { DEBUG_INFO("Child process wasnt created"); } return 0; } ...
You can callsetbuf(stdout, NULL)to disable output buffering onstdout, or you can simply output a\nto flush the output buffer. The second option is preferable.
I have this macro and this main function. ``` #define DEBUG_INFO(format, args...) \ fprintf(stdout, "%12s: %3d: %s ", __FILE__, __LINE__, green), \ fprintf(stdout, format, ##args) int32_t main() { if (server_init()) { DEBUG_INFO("Child process wasnt created"); } return 0; } ...
You can callsetbuf(stdout, NULL)to disable output buffering onstdout, or you can simply output a\nto flush the output buffer. The second option is preferable.
After testing a lot I can't record if Alt key is pressed usingGetAsyncKeyStatein a C program. When I try this: ``` if (GetAsyncKeyState(VK_SHIFT)) // do something ``` It works properly, but when I try this ``` if (GetAsyncKeyState(VK_MENU)) // do something ``` It doesn't work.So my question is "How I can r...
I use the code below to find out the value of any key that perfectly fits inGetAsyncKeyState, I think it is 18 forALTkey . ``` #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #if _WIN32_WINNT < 0x0500 #undef _WIN32_WINNT #define _WIN32_WINNT 0x0500 #endif #include <windows.h> usin...
Writing a Python extension module which is intended to speed up execution of a function written as Python script I am stuck with the problem of how to check in C-code of a Python extension module if a C-Python object is in a C-Python set/list of C-Python objects. In other words what I am looking after is the equivale...
intPySequence_Contains(PyObject *o, PyObject *value)Determine ifocontainsvalue. If an item inois equal tovalue, return1, otherwise return0. On error, return-1. This is equivalent to the Python expressionvalue in o. source
This question already has answers here:dos.h for Linux?(3 answers)Closed6 years ago. I got this message when I compiled a C program "fatal error: dos.h: No such file or directory compilation terminated." I am currently using Ubuntu 16.04
I believe you can't do that, because from the sound of it, "dos.h" is specific to MS-DOS.
In a book, I saw a piece of code. but when I ran this code it said: C:\Users\dipankar\Desktop\cla.cpp [Error] 'delay' was not declared in this scope They used it without proper documentation. They only said that "delay() is used to delay the execution of the next line by few milliseconds"!!. please help.
The book you are reading is crap. Avoid the book and tell others to do the same. <conio.h>is a system-specific header and not guaranteed to be available on many platforms.The result offgetcmust never be stored in acharvariable.The functionfeofmust never be used in a loop condition. The book probably comes from the 1...
I am scanning for a date in the format mm-dd-yyyy and I need to take out three ints and use them for multiple things. How can I create three integers with mm dd and yyyy? Thanks!
Use thesscanfcall from<stdio.h>. ``` char line[80]; int m, d, y; fgets(fgets(line, sizeof line, stdin); sscanf(line, "%d-%d-%d", &m, &d, &y); ``` It is better to use fgets+sscanf instead of scanf directly, because scanf has the notorious\nissue and does not check buffer lengths.
Writing a Python extension module which is intended to speed up execution of a function written as Python script I am stuck with the problem of how to check in C-code of a Python extension module if a C-Python object is in a C-Python set/list of C-Python objects. In other words what I am looking after is the equivale...
intPySequence_Contains(PyObject *o, PyObject *value)Determine ifocontainsvalue. If an item inois equal tovalue, return1, otherwise return0. On error, return-1. This is equivalent to the Python expressionvalue in o. source
This question already has answers here:dos.h for Linux?(3 answers)Closed6 years ago. I got this message when I compiled a C program "fatal error: dos.h: No such file or directory compilation terminated." I am currently using Ubuntu 16.04
I believe you can't do that, because from the sound of it, "dos.h" is specific to MS-DOS.
In a book, I saw a piece of code. but when I ran this code it said: C:\Users\dipankar\Desktop\cla.cpp [Error] 'delay' was not declared in this scope They used it without proper documentation. They only said that "delay() is used to delay the execution of the next line by few milliseconds"!!. please help.
The book you are reading is crap. Avoid the book and tell others to do the same. <conio.h>is a system-specific header and not guaranteed to be available on many platforms.The result offgetcmust never be stored in acharvariable.The functionfeofmust never be used in a loop condition. The book probably comes from the 1...
I am scanning for a date in the format mm-dd-yyyy and I need to take out three ints and use them for multiple things. How can I create three integers with mm dd and yyyy? Thanks!
Use thesscanfcall from<stdio.h>. ``` char line[80]; int m, d, y; fgets(fgets(line, sizeof line, stdin); sscanf(line, "%d-%d-%d", &m, &d, &y); ``` It is better to use fgets+sscanf instead of scanf directly, because scanf has the notorious\nissue and does not check buffer lengths.
I'm looking at a program that was written in C and I need to write it in C#. What is the C# equivalent of this whole line?: ``` printf("%s", " "); ```
If you can use C# 6, you could use string interpolation, and go like this. ``` Console.WriteLine($"{variableName} text"); ```
I do not know what is happening in this very basic code but the output says that the program has stopped working. Can anyone help me? ``` #include<stdio.h> #include<stdlib.h> main() { FILE *ptr; double y=9.0; double x; ptr=fopen("test.csv","w"); fprintf(ptr,"%lf",y); fclose(ptr); ptr=fo...
Here, is the correct piece of code, you need to change yourscanfstatement ``` include<stdio.h> #include<stdlib.h> main() { FILE *ptr; double y=9.0; double x; ptr=fopen("test.csv","w"); fprintf(ptr,"%lf",y); fclose(ptr); ptr=fopen("test.csv","r"); fscanf(ptr,"%lf",&x); printf("%lf",x); fclose(ptr); } ```
This question already has answers here:Escape character in C(6 answers)Closed6 years ago. I need to check into a loop if the user inserts '\' for exiting from the menu. ``` while(choise != '\'){ // do stuff } ``` But I get this error: error: missing terminating ' character
Backslashes are special characters and need to be escaped with another backslash: ``` while (choice != '\\') { ```
I am trying to atach achar shm[][]var into shared memory and i have the following piece of code. ``` int main(){ int shmid; key_t key; char shm[15][10]; if ((key = ftok("test.c", 'R')) == -1) { perror("ftok"); exit(1); } shmid=shmget(key, SHM_SIZE, IPC_CREAT | 0666); if(s...
You want: ``` char (*shm)[10] = shmat(shmid, NULL, 0); ``` This is a pointer to a two-dimensional rectangular array with an unknown number of rows and ten columns.
Is there any C library function that copies achararray (that contains some'\0'characters) to anotherchararray, without copying the'\0'?For example,"he\0ll\0o"should be copied as"hello".
As long as you know how long the char array is then: ``` void Copy(const char *input, size_t input_length, char *output) { while(input_length--) { if(input!='\0') *output++ = input; input++; } *output = '\0'; /* optional null terminator if this is really a string */ } void test() { ...
If I incrementingNULLpointer in C, then What happens? ``` #include <stdio.h> typedef struct { int x; int y; int z; }st; int main(void) { st *ptr = NULL; ptr++; //Incrementing null pointer printf("%d\n", (int)ptr); return 0; } ``` Output: ``` 12 ``` Is itun...
The behaviour is always undefined. You can never own the memory at NULL. Pointer arithmetic is only valid within arrays, and you can set a pointer to an index of the array or one location beyond the final element. Note I'm talking about setting a pointer here, not dereferencing it. You can also set a pointer to a sc...
I'd like to store the variable(two spaces) in C. It looks like there are no string data types in C, so how can I store such a value without having to create astring s = get_stringfunction?
Strings in C programming are built as arrays of chars. In your case:char c[] = " ";
I am on dice game in which i need to roll the dice 5 times and sum the random number. Everything is working fine but my sum is not according to the random number which i am getting ``` for (int i = 1; i <= 5; i++) { printf(" %d time dice rolled = %d \n",i, rand() % s + 1); x += rand() % s + 1; } printf("----...
You are calling therandfunction when displaying the information and then again when saving which explains the disparity.
``` int main(void) { TIM4_Init(); setSysTick(); while (1) { TIM4->CCR1 = 600; // 600 == 0.6 ms -> 0' Delay(700); TIM4->CCR1 = 1500; // 1500 == 1.5 ms -> 90' Delay(700); TIM4->CCR1 = 2100; // 2100 == 2.1 ms -> 150' Delay(700); } r...
The while (1) loops forever, so without a way to get out if the loop, you won't get to the return. To get rid of the warning, you can change main() to return void void main (void) { }
I'm implementing some low level stuff and need to "typedef" many system (Windows) functions. For example, this is a test function that I want to typedef for the hook: ``` BOOL WINAPI WindowsFunction(Param1: DWORD, Param2:DWORD, Param3:DWORD); ``` And the Typedef should be: ``` typedef BOOL (WINAPI *TWindowsFunction...
C++11'sdecltypecan be used this way, either withtypedeforusing: ``` typedef decltype(&WindowsFunction) TWindowsFunction; ``` or: ``` using TWindowsFunction = decltype(&WindowsFunction); ```
``` #include<stdio.h> int main() { int a; char *x; x = (char *) &a; a = 512; x[0] = 1; x[1] = 2; printf("%d\n",a); return 0; } ``` I'm not able to grasp the fact that how the output is 513 or even Machine dependent ? I can sense that typecasting is playing a major role but w...
Theint ais stored in memory as 4 bytes. The number512is represented on your machine as: ``` 0 2 0 0 ``` When you assign tox[0]andx[1], it changes this to: ``` 1 2 0 0 ``` which is the number513. This is machine-dependent, because the order of bytes in a multi-byte number is not specified by the C language.
A small question aboutlseek(C system call). I know that upon failure the return value of the function will be negative. Can we know for sure that if the return value is not negative the function actually moved to the desired location?
If the value is(off_t)-1, there was an error. If the value isn't(off_t)-1, the call was successful. From my system's man page, Upon successful completion,lseek()returns the resulting offset location as measured in bytes from the beginning of the file. On error, the value(off_t)-1is returned anderrnois set t...
I am writing a C++ application that can send and receive AT&T USSD codes to and from a phone connected to a PC through usb (serial communication). The problem I have is, after sending some USSD code request to the phone, I don't know theconditionthat makes me stop read listening. What is the general AT&T USSD code r...
the stop condition is<CR><LF>OK<CR><LF>or<CR><LF>ERROR<CR><LF>
This question already has answers here:Generate random number in C within a range and a specific step(2 answers)How to use the rand function to make numbers in a specific range?(4 answers)Closed6 years ago. I've tried but it doesn't seem to give me the desired numbers. Here's my code so far: ``` #include <stdio.h> #...
``` printf("%d ", rand()%20+30); ``` generates random numbers between 30 and 50 (not included). You need ``` printf("%d ", rand()%10+20); ``` to generate between 20 and 30 (not included) 10being the range, and20being the offset. To include both end points (giving 11 possible values): ``` printf("%d ", rand()%11+...
When we are writingprintf()in C, are we declaring it or defining? If it is a definition then where is the declaration and vice versa?
When we are writingprintf()in C, we are making a call toprintf, which has adeclarationin the<stdio.h>header like thisint printf(const char *format, ...);, and we should include that header in the C program. Thedefinitionofprintfis in the standard library implementation that gets linked with the application code.
``` int main(void) { TIM4_Init(); setSysTick(); while (1) { TIM4->CCR1 = 600; // 600 == 0.6 ms -> 0' Delay(700); TIM4->CCR1 = 1500; // 1500 == 1.5 ms -> 90' Delay(700); TIM4->CCR1 = 2100; // 2100 == 2.1 ms -> 150' Delay(700); } r...
The while (1) loops forever, so without a way to get out if the loop, you won't get to the return. To get rid of the warning, you can change main() to return void void main (void) { }
I'm implementing some low level stuff and need to "typedef" many system (Windows) functions. For example, this is a test function that I want to typedef for the hook: ``` BOOL WINAPI WindowsFunction(Param1: DWORD, Param2:DWORD, Param3:DWORD); ``` And the Typedef should be: ``` typedef BOOL (WINAPI *TWindowsFunction...
C++11'sdecltypecan be used this way, either withtypedeforusing: ``` typedef decltype(&WindowsFunction) TWindowsFunction; ``` or: ``` using TWindowsFunction = decltype(&WindowsFunction); ```
``` #include<stdio.h> int main() { int a; char *x; x = (char *) &a; a = 512; x[0] = 1; x[1] = 2; printf("%d\n",a); return 0; } ``` I'm not able to grasp the fact that how the output is 513 or even Machine dependent ? I can sense that typecasting is playing a major role but w...
Theint ais stored in memory as 4 bytes. The number512is represented on your machine as: ``` 0 2 0 0 ``` When you assign tox[0]andx[1], it changes this to: ``` 1 2 0 0 ``` which is the number513. This is machine-dependent, because the order of bytes in a multi-byte number is not specified by the C language.
A small question aboutlseek(C system call). I know that upon failure the return value of the function will be negative. Can we know for sure that if the return value is not negative the function actually moved to the desired location?
If the value is(off_t)-1, there was an error. If the value isn't(off_t)-1, the call was successful. From my system's man page, Upon successful completion,lseek()returns the resulting offset location as measured in bytes from the beginning of the file. On error, the value(off_t)-1is returned anderrnois set t...
I am writing a C++ application that can send and receive AT&T USSD codes to and from a phone connected to a PC through usb (serial communication). The problem I have is, after sending some USSD code request to the phone, I don't know theconditionthat makes me stop read listening. What is the general AT&T USSD code r...
the stop condition is<CR><LF>OK<CR><LF>or<CR><LF>ERROR<CR><LF>
This question already has answers here:Generate random number in C within a range and a specific step(2 answers)How to use the rand function to make numbers in a specific range?(4 answers)Closed6 years ago. I've tried but it doesn't seem to give me the desired numbers. Here's my code so far: ``` #include <stdio.h> #...
``` printf("%d ", rand()%20+30); ``` generates random numbers between 30 and 50 (not included). You need ``` printf("%d ", rand()%10+20); ``` to generate between 20 and 30 (not included) 10being the range, and20being the offset. To include both end points (giving 11 possible values): ``` printf("%d ", rand()%11+...
When we are writingprintf()in C, are we declaring it or defining? If it is a definition then where is the declaration and vice versa?
When we are writingprintf()in C, we are making a call toprintf, which has adeclarationin the<stdio.h>header like thisint printf(const char *format, ...);, and we should include that header in the C program. Thedefinitionofprintfis in the standard library implementation that gets linked with the application code.
Here is the following spec. I use python3 to talk to a server with TCP/IP using a simple protocol as you see in the image. I wonder how do i calculate the CRC checksum here ?. Its need to be 1 byte as you see in the Command package spec.
I presume in Python 3, if you have the packet in bytes, i.e. saypacket = bytes(0xF0, 0xF0, 0xDE, 0xAD, 0xBE, 0xEF, 0xDE, 0xAD, 0xBE, 0xEF, 0xF0, 0xF0), the checksum would simply be the least-significant byte of 1's complement of the sum of these bytes, i.e.(0 - sum(packet)) & 0xFF. Thus, if you have a payloadpayload,...
I'm working with thecrt.crCrystal shard, which binds ncurses. It's lacking some things I want, likemvhline(). So I'm adding the things I want. One thing I want is is ncurses alternative character sheet, so I can make nice boxes. As far as I can tell, this is pretty dang hard (but I'm not an expert in either Crystal ...
You cannot access things that are only in C header files (and things that are done through the preprocessor) in a shared library file, because they simply aren't put there. Since Crystal only binds to a shared library file, there is no option other than manually (sometimesautomatically) duplicating these as constants...
I keep getting this error: 'Math' undeclared first use in this function although I included the math library. ``` int x = Math.pow(10.0,(double)k); ``` This is the line where I get the error, any ideas why?
powis part of the math library, but there are no namespaces or packages in C. So first ``` #include <math.h> ``` then call as: ``` int x = pow(10.0,k); ``` Old versions ofgccrequire you to add-lmwhen linking, although this is unnecessary with latest versions (version 6 doesn't require it anymore). note that ther...
This question already has answers here:Difference between malloc and calloc?(14 answers)Closed6 years ago. As title, I have some question using char* in c. For example, if I write this ``` char *a = calloc(5, 5); a[0] = '1'; a[1] = '1'; a[2] = '1'; a[3] = '1'; a[4] = '1'; printf("a = %s, length = %d", a, strlen(a));...
calloc(5, 5)allocates and zeroes 25 bytes. You assign the first five of these, but the sixth is still'\0'.
I was wondering if it is possible to dereference a pointer to a two dimensional array in C: ``` int matrix1[2][2] = {{1,2},{3,4}}; int matrix2[2][2] = {{4,5},{6,7}}; ``` I am trying to create an array of pointers, where the first pointer points to matrix1 and the second one to matrix2. I thought of ``` int *(pt[2])...
You have to declareptas an array of pointers to array. ``` int (*pt[2])[2] = { matrix1, matrix2 }; ``` Demo.
Lets say I have the following struct: ``` typedef struct s1 { int field1; int field2; struct s2 otherStruct; }; ``` Wheres2is some other struct that I made: ``` typedef struct s2 { double field1; char unit; }; ``` If I use ``` s1 s; s.field1 = 1; s.field2 = 2; s.otherStruct.field1 = 42; s.ot...
This will work, if you compile the code with the same compiler, the same compiler flags, and run it on the same machine, and never change the definition of the structs. Change anything, and it you'll read garbage. To solve this problem in a more resilient and portable way, considerGoogle's protobufsorCap'n proto.
This question already has answers here:Difference between malloc and calloc?(14 answers)Closed6 years ago. As title, I have some question using char* in c. For example, if I write this ``` char *a = calloc(5, 5); a[0] = '1'; a[1] = '1'; a[2] = '1'; a[3] = '1'; a[4] = '1'; printf("a = %s, length = %d", a, strlen(a));...
calloc(5, 5)allocates and zeroes 25 bytes. You assign the first five of these, but the sixth is still'\0'.
I was wondering if it is possible to dereference a pointer to a two dimensional array in C: ``` int matrix1[2][2] = {{1,2},{3,4}}; int matrix2[2][2] = {{4,5},{6,7}}; ``` I am trying to create an array of pointers, where the first pointer points to matrix1 and the second one to matrix2. I thought of ``` int *(pt[2])...
You have to declareptas an array of pointers to array. ``` int (*pt[2])[2] = { matrix1, matrix2 }; ``` Demo.
The operating system is able to determine how to arrange difference processes/threads onto different cpu cores, the os scheduler does the work well. So when do we really need to call functions like sched_setafficity() for a process, or pthread_setaffinity_np() for a pthread? It doesn't seem to be able to raise any pe...
It's very helpful in some computationally intensive real time processes related to DSP(Digital Signal Processing). Let's say One real time DSP related process PROCESS0 is running on core CPU0. Because of some scheduling algorithms CPU0 pre-emption need to happen such that process0 has to run on another CPU. This swit...
What is the use of __declspec() in GCC compilers? From some research i found that it is a Microsoft specific extension to access shared .dll libraries. So what is it's use in Linux(or Rots like mqx)? This is a piece of sample code that i found which is to be compiled with GCC. ``` __declspec(section "configROM") ```
What I would imagine that anARMrunning some obscureWindowsX/ARMsystem would also need your__declspec; conversely, your__declspechas no sense on Linux/x86. AFAIK, ``` __attribute__((visibility("default"))) ``` And there is no equivalent of__declspec(dllimport)in linux to my knowledge. dllimport/dllexport On cygwin...
``` void foo(int n, int sum) { int k = 0, j = 0; if (n == 0) return; k = n % 10; j = n / 10; sum = sum + k; foo (j, sum); printf ("%d,", k); } int main () { int a = 2048, sum = 0; foo (a, sum); printf ("%d\n", sum); getchar(); } ``` For me this should be 4,0,2,8,0 However, when i ...
As the code stands, the argumentsumtofoois not really relevant since it is passed by value so the last statement in the main functionprintf ("%d\n", sum)will print0regardless of what happens insidefoo. That's the last0you see in the output the program generates. Now, the functionfooitself accepts an argumentn, perfor...
In a 32 bit machine, if you copied an int p, it would copy 4 bytes of information, which would be addressed at 0xbeefbeef, 0xbeefbef0, 0xbeefbef1, 0xbeefbef2 respectively. Is this the same with 64 bit? Or does it store 2 bytes at a single address?
It depends on the architecture. On most "normal" 64-bit systems (e.g. arm64, x86_64, etc.) memory is "byte addressed," so each memory address refers toonebyte (so it's the same as your 32-bit example). There are systems out there which arenotbyte addressed, and this can included 64-bit architectures. For example,DSPs...
I'm trying to create a simple "chatroom" program with C on Unix, using RPC. Currently, multiple clients can connect to a server and call on functions generated by RPCGEN. The server receives arguments and responds with a return value. The relationship is always between client and server. How can I use RPC to have my...
As per John Bollinger's very helpful last comment: "(...) the server can relay messages only via its responses to RPC calls by clients. (...)" So basically no, clients cannot communicate directly with other clients. They can send and ask for information through a call to the server, and it is through those requests t...
I want to handle akill signalfrom C program. I'm starting by create an infinite loop and handle the signal ``` void signal_callback_handler(int signum) { printf("Caught signal %d\n",signum); // Cleanup and close up stuff here // Terminate program exit(signum); } main() { signal(SIGINT, signal_callba...
This is it:you cannot catch aSIGKILL, it willdefinitelykill your program, this is what it's been created for.
How do I get the index of the first non-whitespace character in a string. For example for the string" #$%abcd"I would expect getting the index 3 for#.
Usestrspn()to find the length of the whitespace and then skip past it. ``` #include <stdio.h> #include <string.h> #include <strings.h> const char whitespace[] = " \f\n\r\t\v"; char *str = " Hello World!"; void main() { char *stripped = str + strspn(str, whitespace); printf("Stripped msg: '%s'", stripped)...
I have two stringschar name1[100], name2[100];I want to concatenate the first letters of these strings. How can I do it?I want to do it with the function strcat.My code
Where is the trick in this question? ``` char conc[3]; conc[0] = name1[0]; conc[1] = name2[0]; conc[2] = '\0'; ``` Or using the same array: ``` name1[1] = name2[0]; name1[2] = '\0'; ``` UPDATE Using strcat: ``` name1[1] = '\0'; name2[1] = '\0'; strcat(name1,name2); ```
I want to create a program to print a pattern as shown below, ``` ********** **** **** *** *** ** ** * * ``` I've tried creating this pattern, but it's not printing the star in the middle of the first line. This is the code. ``` int main() { int i,j,k,l; char c='*'; for(i=1;i<=5;i++) { for(j=5...
The center loop should befor(k=1;k<i;k++)(with a<instead of<=). Otherwise, each line has an extra space in the middle.
I am trying to compile my C socket programming files using gcc with -lnsl option on MAC OS but it gives me this error: ld: library not found for -lnslclang: error: linker command failed with exit code 1 (use -v to see invocation) This is the gcc command: ``` gcc -o server -lnsl server.c ``` I looked all over the...
Mac OS X has no libnsl. Functions that live in libnsl on Linux are found in the standard C library on Mac OS X. No additional flags are necessary for building programs that use these functions. If your program works on Linux and doesn't work on a Mac, then your program has a bug that is triggered on Mac OS X but not ...
i am new to C lang. My code is like: ``` int afunc(const struct datas *mydata, void *value) { value = &mydata->astring; // astring is in structure char[20] return 0; } int main (...) { ... const char *thevalue; if (!afunc(thedata, &thevalue) {...} ... } ``` The address in var value is only i...
fix like this ``` #include <stdio.h> struct datas { char astring[20]; }; int afunc(const struct datas *mydata, void *value) { *(const char **)value = mydata->astring; return 0; } int main (void) { struct datas mydata = { "test_data" }, *thedata = &mydata; const char *thevalue; if (!afunc(th...
I have two stringschar name1[100], name2[100];I want to concatenate the first letters of these strings. How can I do it?I want to do it with the function strcat.My code
Where is the trick in this question? ``` char conc[3]; conc[0] = name1[0]; conc[1] = name2[0]; conc[2] = '\0'; ``` Or using the same array: ``` name1[1] = name2[0]; name1[2] = '\0'; ``` UPDATE Using strcat: ``` name1[1] = '\0'; name2[1] = '\0'; strcat(name1,name2); ```
I usesnprintfto write formatted data to disk, but I have one problem, how do I save it to the user's home directory? ``` snprintf(filename, sizeof(filename), "%s_%s.sho", client, id); ```
The user controls his environment - so theHOMEenvironment variable may not be correct or it may not even be set. Usegetuid()andgetpwuid()to get the user's home directory as specified by your system: ``` #include <unistd.h> #include <pwd.h> struct passwd *pwd = getpwuid( getuid() ); /* need to duplicate the string ...
when I explicitly state the value of a string, then compare it to itself, system returns FALSE. Does this have something to do with the extra '\0' character added by the system? And how should I refine my code to make it TRUE? ``` char name[5] = "hello"; if(name == "hello") { ... } ```
You can't (usefully) compare strings using!=or==, you need to usestrcmpThe reason for this is because!=and==will only compare the base addresses of those strings. Not the contents of the strings. don't use predefined array size likechar name[5] = "hello";instead of you can usechar name[] = "hello";orchar name[6] = "he...
I usesnprintfto write formatted data to disk, but I have one problem, how do I save it to the user's home directory? ``` snprintf(filename, sizeof(filename), "%s_%s.sho", client, id); ```
The user controls his environment - so theHOMEenvironment variable may not be correct or it may not even be set. Usegetuid()andgetpwuid()to get the user's home directory as specified by your system: ``` #include <unistd.h> #include <pwd.h> struct passwd *pwd = getpwuid( getuid() ); /* need to duplicate the string ...
My compiler is telling me that the size ofsizeof(long double)is 16 byte, which means it can represent a number up2^128. Now, I want to know until how many digits the precision can handle. For instance, ifx= 0.1234567812345678, canlong doubleidentify the exact precision ofxhere? Thank you
Theheaderfloat.hcontains some macros desribing the precision of the different floating-point data types; e.g.LDBL_MANT_DIGgives you the number of binary digits in the mantissa of along double. If you don't understand the format of floating-point numbers, I recommend you readWhat Every Computer Scientist Should Know A...
I want to create an image processing application with SDL. My problem is that I want to rotate a surface. I tried to write the algorithm for accessing the pixels and putting them in the right position but I get really jaggy results.For this reason,I thought that the easiest solution would be to take advantage of the ...
You can useSDL_RenderReadPixels()to read pixels from the current rendering target.
This question already has answers here:Algorithm to return all combinations of k elements from n(77 answers)Closed6 years ago. I need to access all possible number of combinations of characters in a string. Without Using Any loop, because i have to filter records in thousands. loop can give performance issue. lets T...
There is in fact a function in the C++ standard library for this:std::next_permutation. Here is the example from the link, adapted to your case. ``` #include <algorithm> #include <string> #include <iostream> int main() { std::string s = "ABCD"; std::sort(s.begin(), s.end()); do { std::cout <<...
I wonder if there is some function/macro in Common Lisp has similar function as*=or/=operation in C/C++. incfanddecfin Common Lisp can be considered as+=and-=. In C/C++ ``` A *= 2; ``` equals to ``` A = A * 2; ``` In Common Lisp When I want to set a new value to an array element, I have to write as ``` (setf (...
As stated in the comments, this can easily be created usingDEFINE-MODIFY-MACRO. ``` (define-modify-macro mulf (x) *) ```
I am getting stuck because of this error and can't test my application.
You only can specific value indimentag. So, please give them aspordpvalue instead of name. Hope this helped.
here is my code ``` #include <stdlib.h> #include <malloc.h> #include <stdio.h> int main() { void *p=malloc(1); int *x=(int*)(p); *(x+1000)=1000; printf("*(x+1000)=%d\n",*(x+1000)); //*(x-100)=-100; //Segmentation fault return 0; } ``` the output is ``` *(x+1000)=1000 ``` but I didn't ...
There's nothing in the C language that prevents you from reading or writing outside the bounds of a variable or allocated memory. You dynamically allocate 1 byte of memory, then you attempt to write to a memory location 1000 * sizeof(int) bytes after it. Doing so invokesundefined behavior.
if I define a macro like below: ``` #define TEST_VARIABLE 10 ``` How does the compiler store it internally? as an signed/unsigned integer? I have a loop in my program: ``` for (unsigned int loop = 0; loop < TEST_VARIABLE; loop++) ``` I want to check if extra instruction is added by compiler to type cast "loop" va...
When the preprocessor performs macro replacement, it treats it as text. The fact that the replacement looks like a number is totally irrelevant during macro processing. When the compiler processes the result, it's exactly as if you'd typed the replacement in its place. So ``` for (unsigned int loop = 0; loop < TEST_V...
I'm trying hard to convertchar *macAddressintounsigned char mac[6]but without success so far. My input string looks like "00:10:6f:16:01:b3" and I want to devide it into mac[0] = 0x00, mac[1] = 0x10, etc.. I've tried to usememcpylike: ``` memcpy(&mac, (unsigned char)macAddress, sizeof mac); ``` or same another ways...
You want to convert hexadecimal digits (i.e. the string "00") of the mac address to byte values (i.e. the value 0). Thememcpyinstead copies the value of the string digits (i.e. '0' is 48 or 0x30). You can usesscanffor the correct conversion. At least on Linux, you can also use the functionether_aton. See the man pag...
``` int verify(char filename[], int filenameLength) // If f.ex. filename is "x.txt" then filenameLength is 5 { char* filenameCorrect = malloc(sizeof(char) * (filenameLength + 9)); filenameCorrect = "correct_"; strcat(filenameCorrect, filename); ... } ``` Everytime i run this i get this exception: "Ac...
filenameCorrectis a pointer, not a variable that holds the characters rather a pointer to some area in memory that was assigned to hold the characters. In the second line you are reassigningfilenameCorrectto point to a string that is compiled as part of the code and thus cannot be changed hence the error. What you ar...
I am running into a really weird error. Commenting out the below pieces of code lets my program run. Keeping it in, gives me the error. In my functions .c file: ``` int validateArgs(int MIN_INPUT, int MAX_INPUT, int argc) { if ((argc < MIN_INPUT) || (argc > MAX_INPUT)) { printf("Wrong input."); ...
Your line ``` int validateArgs(int MIN_INPUT, int MAX_INPUT, int argc) ``` translates as ``` int validateArgs(int 0, int 9, int argc) ``` because of your constant definitions. That is not correct C syntax and probably not what you want.
Will this work? I expect ``` foo(myArraypointer + 10); ``` be the same as ``` foo( &(myArraypointer[10])); ``` will this be treated as same for most compilers? Is this considered good or bad practice and why? What could go wrong?
For any pointer or arrayaand indexi, the expressiona[i]is equal to*(a + i). That means that&a[i]is equal to&*(a + i), where the last can be shortened toa + i.
I am running into a really weird error. Commenting out the below pieces of code lets my program run. Keeping it in, gives me the error. In my functions .c file: ``` int validateArgs(int MIN_INPUT, int MAX_INPUT, int argc) { if ((argc < MIN_INPUT) || (argc > MAX_INPUT)) { printf("Wrong input."); ...
Your line ``` int validateArgs(int MIN_INPUT, int MAX_INPUT, int argc) ``` translates as ``` int validateArgs(int 0, int 9, int argc) ``` because of your constant definitions. That is not correct C syntax and probably not what you want.
Will this work? I expect ``` foo(myArraypointer + 10); ``` be the same as ``` foo( &(myArraypointer[10])); ``` will this be treated as same for most compilers? Is this considered good or bad practice and why? What could go wrong?
For any pointer or arrayaand indexi, the expressiona[i]is equal to*(a + i). That means that&a[i]is equal to&*(a + i), where the last can be shortened toa + i.
So I have this code: ``` #include <stdio.h> #include <stdlib.h> int main() { char a[200], b = 0; int x; x = 100 + rand() % 200; for (int i = 0; i < x; i++) { a[i] = 'a' + rand() % 26; } for (int i = 0; i < x; i++) { if (b % 10 == 0) { printf("\n%c ", a[i]); ...
A simple solution is to loop over the array and copy each element to a new array,butfirst check that the value doesn't already exist in the new array.
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.Closed5 years ago.Improve this question I have downloaded zip file of Turbo C++ 3.2 for my windows 10 64-bit. I can not run it in...
64Bit Windows no longer supports old 16Bit DOS applications. Youneed to use doxbox to get the tool runningor use thisupdated TurboC++ version, which includes DOSBox and does magic for you.
I am getting the error atfp=fopen("task.txt","r")please could anybody help me out?I am trying to open file withfp(File pointer) ``` main() { int l=0,pr[100]; FILE *fp; fp=("task.txt","r"); if(fp==NULL) printf("No file found"); char arr[100][20]; const char *str;int i; while(fscanf(fp,"...
Your code has no such line. Check your code again. You wrote without fopen ``` fp=("task.txt","r"); ``` write this ``` fp=fopen("task.txt","r"); ``` you will get it
While this works perfectly : ``` object.o: $(SRCDIR)object.c $(CC) -c $(CFLAGS) $(INCLUDEDIR) $< mv object.o $(OBJDIR) ``` The goal is to create .o file inside a directory automatically while creating it. ie. not like first create and then move. I did this : ``` $(OBJDIR)/object.o: $(SRCDIR)object.c ...
I think you're looking for something like this: ``` $(OBJS) = $(patsubst $(SRCS),$(SRCDIR)/%.c,$(OBJDIR)/%.o) $(OBJS) : $(SRCDIR)/%.o : $(OBJDIR)/%.c @echo "$< => $@" @$(CC) -c -o $@ $(CFLAGS) $(INCLUDEDIR) $< ``` This is astatic pattern rulewhich says to build your objects using a specific pattern. Notic...
There is a small problem in Makefile. Whenever I write this, it works well ``` OBJDIR:=.obj OBJ := A.o B.o ``` . . . ``` A: $(OBJDIR)/A.o $(OBJDIR)/B.o $(CC) $(CFLAGS) $(INCLUDEDIR) -o $@ $^ ``` The compilation goes like this .... ....-g -O0 -DWITH_POSIX -Iinclude/ -o A .obj/A.o .obj/B.o But instead, if I w...
Assuming you're usingGNU make, ``` A: $(addprefix $(OBJDIR)/,$(OBJ)) A: $(patsubst %,$(OBJDIR)/%,$(OBJ)) A: $(foreach obj,$(OBJ),$(OBJDIR)/$(obj)) ``` will all do the same thing.
While this works perfectly : ``` object.o: $(SRCDIR)object.c $(CC) -c $(CFLAGS) $(INCLUDEDIR) $< mv object.o $(OBJDIR) ``` The goal is to create .o file inside a directory automatically while creating it. ie. not like first create and then move. I did this : ``` $(OBJDIR)/object.o: $(SRCDIR)object.c ...
I think you're looking for something like this: ``` $(OBJS) = $(patsubst $(SRCS),$(SRCDIR)/%.c,$(OBJDIR)/%.o) $(OBJS) : $(SRCDIR)/%.o : $(OBJDIR)/%.c @echo "$< => $@" @$(CC) -c -o $@ $(CFLAGS) $(INCLUDEDIR) $< ``` This is astatic pattern rulewhich says to build your objects using a specific pattern. Notic...
There is a small problem in Makefile. Whenever I write this, it works well ``` OBJDIR:=.obj OBJ := A.o B.o ``` . . . ``` A: $(OBJDIR)/A.o $(OBJDIR)/B.o $(CC) $(CFLAGS) $(INCLUDEDIR) -o $@ $^ ``` The compilation goes like this .... ....-g -O0 -DWITH_POSIX -Iinclude/ -o A .obj/A.o .obj/B.o But instead, if I w...
Assuming you're usingGNU make, ``` A: $(addprefix $(OBJDIR)/,$(OBJ)) A: $(patsubst %,$(OBJDIR)/%,$(OBJ)) A: $(foreach obj,$(OBJ),$(OBJDIR)/$(obj)) ``` will all do the same thing.
Say I have the following header and .c file declared within my project. Imagine Type is a data type that I declared. ``` //header1.h typedef struct Typing { int size; } Type; Type foo(int); int randomNum; ``` And here is the .c file ``` //header1.c #include "header1.h" Type foo(int size) { Type type; type....
externis needed onextern int randomNum;to keep the declaration from being a definition. If you have a definition of a variable in your header file, you will get multiple definition errors at link time. Functions areexternby default, so you don't need it there.
So I am learning the C programming language and I want to run a basic script in which the user inputs a variable and the variable that is printed out is the one in which the user inputed, which is simple, however, the code I wrote prints a random thing that has nothing to do with the code, please help. ``` #include <...
``` #include <stdio.h> void main(void){ char var[20]; printf("Enter your name: \n"); scanf("%s", var); // Note: %s is for char arrays and not %f(floats) printf("%s", var); // Note: no ampersand here } ```
For example, suppose we have a file called "Hello.txt", then checking if "hello.txt" or "heLLo.txt" exist should both return true.
If you're running Windows or any case-insensitive filesystem, then there's nothing to do but check one casing. If"Hello.txt"exists, then"hEllo.txt"exists (and is the same file) (the difficult problem here is when you want to make sure that the file is spelled with a given casing in the filesystem) If you're running a...
I have this code with two childs and his father, but there is a problem because all childs (and father execute the code on main). code: ``` int main() { switch (fork()) { case 0: //child1 break; default: switch (fork()) { case 0: //child2 break; default: //father break; }...
When you usefork()it creates an almost-exact duplicate of the parent process, except for the return value from thefork()call. They both continue and execute all the same code, except for anything that depends on that return value. Since the call toprintf()is not conditional, it will be executed in both the father and...
Using OpenMPI in C; Say I'm have ``` main() { MPI_Init(); //// Important Program Region MPI_Barrier(MPI_COMM_WORLD); // do something here MPI_Barrier(MPI_COMM_WORLD); //// MPI_Finalize(); } ``` Is this bad practice? Can I force synchronisation in forcing barriers twice like this? Any disadvantages of doing thi...
The above program should work as is. It is perfectly acceptable to force synchronization viaMPI_Barriernot just once or twice, but for as many times as you want. With that said, the major disadvantage ofMPI_Barrieris that the scalability of your program will be significantly lesser the more times you call it. Note: I...
Is this: ``` int *a = malloc (sizeof (int) ); int *b = a; free (b); ``` the same as this: ``` int *a = malloc (sizeof (int) ); free (a); ``` If yes, no need to explain, but if no, please elaborate why not!
Yes, they are equivalent. QuotingC11, chapter §7.22.3.3, (emphasis mine) Thefreefunction causes thespace pointed to byptrto be deallocated, that is, made available for further allocation. Ifptris a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory ma...
In C or C++, can one obtain the size occupied by a function, allocate memory dynamically withmalloc()for it, make a copy, and execute it with a function pointer cast? Am just curious about it, and here is a non-working example: ``` #include <stdio.h> int main(void) { void *printf_copy = malloc(sizeof(printf)); ...
First, you can't get size of the code used by a function such a way, there is no C operator or function for this. The only way is to get it from ELF headers, etc. Beware that a function may call others, so you usually need some kind of linking... and that function code may not be relative! Second, the only way to get...
As you know,eclipse IDE has a convenientattached debugging facilityfor C project.You can see it from theGUIand you can use this facility to debug process that are already in running status,likedaemon process.. My questionis that when a process just started and I want to debug it from the begining of the process(i.e. ...
Check CDT reverse debugging. You will need GDB 7.0 or later for this feature. ReferHow_do_I_do_Reverse_Debugging
``` #include <stdio.h> #include <stdlib.h> int main() {int array1[10],i=0,sum=0; while(i<10) {scanf("%d",&array1[i]); i=i+1; } while(i<10) {sum=sum+array1[i];i=i+1; } printf("sum =%d",sum); return 0; } ``` The code compiles fine but while running it does not produce any result, it always prints 0.
The problem is in the second loop. Check the value ofiwhile entering thewhileloop body and thereafter. You need to reset the value ofi. Otherwise, the second loop does not execute. After the execution of the first loop,ihold a value of10and unless changed, the secondwhileloop condition evaluates to false, thus the lo...
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.Closed6 years ago.Improve this question I'm trying to create a Vulkan application in Linux. How can I obtain a Vulkan context fro...
If you already got your X11 window you need to defineVK_USE_PLATFORM_XLIB_KHRand create a Vulkan compatible surface from it usingvkCreateXlibSurfaceKHR, or if you want to use XCB you'd usevkCreateXcbSurfaceKHRand defineVK_USE_PLATFORM_XCB_KHR. Also note that you need to provide the proper surface extension at instanc...
I have a function which splits a string into tokens and stores it in an array. How to determine the size of an array of strings of typechar**? ``` ie: char **input; ```
Keep a variable globally and increment that variable value in the function which is splitting the string into tokens & storing into array.