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 which situations would you do this? Surely the pointer type (message_t) should be enough to tell the compiler how to dereference the pointer (i.e. how many bytes the first variable in the struct needs, etc). Let me know if my question isn't clear.
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 I compile the code the compiler displays these warnings: "Function is deprecated [-Wdeprecated-declarations]" So what type should I change if I cannot use the function type?
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 the job. */ char *doc; /* Documentation for this function. */ } COMMAND; ```
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 which situations would you do this? Surely the pointer type (message_t) should be enough to tell the compiler how to dereference the pointer (i.e. how many bytes the first variable in the struct needs, etc). Let me know if my question isn't clear.
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 this question In this simple program to find whether a number is even or odd it keeps howing the error Main.c:3:9: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘attribute’ before ‘{’ token. Please help. ``` #include<stdio.h> int main{ int n; scanf("%d",&n); if(n%2==0) printf("%d is an even number",n); else printf("%d is an odd number",n); return 0; } ```
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(number), then I have to getNinteger number inputs from one line like above. The input and output should be : ``` how many do you want to enter: 5 1 2 3 4 5 sum: 15 ```
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 this question In this simple program to find whether a number is even or odd it keeps howing the error Main.c:3:9: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘attribute’ before ‘{’ token. Please help. ``` #include<stdio.h> int main{ int n; scanf("%d",&n); if(n%2==0) printf("%d is an even number",n); else printf("%d is an odd number",n); return 0; } ```
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(number), then I have to getNinteger number inputs from one line like above. The input and output should be : ``` how many do you want to enter: 5 1 2 3 4 5 sum: 15 ```
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 arithmetic for the half precision. Unlessyour compilersupport it. Or goopen source.
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; } ``` When my main function started to work. It will work return value of server_init(). I used DEBUG_INFO in server_init(),too. After the macro line. When in server_init(), Macro didn't write anything. But if server_init() returns False value. then Macro of main function will write error. Why doesn't work macro in function.
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 arithmetic for the half precision. Unlessyour compilersupport it. Or goopen source.
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; } ``` When my main function started to work. It will work return value of server_init(). I used DEBUG_INFO in server_init(),too. After the macro line. When in server_init(), Macro didn't write anything. But if server_init() returns False value. then Macro of main function will write error. Why doesn't work macro in function.
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; } ``` When my main function started to work. It will work return value of server_init(). I used DEBUG_INFO in server_init(),too. After the macro line. When in server_init(), Macro didn't write anything. But if server_init() returns False value. then Macro of main function will write error. Why doesn't work macro in function.
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 record ALT?". Thanks in advance
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> using namespace std; int main () { char i; for(i=8; i<190; i++) { if(GetAsyncKeyState(i)== -32767) { cout<<int (i)<<endl; } } return 0; } ```
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 equivalent of Python script expressionitem in list/setin C code of a Python extension module. Any hints how to accomplish this are welcome.
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 1980s or early 1990s. There is a functiondelayin Turbo Pascal that takes milliseconds. Maybe that's the one the author means.
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 equivalent of Python script expressionitem in list/setin C code of a Python extension module. Any hints how to accomplish this are welcome.
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 1980s or early 1990s. There is a functiondelayin Turbo Pascal that takes milliseconds. Maybe that's the one the author means.
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=fopen("test.csv","r"); fscanf("%lf",&x); printf("%lf",x); fclose(ptr); } ```
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(shmid<0){ perror("shmget"); exit(1); } shm=shmat(shmid, NULL, 0); if(shm==(void*)-1){ perror("shmat"); exit(1); } } ``` Trying to compile i am getting the following compilation error: ``` error: assignment to expression with array type shm=shmat(shmid, NULL, 0); ``` Am i doing something wrong? Thanks for any help.
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() { char output[100]; char input = "He\0ll\0o"; Copy(input, sizeof(input), output); } ```
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 itundefined behavior? IfNo, thenWhy?
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 scalar and one past that scalar. You can't use pointer arithmetic to traverse other memory that you own.
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("--------------------------------------Sum is %d", x); getch(); } ``` s is the sides of the dice
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); } return 0; } ``` Above is part of the code I'm currently working on. I'm getting a warning saying that 'Statement is unreachable' at the Return 0, and I couldn't figure out why.
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)(Param1: DWORD, Param2:DWORD, Param3:DWORD); ``` This is OK for a few functions, but if I want to do the above for dozens of functions, is there a shortcut (like a "magic #define") that will save me from copying almost the exact function declaration over and over again? A "magic" like: ``` #define TYPEDEF_FUNCTION(WindowsFunction....) ``` Thanks!
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 what is happening behind the scenes, can someone help me visualise this problem ?
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 to indicate the error. There arementionsthatoff_tmust be a signed type, so it appear safe to check if the result is negative or non-negative.
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 receive format if there is any. because if I don't setup a receive condition, my read code will last forever. Thank you for your understanding.
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> #include <stdlib.h> int main() { int n, i; printf("Value of n:\n"); scanf("%d", &n); int t[n]; for(i=0; i<n; i++) printf("%d ", rand()%20+30); return 0; } ```
``` 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+20); ```
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); } return 0; } ``` Above is part of the code I'm currently working on. I'm getting a warning saying that 'Statement is unreachable' at the Return 0, and I couldn't figure out why.
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)(Param1: DWORD, Param2:DWORD, Param3:DWORD); ``` This is OK for a few functions, but if I want to do the above for dozens of functions, is there a shortcut (like a "magic #define") that will save me from copying almost the exact function declaration over and over again? A "magic" like: ``` #define TYPEDEF_FUNCTION(WindowsFunction....) ``` Thanks!
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 what is happening behind the scenes, can someone help me visualise this problem ?
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 to indicate the error. There arementionsthatoff_tmust be a signed type, so it appear safe to check if the result is negative or non-negative.
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 receive format if there is any. because if I don't setup a receive condition, my read code will last forever. Thank you for your understanding.
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> #include <stdlib.h> int main() { int n, i; printf("Value of n:\n"); scanf("%d", &n); int t[n]; for(i=0; i<n; i++) printf("%d ", rand()%20+30); return 0; } ```
``` 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+20); ```
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, this would be the code to make it into a full packet: ``` packet = b'\xF0\xF0' + payload + b'\xF0\xF0' packet += bytes([(0 - sum(packet)) & 0xFF]) ```
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 or C).From what I can tell, the alternative character sheet characters are all unsigned chars, defined by the preprocessor. Can someone explain how I can get access to the alternative character sheet characters?
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 in Crystal code.
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 there's no need to castkas adouble, and also, you may have loss of precision by storing your result in anint(truncating) Also note that if you're doing that to get an integer power of10, you'd better use integer multiplication in a loop (there are even better algorithms, but still integers, likeThe most efficient way to implement an integer based power function pow(int, int))
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)); ``` and the output is ``` a = 11111, length = 5 ``` Why is strlen working fine without '\0'? Can someone help me understand?
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]); pt[0] = &matrix1 ``` My goal would be to be able to access any element in one of the two array with something like: ``` pt[0][n][m]; ``` Or for the second matrix: ``` pt[1][n][m] ``` But as far as I know this doesn't work. Is the pointer declaration wrong?
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.otherStruct.unit = '!'; write(file_descriptor, &s, sizeof(s)); ``` And then later: ``` read(file_descriptor, &s, sizeof(s)); ``` Will it work? I mean, when I try to writesto the file, will it write all the fields ofscorrectly? Also, will it read it all back in correctly?
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)); ``` and the output is ``` a = 11111, length = 5 ``` Why is strlen working fine without '\0'? Can someone help me understand?
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]); pt[0] = &matrix1 ``` My goal would be to be able to access any element in one of the two array with something like: ``` pt[0][n][m]; ``` Or for the second matrix: ``` pt[1][n][m] ``` But as far as I know this doesn't work. Is the pointer declaration wrong?
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 performance dramatically, if it can, then I suppose we need to re-write linux process scheduler right? Just wish to know when do we need to call these functions, in my applications? Thanks.
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 switching of realtime process is a overhead. Hence affinity. We direct to kernel that the process0 should run on CPU0.
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, mingw and arm-pe targets, __declspec(dllimport) is recognized as a synonym for __attribute__ ((dllimport)) for compatibility with other Microsoft Windows compilers. Have a look at this visibility support from GCC,https://gcc.gnu.org/wiki/Visibility
``` 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 execute it, it gives me 2,0,4,8,0
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, performs integer division by 10, and recursively calls itself untilnis zero. This in effect means that it will print the decimal digits of the input number which is what you see in the output...
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 are a classic example of systems wherecharcan be 32-bits (or more) and an individual byte (or rather, octet) is not addressable.
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 server send a message received from one client to another?
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 that it is possible to "communicate" from one client to the other.
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_callback_handler); printf("pid: %d \n",getpid()); while(1) { } } ``` When I run this program and make CTRL+C, the kill is handled, and it works. The messageCaught signalis printed. However, when I'm trying to kill from another program ``` int main(int argc, char **argv) { kill(atoi(argv[1]), SIGKILL); return 0; } ``` The program is stoped but the signal is not handled. In other words, the messageCaught signalis not printed. The infinite loop is just stopped.
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;j>=i;j--) { printf("%c",c); } for(k=1;k<=i;k++) { printf(" "); } for(l=5;l>=i;l--) { printf("%c",c); } printf("\n"); } getch(); return 0; } ``` This program prints the pattern shown below. ``` ***** ***** **** **** *** *** ** ** * * ``` So, what are your suggestions ?
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 internet but I can't find sth relevant to help me. How to install the missing library? Or should I reinstall gcc? Please help! Thanks!
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 on Linux. No amout of fiddling with linker flags is likely to change that.
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 in the function, when the function is over variable thevalue is still empty... So, I want pointer on array in the structure. How should I fix that?
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(thedata, &thevalue)) { puts(thevalue); } } ```
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 - we don't know what pw_dir points to */ const char *homeDir = strdup( pwd->pw_dir ); ``` Error checking is left as an exercise...
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] = "hello";when use ``` #include <stdio.h> #include <string.h> int main() { char a[] = "hello"; char b[] = "hello"; if (strcmp(a,b) == 0) printf("strings are equal.\n"); else printf("strings are not equal.\n"); return 0; } ```
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 - we don't know what pw_dir points to */ const char *homeDir = strdup( pwd->pw_dir ); ``` Error checking is left as an exercise...
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 About Floating-Point Arithmetic.
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 SLD_RenderCopyEx. However, as I expected, this function doesn't affect the surface but the renderer, and if I want to save the result(after rotation) I will not get the rotated version of the image. Do you guys know if there is any way of saving the image as I see it on the screen? And if not, what do you guys suggest me to do ?
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 Take a Example :Any Custom methodABCD ===>> ABCD, ABDC,ACBD,ACDB, ADCB, BACD, BADC, BCAD, BCDA, BDAC , BDCA , CADB,CBDA,CDBA, CBAD, DABC, DBCA, DCBA,DCAB...... thanks in Advance
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 << s << '\n'; } while(std::next_permutation(s.begin(), s.end())); } ``` Onlinehere
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 (aref arr i) (* (aref arr i) 2)) ``` The statement of accessing the array has to write two times, if there is a function/macromulfhave similar function as*=in C language. I can write code as ``` (mulf (aref arr i) 2) ``` Then the array accessing statement is needed to write only once. Thanks.
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 allocated a memory with 4000(1000*sizeof(int)) sizes memory, only 1.when I use*(x-100)=-100,the shell will outputSegmentation fault, which seems to make sense. Can you tell me why?ThanksI use ubuntu 16.04.4 and gcc 5.4.0
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" variable while comparing with TEST_VARIABLE. if TEST_VARIABLE is stored in different data type, extra instruction shall be required.
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_VARIABLE; loop++) ``` is treated identically to ``` for (unsigned int loop = 0; loop < 10; loop++) ``` The compiler will interpret10as asigned int.
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 likemac = (unsigned char *)macAddressand so on but nothing worked for me well.Is there any correct way how to convert it without any precision loss?
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 page.
``` 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: "Access violation writing location".
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 are looking for is to copy the string"correct_"to the allocated area in memory. So use: ``` strcpy(filenameCorrect, "correct_"); ``` then you can safely usestrcat.
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."); return FALSE; } return TRUE; } ``` I have all constants in a header file. Constants are 0 and 9.
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."); return FALSE; } return TRUE; } ``` I have all constants in a header file. Constants are 0 and 9.
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]); b = 0; } else { printf("%c ", a[i]); } b++; } printf("\n"); return 0; } ``` Purpose is that I should generate random array of letters from 'a' to 'z' (which I've managed to do) and after that print new array without elements that repeat in first array. I've tried implementing code fromherefor removing duplicate elements but it didn't worked in my code.
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 cmd because it gives mentioned error. But it perfectly runs in turbo c++. I have set environment variables. what should i do?
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,"%s",str)!=EOF) { strcpy(arr[l],str); l++; } for(i=0;i<l;i++) { system(arr[i]); } } ```
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 $(CC) -c $(CFLAGS) $(INCLUDEDIR) $< ``` This one outputs :make: *** No rule to make target 'object.o', needed by 'all'. Stop. Any direction, how to achieve that?
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. Notice that I assume you moved the trailing/out of$(SRCDIR)(as it's cleaner that way).
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 write this, it wnly takes first object file ``` A: $(OBJDIR)/$(OBJ) ``` The compilation then .... ....-g -O0 -DWITH_POSIX -Iinclude/ -o A .obj/A.o B.o It should take recursively from directory. probably I am missing the correct way to handle this. Anyone have a sugestion, please let me know.
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 $(CC) -c $(CFLAGS) $(INCLUDEDIR) $< ``` This one outputs :make: *** No rule to make target 'object.o', needed by 'all'. Stop. Any direction, how to achieve that?
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. Notice that I assume you moved the trailing/out of$(SRCDIR)(as it's cleaner that way).
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 write this, it wnly takes first object file ``` A: $(OBJDIR)/$(OBJ) ``` The compilation then .... ....-g -O0 -DWITH_POSIX -Iinclude/ -o A .obj/A.o B.o It should take recursively from directory. probably I am missing the correct way to handle this. Anyone have a sugestion, please let me know.
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.size = 100; return type; } ``` Let's say there is some other file called example.h that needed to call this function foo from header. Does it matter if I add the work extern for the function or variable? From what I hear, it is needed for variables. ``` //example.h #include "header1.h" extern int randomNum; extern Type foo(int); ```
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 <stdio.h> char main(void){ char var[3]; printf("Enter your name: "); scanf("%1f", &var); printf("%s", &var); } ```
``` #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 case-sensitive filesystem, just take directory name of the current file, list file contents, and compare entries against the current filename, ignoring case.
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; } } printf("hi\n"); } ``` outputs: ``` hi hi hi ```
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 child processes. If you want it to execute only in a specific process, you should put it in that branch of theswitch()statement.
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 this?
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: If you call it on the "same line" as suggested in the title (but not the question itself), then the second barrier is effectively a no-op - you've already hit a synchronization point; what exactly is the second barrier going to do?
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 management function, or if the space has been deallocated by a call tofreeorrealloc, the behavior is undefined. So, as long as you pass the sameptrvalue (the pointer itself or a copy of it) which was earlier returned bymalloc()or family, you're good to go.
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)); ((int(*)(const char *, ...))printf_copy)("%s\n", "hello, world"); return 0; } ```
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 some executable memory is throughmmap,malloconly gives you heap memory which is usually not executable part of the process space.
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. from the first line of main function),how I can do it using the IDE? I know underWindows,there is a tool calledgflag,using this tool we can do some configuraitons before starting the process,and when the process is launched,the gflag can detect this and let the debugger tool(e.g. virtual studio) attach the process automatically. Do not tell me that usesleepfuction.
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 loop body does not execute, leavingsumto it's initialized value. That said, int main()should better beint main(void)for a hosted environment.Always check the return value ofscanf()for success before using the scanned value.
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 from a raw X11 window, no Qt or GTK involved. Thanks :)
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 instance creation time. EitherVK_KHR_XLIB_SURFACE_EXTENSION_NAMEorVK_KHR_XCB_SURFACE_EXTENSION_NAME. You then provide that surface at swapchain creation time (given your application does some visible output). Seethe WSI chapter of the spec for details.
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.