question
stringlengths
25
894
answer
stringlengths
4
863
I am going through the Kadane's Algorithm for Maximum sub-array problem.Now what I understand from the statement the algo that we have find asub-array. Does sub-array include whole array itself. Actually I was trying following program ``` int main(void) { int arr[9]={5,6,-4,-1,-2,1,5,3}; int i,n,max_last =0,max_mid =0; for(i=0;i<8;i++) { max_mid = max_mid + arr[i]; printf("max_mid =%d\n",max_mid); if ( max_mid < 0) max_mid =0; if( max_mid > max_last) max_last = max_mid; } printf("val=%d",max_last); return 0; } ``` Here it is giving 13 as final answer which is the sum of all element of array.
Yes, any continuous sub-array could be a solution, including the whole array. Note that empty sub-array might be valid solution too (for all negative numbers algorithm gives max sum result 0)
I am using char array to store data when using fscanf function, as there is no space to malloc the char* before the function. However, I need it to be pointer for next function as the input is set as char pointer. How can I do it? (Does it actually make sense?)
Iffoois of typechar[n]for integraln, then you can use &foo[0] to give you the pointer to the zeroth element offoo. The type of this expression ischar*.
I am using char array to store data when using fscanf function, as there is no space to malloc the char* before the function. However, I need it to be pointer for next function as the input is set as char pointer. How can I do it? (Does it actually make sense?)
Iffoois of typechar[n]for integraln, then you can use &foo[0] to give you the pointer to the zeroth element offoo. The type of this expression ischar*.
The question how to print one \ is already asked for many times. I couldn't find anything about printing two backslashes (\\). When I try to write this:fputs("\\\\",w_ptr); there won't be more backslashes than one. If you are interested: it's a custom bill writing program which creates Latex PDF with a csv feed. And there are a lot of double-backslashes in there which indicate a new line feed. Thanks in advance!
Since you already know how to print one backslash, printing two of them should be easy. ``` fprintf(file, "%s\n", "\\"); // one backslash fprintf(file, "%s\n", "\\\\"); // two of them ``` Oh, andalways activate compiler warnings. The first argument tofprintfmust be a file pointer, not a string.
I have recently started to code in C and I am having quite a lot of fun with it. But I ran into a little problem that I have tried all the solutions I could think of but to no success. How can I assign a char* variable to an array? Example ``` int main() { char* sentence = "Hello World"; //sentence gets altered... char words[] = sentence; //code logic here... return 0; } ``` This of course gives me an error. Answer greatly appreciated.
You need to give the arraywordsa lengthchar words[100]; // For exampleThe usestrncpyto copy the contentsstrncpy(words, sentence, 100);Just in case add a null character if the stringsentenceis too longwords[99] = 0;
I am not able to execute even a simple c code through the mingW development environment. This code works fine ``` #include<stdio.h> int main(){ char ans[5]; printf("Enter yes or no"); scanf("%s", ans); printf("You just entered", ans); return 0; } ``` But whenever I convert the datatype of ans tochar*and then execute the .exe file that has been created by the command ``` gcc basic.c -o basic.exe ``` I am not able to see the output, it just saysbasic.exe has stopped working. I don know if there is some issues in the installation in the mingW or what.
You are not suppose to see an output, the program is suppose to crash because Its not enough to change ans to char*, you need to allocate a place for the string using malloc: ``` ans=malloc(sizeof(char) * 5); ``` And also the printf should be: ``` printf("....%s",ans); ```
I need to create 5 processes one being father of the second, grandpa of the third etc. All of them have to wait for each other to finish. I tried the approach with: ``` switch (pid = fork()) { case 0: printf("Child PID = %d\n", getpid()); printf("parent: =\%d\n", getppid()); return 0; default: break; ``` But I always get the same parent.
You need to use recursion. For example: ``` void create_processes(int n) { if(n == 0) return; if(fork() == 0) { int status; // You're in the child process. Calling it recursively will have the // child's PID as parent create_processes(n - 1); // Do work you need done before the child terminates wait(&status); // Do work you need done after the child terminates } } ``` Then call it like ``` create_processes(5); ```
I've been trying to use GNU indent to indent some very simple C files, and I wish to use the K&R indentation style but without any use of spaces, purely tabs. I've triedindent -kr --use-tabs, and justindent -krbut they both just use the default K&R with spaces or mix indentation with spaces and tabs. Is there a way to use K&R with GNU indent while strictly using tabs only? If not, is there a better utility for indentation in this style?
The default assumed width of a tab in GNU indent is 8 (because historically that is what line-printers, teletypes and dumb terminals use). If your indent width is not then a multiple of 8, the tool will mix tabs and spaces to meet your indent width specification. You need to set the tab width to match your indent with the--tab-size/-tsoption,as described in the documentation.
I'm beginner forC languageand forEclipse IDE. I've downloaded and installed Eclipse ide for c/c++ developers i.e. Mars 2.0. I've created a new project and selected the appropriate compiler and typed the following code: ``` #include <stdio.h> int main() { printf("Hello, World! \n"); return 0; } ``` After, when click build project it creates .exe file for me and when I click on Debug it successfully Debugs butshutdowns automatically within a fraction of a second.
From what you've told us, that would be correct. If you want to step through the code, you have to set a breakpoint. You should be able to double-click in the margin on the "printf" line to set a breakpoint there.
GCC (I am using GCC-4.8.5) has the concepts of prologue and epilogue, which are used to generate codes at the beginning and end of each function. I am wondering how to insert my own code into the prologue and epilogue. I tried to search "prologue/epilogue" in the gcc source code, but still do not have any idea(I am new to compiler). Can anyone tell me how to achieve this in detail (e.g. which function in gcc shall I look for, and etc.). Someone asked a similar questionhere, but the answers there were not helpful.
It depends on what you exactly want to do. Instead of changing he compiler which is a complicated job to do you may insert asm code before your function call or in your function to manipulate the compiler-implemented call mechanism. Or you may use asm code to call your function instead of using standard syntax. I remember I read about this somewhere. I think it was one of osdev.org articles.
I'm beginner forC languageand forEclipse IDE. I've downloaded and installed Eclipse ide for c/c++ developers i.e. Mars 2.0. I've created a new project and selected the appropriate compiler and typed the following code: ``` #include <stdio.h> int main() { printf("Hello, World! \n"); return 0; } ``` After, when click build project it creates .exe file for me and when I click on Debug it successfully Debugs butshutdowns automatically within a fraction of a second.
From what you've told us, that would be correct. If you want to step through the code, you have to set a breakpoint. You should be able to double-click in the margin on the "printf" line to set a breakpoint there.
GCC (I am using GCC-4.8.5) has the concepts of prologue and epilogue, which are used to generate codes at the beginning and end of each function. I am wondering how to insert my own code into the prologue and epilogue. I tried to search "prologue/epilogue" in the gcc source code, but still do not have any idea(I am new to compiler). Can anyone tell me how to achieve this in detail (e.g. which function in gcc shall I look for, and etc.). Someone asked a similar questionhere, but the answers there were not helpful.
It depends on what you exactly want to do. Instead of changing he compiler which is a complicated job to do you may insert asm code before your function call or in your function to manipulate the compiler-implemented call mechanism. Or you may use asm code to call your function instead of using standard syntax. I remember I read about this somewhere. I think it was one of osdev.org articles.
I just started venturing into C coming from PHP. I'm having trouble with theprintf()function when its called from within another function: ``` #include <stdio.h> void printloop (int valx) { int x; for (x = valx; x < 5; x++) { printf("Value of x is: %d\n", x); } } int main() { printloop(5); return 0; } ``` The program will compile and run but there is no output on screen.
When you invoke theprintloopfunction with5the for loop essentially becomes ``` for (x = 5; x < 5; x++) { //... } ``` Andx < 5will never be true. I guess what you meant was something like ``` for (x = 0; x < valx; x++) { //... } ```
See i know there are various methods to communicate between threads but my question is specific for LINX. Please answer. Thanks in advance
threads of the same process share heap staff, synchronized bythread lock, Semaphore and condition variable. Besides, The communication approach from Interprocess communication(IPC for example,PIPE/FIFO/MessageQueue/SharedMemory/Signal/Socket) works for threads communication, too. take FIFO for example(neglect error code checking): ``` char buf[110]; char *FIFO = "/tmp/my_fifo"; mkfifo(FIFO, O_CREAT); int fd = open(FIFO, O_RDONLY, 0); int nread = read(fd, buf, 100); ```
I'm going through an exercise book on C and came across the statement ``` printf("%c", "\n"); ``` Which when run in a console still works but displays the "$" symbol. Why did this statement not crash the console like ``` printf("%s", '\n'); ``` does?
a double quoted string like that produces a value of a pointer tochar(akachar*), while the single quote produce a value that's a character (using the ASCII value of whats in the quotes. On some compilers you can stack multiple characters into the single quotes. ``` printf("%c", *("\n") ); ``` would print your linefeed, as the*operator would dereference the pointer ( You could probably do*"\n", I just tend to be conservative in writing expressions) ``` printf("%s", '\n'); ``` crashes because%sexpects a pointer, and a linefeed cast into a pointer is pointing off in the weeds and most likely causes an invalid memory access
See i know there are various methods to communicate between threads but my question is specific for LINX. Please answer. Thanks in advance
threads of the same process share heap staff, synchronized bythread lock, Semaphore and condition variable. Besides, The communication approach from Interprocess communication(IPC for example,PIPE/FIFO/MessageQueue/SharedMemory/Signal/Socket) works for threads communication, too. take FIFO for example(neglect error code checking): ``` char buf[110]; char *FIFO = "/tmp/my_fifo"; mkfifo(FIFO, O_CREAT); int fd = open(FIFO, O_RDONLY, 0); int nread = read(fd, buf, 100); ```
I'm going through an exercise book on C and came across the statement ``` printf("%c", "\n"); ``` Which when run in a console still works but displays the "$" symbol. Why did this statement not crash the console like ``` printf("%s", '\n'); ``` does?
a double quoted string like that produces a value of a pointer tochar(akachar*), while the single quote produce a value that's a character (using the ASCII value of whats in the quotes. On some compilers you can stack multiple characters into the single quotes. ``` printf("%c", *("\n") ); ``` would print your linefeed, as the*operator would dereference the pointer ( You could probably do*"\n", I just tend to be conservative in writing expressions) ``` printf("%s", '\n'); ``` crashes because%sexpects a pointer, and a linefeed cast into a pointer is pointing off in the weeds and most likely causes an invalid memory access
im just trying to open a file. i have done it for 100 times, and then I sent SIGCHLD signal to other processes and i think right after that i couldn't open that file anymore. ``` #include <signal.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #define FLAGS IPC_CREAT | 0644 int main() { int res =open("results.txt",FLAGS); if(res== -1) { printf("error!!")} //prints it every time return 0;} ``` ..it suddenly just happened.. help ???
You're doing something strange with the flags. I think your intention is as per below code: ``` #define FLAGS O_CREAT #define MODE 0644 int main() { int res =open("results.txt",FLAGS,MODE); if(res== -1) { printf("error!!");} //prints it every time return 0; } ```
I have some code that looks like this: ``` char template[] = "temp-XXXXXX"; FILE * f = mkstmp(template); /* ... some stuff is written to f with fprintf ...*/ char fname[15] = xyzzy(f); // <-- Problem char tmp[20]; sprintf(tmp,"less %s", fname); system(tmp); ``` I need to find out the name given tofbymkstmpso I can calllesson it.
templatewill have been changed to the file's name. So: ``` sprintf(tmp,"less %s",template) system(tmp); ```
This question already has answers here:Default case in a switch condition(3 answers)Closed7 years ago. Why this code compile and run fine. I have written defau1t instead of default , 1 at the place of l. ``` #include<stdio.h> int main() { int i=4; switch(i) { case 3: break; defau1t : break; } } ```
defau1t :is a valid label name, even if it is not a case label. You could have agoto defau1t;somewhere else in the code.
This question already has answers here:Default case in a switch condition(3 answers)Closed7 years ago. Why this code compile and run fine. I have written defau1t instead of default , 1 at the place of l. ``` #include<stdio.h> int main() { int i=4; switch(i) { case 3: break; defau1t : break; } } ```
defau1t :is a valid label name, even if it is not a case label. You could have agoto defau1t;somewhere else in the code.
I have already tried the basic way to solve this series but it takes time for the larger values ofn&r. Is there any way to reduce this expression in a single expression whose time complexity doesn't depend on the value ofnORr.Range r,n<=10^5 NOTE: herer < ni.e. i have to find the sum of firstr+1terms of this series. I have already read this question but it doesn't help me: Algorithm to find Sum of the first r binomial coefficients for fixed n modulo m
AFAIK, there is no such expression to which it can be reduced. But it can be done in O(r) time complexity as follows. Consider an array A, where A[i] storesnci. Then we can easily verify that A[i] = A[i-1].(n-i+1)/(i) So ``` A[0] = 1; for(int i=1;i<=r;i++){ A[i] = A[i-1].(n-i+1)/(i); } int ans = 0; //The required answer for(int i=0;i<=r;i++){ ans = ans+A[i]; } ```
Currently the the file gets created and overwritten. I am trying to get it so that if the file already exists it just exits the program. open must be used. ``` if ((dest = open(argv[2], O_WRONLY | O_CREAT, 0644)) == -1) { printf("Error File %s exists", argv[2]); return 3; } ```
Just useO_EXCL: O_EXCLEnsure that this call creates the file: if this flag is specified in conjunction withO_CREAT,and pathname already exists, thenopen()will fail.
By defaultargpuses stdout. In the argp-parse.c source code, you can see that in the init function the value is initialized to stdout: ``` parser->state.out_stream = stdout; ``` The struct argp_state is internally used argp and stores the valueout_stream. I would like to change the default behaviour and redirect the stream to another file descriptor.
What you can do is redirectstdoutand restore it later: ``` int orig_stdout = dup(STDOUT_FILENO); extern int my_other_file_descriptor; dup2(my_other_file_descriptor, STDOUT_FILENO); // parse args dup2(orig_stdout, STDOUT_FILENO); ```
I find afoo.hfile having: ``` typedef STRUCT_s STRUCT; STRUCT *foo(); ``` and thefoo.cfile: ``` #include "i_foo.h" struct STRUCT_s{ //... }; #define STRUCT struct STRUCT_s STRUCT *foo() { STRUCT *s; //... return s; } ``` Is it the common way to hide the structure definition in C ? If yes, I wonder, if the structure is not declared in the header, how is the client supposed to use it?
This is a common way to hide structure definition in C. And client isn't supposed to use structure directly. He has to use only proposed functions from interface to interact with data: instantiate, set or get values, launch operation on it,.... With this way, implementation is totally hidden to client. So client is not constraint by changes in implementation. Library can evolves as it need without disturbing client, according no change in interface.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question When I compile and run the C code shown below, it generates the following: Input: ``` #include <stdio.h> int main() { int i, j; int a, b; for (j = 0; j <= 4; j+=2) { a = j; b = 0; for (i = 0; i <= 4; i++) { b += 2 * a * i; } printf("%d %d\n", a, b); } } ``` Output: ``` 0 0 2 40 4 80 ``` If anyone can tell me why the following input generates the above output, this would be much appreciated.
Hope you understand it with the simple trace table I draw.
By defaultargpuses stdout. In the argp-parse.c source code, you can see that in the init function the value is initialized to stdout: ``` parser->state.out_stream = stdout; ``` The struct argp_state is internally used argp and stores the valueout_stream. I would like to change the default behaviour and redirect the stream to another file descriptor.
What you can do is redirectstdoutand restore it later: ``` int orig_stdout = dup(STDOUT_FILENO); extern int my_other_file_descriptor; dup2(my_other_file_descriptor, STDOUT_FILENO); // parse args dup2(orig_stdout, STDOUT_FILENO); ```
This question already has an answer here:How do I add custom windows' resources into executable without resource compiler?(1 answer)Closed7 years ago. I am looking to inject an icon (.ico) file into an executable that does not have any resources. pseudo C++ code: ``` read("target.exe"); AddResourceA(LPCSTR("icon.ico")); save("target1.exe"); ``` This code should load the executable, inject the icon, then save the new executable.
The functions you are probably looking for are: BeginUpdateResource UpdateResource EndUpateResource There should be plenty of examples of usage of these functions if you did a web search.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question i have this expression int *(*foo())[30] is foo a function (which receive no arguments) and returns a pointer to an array (size 30) of pointers of integers ?
No. You can decode declaration in reverse order of normal evaluation of expression. Normal evaluation order: foofoo()*foo()(*foo())[30]*(*foo())[30] So this declaration is: *(*foo())[30]:a pointer(*foo())[30]:array ofpointers*foo():a pointer toarray of pointersfoo():function that returns apointer to array of pointersfoo So this declaration means "a functionfoothat returns a pointer to array of pointers toint". The point in which you are wrong is that the number of arguments offooisn't specified here, so its number of arguments need not be zero.
when I generate C code from python3 code withcython3and try to compile with gcc the resulting code, I get this error :test.c:4:20: fatal error: Python.h: Aucun fichier ou dossier de ce type. I looked over the web for this error, and all the answer were about installingpython2-devorpython3-dev, but I already have this two installed in my computer. I don't only have these two, but I havepython3.4-devandpython3.5-devtoo. So can anyone give me the solution to this error. PS : I am using Ubuntu 15.10 with linux version > 4 .
You should compile using the appropriate paths, like this... ``` $ gcc -o test test.c `pkg-config --cflags --libs python3` ``` What happened before is that you weren't including the appropiate include paths (retrieved bypkg-config --cflags) and library/linking paths (retrieved bypkg-config --libs). Including both, your program should be able to compile and link.
ERROR: type should be string, got "\nhttps://github.com/mackyle/sqlite\n\nAbove is the source code of SQlite\nIt use tcl script to concat the whole program into a single file sqlite3.c\n\nWhat I am currently doing is I use the tcl script provided to split the huge sqlite3.c (see section 2.0 inhttps://www.sqlite.org/amalgamation.html#2)\nand write a cmake script to allow me to debug it in CLion.\n\nIs there a better/proper way to do it? It would be nice if I could debug in the original file structure .\n"
You can compile sqlite without the amalgamation into a singlesqlite3.c. This can be done by passing the--disable-amalgamationoption to./configure: ``` ./configure --disable-amalgamation ```
I want to dynamically load library from SD card, with dlopen, but when I do it, get error: dlopen failed: couldn't map "/storage/emulated/0/Documents/Tests/armeabi-v7a/libtest.so" segment 2: Operation not permitted When i use it for internal storage it's work. What can i do to solve this problem?
This is disallowed by Android's security policy. Anyone can write to that location, so loading code from it is an easily exploitable attack vector.
if I have this data in a file : Mercure 99842 1 18 2001 5 30 1991 16 12.5Mazda 123961 2 20 1993 6 15 1993 19.3 16.7 and I'm interested in , say, just the third number of each line, and I want to store it in an array. What I used to do , is to use some variables to store all the values in the line , and then I pick the one I'm interested in . for example : ``` while(fscanf(file,"%s %d %d %d %d %d %d %f %f",a,&b,&array[i],&d,&e,&r,&t,&g,&h)!=EOF) {i++;} ``` array[i] is storing the value that I'm interested in , and the other variables are just to mach the format , I do not need them . Is there any better way of doing this ?
You can use*to havefscanf()read values and throw them away. ``` while(fscanf(file,"%*s %*d %d %*d %*d %*d %*d %*f %*f",&array[i])!=EOF) {i++;} ```
How do I set up a while loop to loop if a variable is between a range? For example if a number is <100 or >1500 than loop. I tried the below but it didn't work... ``` while (number < 100 || number > 1500); ```
Conditions in programming don't work like in math. Every comparison like that returns a true or false value. If you need the number to be in a certain range you have to set up 2 conditions:number <= maxandnumber >= min. Now you will have two bool outputs but you need to combine them into one. '&&' operator is used to do that. The final statement will look like:(number <= max && number >= min). That will return true when both above values are true. (<=and>=will return true if the left value is smaller/larger or equal) I'd suggest posting programming related questions on stackoverflow instead next time, which is focused on programming and software engineering.
To format a double for JSON with maximal precision but no trailing zero's we use%.15g. However in order to distinguish between integers and real numbers we want to format doubles with at least one digit, i.e."%.1f", except for numbers in scientific notation (which are doubles by definition). Is there a way to implement this in a single snprintformat? ``` double val; char buf[32]; if(fabs(val) < 1e15 && !fmod(val, 1)){ // whole numbers get at least one decimal snprintf(buf, 32, "%.1f", val); } else { // automatically detemines decimal or scientific notation snprintf(buf, 32, "%.15g", val); } ```
Just use conversion specifierg, and add.0at the end of string, if string contains only sign and digit characters. Theyajllibrary has anexample implementation: ``` char buf[32]; sprintf(buf, "%.20g", val); if (strspn(buf, "0123456789-") == strlen(buf)) { strcat(buf, ".0"); } ```
My code: ``` PGresult *res = PQexec(m_IConnection, "MOVE NEXT in my_cursor_name"); ExecStatusType status = PQresultStatus(res); if (status != PGRES_COMMAND_OK) { PQclear(res); return; } ``` But it does not fail after it reaches the last row. I've searched all over and can find no reference for detecting the end of rows.
Per the first comment, if(!stricmp(PQcmdTuples(res), "0")) works to check for the last row of the MOVE
I need to copy one file to windir, So I do: ``` TCHAR windir[MAX_PATH]; GetWindowsDirectory(windir, MAX_PATH); ``` to get the windir. ``` char newLocation[]="text.txt"; // how to add the windir here? BOOL stats=0; CopyFile(filename, newLocation, stats); ``` My problem is, I want to add the windir value before the text.txt in char newLocation[]. Any ideas?
Did you try concatenating the strings, like this? ``` #include <stdlib.h> #include <string.h> char* concat(char *s1, char *s2) { char *result = malloc(strlen(s1)+strlen(s2)+1);//+1 for the zero-terminator //in real code you would check for errors in malloc here strcpy(result, s1); strcat(result, s2); return result; } ``` If that won't work, givewcscat()a shot! Sources: How do I concatenate two strings in C?What is difference between TCHAR and WCHAR?C++ Combine 2 Tchar
As per thisquestion, from c-faq.com, it's not possible to assign achar **to aconst char **without a cast. The explanation given at the link is perfectly reasonable and easy to understand. Indeed, doing it would violate the promise not to modify the pointed data. I, cannot understandWhy is it illegal to pass it to a funcion? I can't see why this ``` void function(const char **pointer) { // Prevent modifying pointer } int main(void) { char **pointer; // Initialize pointer function(pointer); return 0; } ``` is not possible either.
It isn't allowed for the same reason assigning isn't allowed. To adapt the example from your link: ``` const char c = 'x'; void function(const char **p2) { *p2 = &c; } int main() { char *p1; function(&p1); //********* *p1 = 'X'; } ``` If the marked line was allowed, it would allow you to change the value of the constant variablec.
This question already has answers here:How to initialize all members of an array to the same value?(26 answers)c structure array initializing(5 answers)Closed7 years ago. Lets assume the following in C or C99: ``` typedef struct { int x; double y; } MY_S; MY_S a[666] = {333, 666.6}; ``` Does this initialize the first object of the array only? If yes, is there a way to initialize ALL elements of the array to all the same values using that syntax (without calling a function/loop and without repeating the initializer)?
In standard C, you'd need to repeat the initializer. In GCC, you can specify a range of elements to initialize with the same initializer, for example: ``` MY_S a[666] = { [0 ... 665] = {333, 666.0} }; ```
This question already has answers here:Static variable inside of a function in C(14 answers)Closed7 years ago. WithstaticinCone can keep astackvariable around, even after the creating function exists. In this case however, ``` void static_func() { static int var = 1; var += 1; } ``` I can accessvaroutside of thestatic_func()and return its value. Let's assumestatic_func()is called three times in themain(), then the value ofvaris 3. However, it is set to1every time the function is executed. Why do I still get the value 3?!
Once you saystatic int var = 1;, this variable is createdandinitialized. This can happenonly once, otherwise you're gonna flood your memory with useless duplicates since this variable will stay alive during whole program runtime.
I need to copy one file to windir, So I do: ``` TCHAR windir[MAX_PATH]; GetWindowsDirectory(windir, MAX_PATH); ``` to get the windir. ``` char newLocation[]="text.txt"; // how to add the windir here? BOOL stats=0; CopyFile(filename, newLocation, stats); ``` My problem is, I want to add the windir value before the text.txt in char newLocation[]. Any ideas?
Did you try concatenating the strings, like this? ``` #include <stdlib.h> #include <string.h> char* concat(char *s1, char *s2) { char *result = malloc(strlen(s1)+strlen(s2)+1);//+1 for the zero-terminator //in real code you would check for errors in malloc here strcpy(result, s1); strcat(result, s2); return result; } ``` If that won't work, givewcscat()a shot! Sources: How do I concatenate two strings in C?What is difference between TCHAR and WCHAR?C++ Combine 2 Tchar
As per thisquestion, from c-faq.com, it's not possible to assign achar **to aconst char **without a cast. The explanation given at the link is perfectly reasonable and easy to understand. Indeed, doing it would violate the promise not to modify the pointed data. I, cannot understandWhy is it illegal to pass it to a funcion? I can't see why this ``` void function(const char **pointer) { // Prevent modifying pointer } int main(void) { char **pointer; // Initialize pointer function(pointer); return 0; } ``` is not possible either.
It isn't allowed for the same reason assigning isn't allowed. To adapt the example from your link: ``` const char c = 'x'; void function(const char **p2) { *p2 = &c; } int main() { char *p1; function(&p1); //********* *p1 = 'X'; } ``` If the marked line was allowed, it would allow you to change the value of the constant variablec.
This question already has answers here:How to initialize all members of an array to the same value?(26 answers)c structure array initializing(5 answers)Closed7 years ago. Lets assume the following in C or C99: ``` typedef struct { int x; double y; } MY_S; MY_S a[666] = {333, 666.6}; ``` Does this initialize the first object of the array only? If yes, is there a way to initialize ALL elements of the array to all the same values using that syntax (without calling a function/loop and without repeating the initializer)?
In standard C, you'd need to repeat the initializer. In GCC, you can specify a range of elements to initialize with the same initializer, for example: ``` MY_S a[666] = { [0 ... 665] = {333, 666.0} }; ```
This question already has answers here:Static variable inside of a function in C(14 answers)Closed7 years ago. WithstaticinCone can keep astackvariable around, even after the creating function exists. In this case however, ``` void static_func() { static int var = 1; var += 1; } ``` I can accessvaroutside of thestatic_func()and return its value. Let's assumestatic_func()is called three times in themain(), then the value ofvaris 3. However, it is set to1every time the function is executed. Why do I still get the value 3?!
Once you saystatic int var = 1;, this variable is createdandinitialized. This can happenonly once, otherwise you're gonna flood your memory with useless duplicates since this variable will stay alive during whole program runtime.
I have a C app, and I'm using OpenSSL ver 1.0.2d. I want to know, if it has support at IPv6. I saw some other questions here, but without any answer, and in the official OpenSSL website, the documentation says: Major changes between OpenSSL 1.0.2h and OpenSSL 1.1.0 : - Reworked BIO networking library, with full support for IPv6. So maybe the IPv6 support start only at the 1.1.0 version?
I found that: they say that IPV6 is 80% working on 1.0.2d.v6 tested with testssl.sh.(drwetter commented on 26 Sep 2015 ) From: https://github.com/drwetter/testssl.sh/issues/11 Hope it helps,
This question already has an answer here:Redirect stdout to file without ANSI warnings(1 answer)Closed7 years ago. Can the standard input/output be set to a file for a C programme. I know that we can use fscanf and fprintf to read from and write to a file but by setting the std i/o to a file, can we use just printf/scanf for i/o operations in a C programme?
Is it possible to set the standard input/output to a file in C? Yes, you can do that usingfreopen. Example code from the above site: ``` #include <stdio.h> #include <stdlib.h> int main(void) { puts("stdout is printed to console"); if (freopen("redir.txt", "w", stdout) == NULL) { perror("freopen() failed"); return EXIT_FAILURE; } puts("stdout is redirected to a file"); // this is written to redir.txt fclose(stdout); } ```
I am trying to run the loop in parallel by adding "#pragma omp parallel for",but this did not work any suggestions to how i can parallel this loop? ``` #pragma omp parallel for for (p = split; *p != 0; p++) if (*p == ' ') *p = '0'; ```
For OpenMP to parallelize the loop, the number of loop iterations must be determinable in advance. In this particular case, you'd have to determine the string length first: ``` size_t len = strlen(split); #pragma omp for for ( size_t p = 0 ; p < len; ++p ) if (split[p] == ' ') split[p] = '0'; ``` It's very doubtful that you'll gain any performance benefit from parallelization for this example though.
i've done a function that inverse a String(array of character) given in parameter , but it's not working , any idea why ? I'm getting something like this : æIGt(Kt$0@ thanks you ``` #include <stdio.h> #include <string.h> char * inverse(char *s) { int i, taille = strlen(s); char r[taille]; for (i = 0 ; i < taille ; i++) { r[i] = s[taille - i - 1]; } r[i] = '\0'; return r; } int main() { char s[] = "kira"; char *r = inverse(s); printf("%s",r); return 1; } ```
You are returning a pointer to a local variable. That variable gets destroied when the function inverse returns, so accessing the pointer after the function exits will return invalid data.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question I have to write a n numbers of bytes in a binary file in C, how can I write it? All the bytes has to be 0. I am writting a char, but I dont know if this is the correct way. ``` int i; for(i=0; i < 200; i++){ fwrite(0, sizeof(char), 1, file); } ```
The first argument offwritemust be a valid pointer. You can usefputcto write an immediate character (byte) into a file like this: ``` int i; for(i=0; i < 200; i++){ fputc(0, file); } ```
I want to be create a struct, but I also want to write its array or string elements with dynamic memory allocation. ``` struct st { char *name[40]; int age; }; ``` For "name" string should I use malloc before struct, or can I use it in struct also. 1) ``` char *name = malloc(sizeof(char)*40); struct st { char *name; int age; }; ``` 2) ``` struct st { char *name = malloc(sizeof(char)*40); int age; }; ``` Are both of them true or is there any mistake? And if both of them are true, which one is more useful for other parts of code?
You need to create aninstanceof the structure, an actual variable of it. Then you need to initialize the members of the structure instance in a function. For example, in some function you could do ``` struct st instance; instance.name = malloc(...); // Or use strdup if you have a string ready instance.age = ...; ```
I found this as a proposition of the eclipse idexer/intelisence whatever the call it. And this is it: ``` char *_EXFUN(index,(const char *, int)); ``` First it looks like a function returning a pointer for a char, but the parameters (if it is a function at all) looks to me quite confusing. How come into the parameter list we have a brackets.
_EXFUNappears to be a macro used in standard headers on some platforms, e.g.here ``` #ifndef _EXFUN # define _EXFUN(N,P) N P #endif ``` Thus,char *_EXFUN(index,(const char *, int));expands to ``` char * index(const char *, int) ``` This trick is sometimes done so that the same header can be preprocessed with_EXFUNset to something else, e.g. to introspect function signatures, or to declare exported symbols in a library.
i am using c# to call a c code through a DLL , i got AccessViolationException when calling a method , here is the code from the source header ``` extern __declspec( dllexport ) int ReadCardSN( IN OUT unsigned char* CardSN ); ``` in my c# code i am using ``` public static byte[] Data = new byte[4]; [DllImport("CardLib.dll")] public static extern Int32 ReadCardSN(byte[] Data); int resCode = ReadCardSN(Data); ``` what can be the problem ?
The error is because your buffer is too small. The example code shows the use of a buffer of length 10240. You supply a buffer of length 4. As written it looks like the C code uses the default cdecl calling convention. Your C# code uses stdcall. It would also be better to apply the[In, Out]attribute to the argument. Becausebyte[]is blittable that is not strictly necessary but it is semantically accurate.
How can i check by a preprocessor directive if the typeunsigned long longis available in the current build environment? I tried checking ``` #if __STDC_VERSION__ >= 199901L /* Available */ #else /* Not available */ #endif ``` but compiling with gcc and at least without-std=-compiler argument this leads to "Not avaibalble" (but would work). Is there a better macro to check so that at least it works with C99 standard compilers and with GCC without-std=C99?
Although it is not the most elegant of solutions, my first instinct would be to check for the existence of theULLONG_MAXsymbol in thelimits.hheader. If it is defined, then theunsigned long long inttype is almost certainly available. If it is not defined, then the type is probably not available—or at least, it is not well-supported and may only be available as a non-portable compiler extension.
The break and error indication glows up in real terms while communicating with RS-232. Sometimes, the CTS is also will be glowing. Due to this, the data in prints as junk for some time; later it gets corrected after a few reset of real term. This is ascreenshotshowing the error: What does BREAK mean really? What happens when there's a break?
A break condition occurs whenthe transmitter is holding the data line at logical 0 for too long, i.e. longer than the time needed for transmitting a start bit and the (usually 8) data bits. Possible causes: The transmitter can send a breakdeliberately, as an out-of band signal, e.g. to signal the beginning of a data packet, like in theLINprotocol. It can occur when thetransmitter is sending at a lower speedas the receiver is expecting. Perhaps its clock is not properly initialized. Of course it can be caused by a noisy or otherwisebad connection.
I am trying to generate mutants for a code (with an AST based mutant generator) which in order to compile uses -D macros. I am able to use clang to generate an AST dump using this command clang -Xclang -ast-dump -fsyntax-only -DFLAG=0 -DOTHER_FLAG file.c But, the mutant generator tool (Milu) uses libclang to parse the c code and generate the AST. Without these macros, libclang is not able to parse the code properly, and it's not possible to add the #defines in the code. I want to set these -D macros globally. For example, I can set an environment variable C_INCLUDE_PATH which is read by libclang. I am wondering if I can do something similar for -D macros.
Just pass them when creating yourCXTranslationUnit. Therelevant functionclang_createTranslationUnittakes arguments similar toargvandargc.
This question already has answers here:Using memset for integer array in C(10 answers)Closed7 years ago. I need to set all values of an array equal to one. I have been trying to do this using the following code: ``` int bulbSwitch(int n) { int bulbs[n]; memset(bulbs, 1, n * sizeof(int)); ... ``` However, the debugger shows that all values within the array are actually being set to 16843009. Withoutmemset, the array values are seemingly random, positive integers. Why is this, and how would I fix it?
memsetsets eachbyteof memory to the value you have specified. Aninton your platform is clearly 4 bytes. So you are setting each byte of theintto be 1. That is, for eachint, the code effectively does: ``` bulbs[i] = 0x01010101; ``` That value in decimal is exactly16843009. It means you should not usememsetbut a simple loop instead to set each element of the array.
I have a static array ofNSStringdefined in my implementation file like so: ``` NSString * const knames[] = { @"", @"", @"", ..., @"" }; ``` and what I'd like to do is get the lengthdynamically. Since this is a C array,lengthandcountare not valid, so I've tried usingsizeof: ``` int count = (sizeof knames) / (sizeof knames[0]); ``` However, it results in the error message: Invalid application of 'sizeof' to an incomplete type 'NSString *const _strong[]'
Small typo;sizeofrequires brackets: ``` /*const?*/ int count = sizeof(knames) / sizeof(knames[0]); ``` You could create a macro somewhere globally: ``` #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0])) ... const int count = ARRAY_SIZE(knames); ```
``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char* str="abcdef"; char* str1 = malloc(strlen(str)+1); strcat(str1,str[1]); printf("String = %s\n", str1); return(0); } ``` So i get the "Segmentation fault" when i want to to concatenate a letter from str to str1strcat(str1,str[1])
Try it this way if you want to append the second character ofstrtostr1: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *str="abcdef"; char *str1 = malloc(strlen(str)+1); // malloc just allocates the memory strcpy(str1, str); // you need to copy str to str1 printf("String = %s\n", str1); char str2[] = { str[1], '\0' }; strcat(str1, str2); // strcat takes two null terminated strings as arguments printf("String = %s\n", str1); return(0); } ```
I am programming C on a arm cortex cpu with gcc-arm-none-eabi. I know it is 4-byte alignment by test and google. But is there any macro or variable which defines how many bytes alignment it is? I need know in case someday this program may be port for another cpu.
A trick to find the alignment of a particular data type is to pack it in a struct with a char: ``` #define LONG_ALIGNMENT (sizeof (struct {char a, long b}) - sizeof (long)) #define INT_ALIGNMENT (sizeof (struct {char a, int b}) - sizeof (int)) ```
This is a tic-tac-toe game. The problem is if the last row is filled, the game prints "Draw" and ends, This is supposed to happen only if all the cells are filled. What's my fault?! http://pastebin.com/RZZn5wWe
The break statement terminates the execution of the nearest enclosingdo,for,switch, orwhilestatement in which it appears. Control passes to the statement that follows the terminated statement. When you set your empty_cell variable you use a break in a nested loop. Doing this you exit only from the first loop and continue in the second. this is causing your issue. Set your flag out of the loop and change it only if needed.
The break and error indication glows up in real terms while communicating with RS-232. Sometimes, the CTS is also will be glowing. Due to this, the data in prints as junk for some time; later it gets corrected after a few reset of real term. This is ascreenshotshowing the error: What does BREAK mean really? What happens when there's a break?
A break condition occurs whenthe transmitter is holding the data line at logical 0 for too long, i.e. longer than the time needed for transmitting a start bit and the (usually 8) data bits. Possible causes: The transmitter can send a breakdeliberately, as an out-of band signal, e.g. to signal the beginning of a data packet, like in theLINprotocol. It can occur when thetransmitter is sending at a lower speedas the receiver is expecting. Perhaps its clock is not properly initialized. Of course it can be caused by a noisy or otherwisebad connection.
I am trying to generate mutants for a code (with an AST based mutant generator) which in order to compile uses -D macros. I am able to use clang to generate an AST dump using this command clang -Xclang -ast-dump -fsyntax-only -DFLAG=0 -DOTHER_FLAG file.c But, the mutant generator tool (Milu) uses libclang to parse the c code and generate the AST. Without these macros, libclang is not able to parse the code properly, and it's not possible to add the #defines in the code. I want to set these -D macros globally. For example, I can set an environment variable C_INCLUDE_PATH which is read by libclang. I am wondering if I can do something similar for -D macros.
Just pass them when creating yourCXTranslationUnit. Therelevant functionclang_createTranslationUnittakes arguments similar toargvandargc.
This question already has answers here:Using memset for integer array in C(10 answers)Closed7 years ago. I need to set all values of an array equal to one. I have been trying to do this using the following code: ``` int bulbSwitch(int n) { int bulbs[n]; memset(bulbs, 1, n * sizeof(int)); ... ``` However, the debugger shows that all values within the array are actually being set to 16843009. Withoutmemset, the array values are seemingly random, positive integers. Why is this, and how would I fix it?
memsetsets eachbyteof memory to the value you have specified. Aninton your platform is clearly 4 bytes. So you are setting each byte of theintto be 1. That is, for eachint, the code effectively does: ``` bulbs[i] = 0x01010101; ``` That value in decimal is exactly16843009. It means you should not usememsetbut a simple loop instead to set each element of the array.
I have a static array ofNSStringdefined in my implementation file like so: ``` NSString * const knames[] = { @"", @"", @"", ..., @"" }; ``` and what I'd like to do is get the lengthdynamically. Since this is a C array,lengthandcountare not valid, so I've tried usingsizeof: ``` int count = (sizeof knames) / (sizeof knames[0]); ``` However, it results in the error message: Invalid application of 'sizeof' to an incomplete type 'NSString *const _strong[]'
Small typo;sizeofrequires brackets: ``` /*const?*/ int count = sizeof(knames) / sizeof(knames[0]); ``` You could create a macro somewhere globally: ``` #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0])) ... const int count = ARRAY_SIZE(knames); ```
``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char* str="abcdef"; char* str1 = malloc(strlen(str)+1); strcat(str1,str[1]); printf("String = %s\n", str1); return(0); } ``` So i get the "Segmentation fault" when i want to to concatenate a letter from str to str1strcat(str1,str[1])
Try it this way if you want to append the second character ofstrtostr1: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *str="abcdef"; char *str1 = malloc(strlen(str)+1); // malloc just allocates the memory strcpy(str1, str); // you need to copy str to str1 printf("String = %s\n", str1); char str2[] = { str[1], '\0' }; strcat(str1, str2); // strcat takes two null terminated strings as arguments printf("String = %s\n", str1); return(0); } ```
why is the output of the below code the case? ``` char str[] = {'i', 't', 'i', 's', 'm', 'e', '\0'}; //this code equates to 7 bytes char* str[] = {'i', 't', 'i', 's', 'm', 'e', '\0'}; //this code equates to 28 bytes ```
This code does not do what you think. It usescharconstants to initialize elements of achar*array of pointers. Such "pointers" do notpointto your characters; instead, they have numeric values of their corresponding characters! Each character pointer on your system is 4-bytes long, which explains the result.
I was wondering what the abbreviation "MSP" inHAL_xxx_MspInit()callbacks stands for. I have seen that in some firmware drivers like the HAL library from ST. For example: ``` void HAL_UART_MspInit(UART_HandleTypeDef *huart); void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi); ``` fromstm32f3xx_hal_uart.handstm32f3xx_hal_spi.h. I am wondering whatMsprefers to. Is it just a naming convention for callbacks frominitfunctions in drivers or does it have a deeper meaning (what I suspect it has).
In STM32CubeMX it stands forMCUSupportPackage. The STM32CubeMX documentation"STM32CubeMX for STM32 configuration and initialization C code generation"(UM1718) is clear on this - section 5.1: It does however somewhat unhelpfully use the term several times in the documentation before it actually defines it! Other aspects of the STM32CubeMX naming conventions are also defined in this document.
I would like to modify the screen that I see with a compute shader without invoking vertex/fragment shader. The compute shader will use data, and I would like to know how to invoke this data from within the compute shader. So how shall I do it ?
Compute shaders can only access images or buffers. Thedefault framebufferis neither; it is a special object, and you cannot attach its images to anything. You can however create a texture, bind it foruse as an imageby a compute shader, and do whatever computations you wish on it. You can then (afterthe appropriateglMemoryBarriercall, of course) render that image to the default framebuffer.
why is the output of the below code the case? ``` char str[] = {'i', 't', 'i', 's', 'm', 'e', '\0'}; //this code equates to 7 bytes char* str[] = {'i', 't', 'i', 's', 'm', 'e', '\0'}; //this code equates to 28 bytes ```
This code does not do what you think. It usescharconstants to initialize elements of achar*array of pointers. Such "pointers" do notpointto your characters; instead, they have numeric values of their corresponding characters! Each character pointer on your system is 4-bytes long, which explains the result.
I was wondering what the abbreviation "MSP" inHAL_xxx_MspInit()callbacks stands for. I have seen that in some firmware drivers like the HAL library from ST. For example: ``` void HAL_UART_MspInit(UART_HandleTypeDef *huart); void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi); ``` fromstm32f3xx_hal_uart.handstm32f3xx_hal_spi.h. I am wondering whatMsprefers to. Is it just a naming convention for callbacks frominitfunctions in drivers or does it have a deeper meaning (what I suspect it has).
In STM32CubeMX it stands forMCUSupportPackage. The STM32CubeMX documentation"STM32CubeMX for STM32 configuration and initialization C code generation"(UM1718) is clear on this - section 5.1: It does however somewhat unhelpfully use the term several times in the documentation before it actually defines it! Other aspects of the STM32CubeMX naming conventions are also defined in this document.
I would like to modify the screen that I see with a compute shader without invoking vertex/fragment shader. The compute shader will use data, and I would like to know how to invoke this data from within the compute shader. So how shall I do it ?
Compute shaders can only access images or buffers. Thedefault framebufferis neither; it is a special object, and you cannot attach its images to anything. You can however create a texture, bind it foruse as an imageby a compute shader, and do whatever computations you wish on it. You can then (afterthe appropriateglMemoryBarriercall, of course) render that image to the default framebuffer.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question Is there any way by which we can get the answer for 1/2 as 0.5 where the data type of both the numerator and denominator are int in C.
If you expect a decimal value(which may not be the exact one), you'll have to cast it to a floating point type. For example: ``` int numerator = 1, denominator = 2; printf("%g", (double) numerator / denominator); ``` Or, if exact values are called for, return a struct: ``` struct fraction { int numerator; int denominator; }; ``` and then ``` return (struct fraction){.numerator = 1, .denominator = 2}; ```
I am working on an pure c project for school. ``` char** init_matrix ( ) { printf ( "%s\n", __PRETTY_FUNCTION__ ); char** temp_matrix; temp_matrix = ( char ** ) malloc ( CHAR_BIT * sizeof (char* ) ); for ( int i = 0; i < CHAR_BIT; i ++ ) { *( temp_matrix + i ) = ( char * ) calloc ( CHAR_BIT, sizeof (char ) ); } return temp_matrix; } ``` somewhere in main i have a call, ``` char ** mat = init_matrix ( ); ``` Is free cascading to all pointers pointed ``` free(mat); ``` or should i do a for loop again for every pointer defined?
Is free cascading to all pointers pointed No. should i do a for loop again for every pointer defined? Yes. The general rule is: 1 call tofree()per 1 call tomalloc()or its friends (calloc(),realloc(),strdup()). Where a call torealloc()on an already re/allocated piece of memory does not count.
I'm parsing a line to extract a string from inside a set of parens but in instances where there are multiple nested parens I don't get anything when I print procName. e.g. 109765 ((test)) blah blah ``` sscanf(line,"%*d (%[^'('')']", procName); ``` This format is supposed to find a left-paren then return the string while ignoring any number of left and right parens, but it doesn't work in this particular case. However if there is just one set of parens it works flawlessly. Any idea what I could be missing here? Thanks in Advance!
OP's"("matches exactly 1'('.Use"%*[(]"to scan 1 or more'('. Better to limit string input.Breaking up format input pieces is easier to see.Check return value. ``` char procName[100]; int cnt = sscanf(line,"%*d" " %*[(]" "%99[^()']", procName); if (cnt == 1) OK(); ```
This question already has answers here:Pointer arithmetic for void pointer in C(10 answers)Closed7 years ago. I have to write a function, in C on Linux, to read or write generic data. I can read (or write) big data so i made a while using how many bytes I read. At the next call i, for example, read in the original pointer + how many bytes I read. But I don't know the type so I used a void * but gcc says: ``` membox.c: In function ‘myRW’: membox.c:301:22: warning: pointer of type ‘void *’ used in arithmetic [-Wpointer-arith] w = read(fd, data + (s*type) , len - s); ^ membox.c:308:23: warning: pointer of type ‘void *’ used in arithmetic [-Wpointer-arith] w = write(fd, data + (s*type) , len - s); ``` Can i do this? I should ignore this warnings?
Cast thevoid *tochar *. That way, you have an underlying type of size 1 to do pointer arithmetic on. ``` (char*)data + (s*type) ```
In an SDL2 project,SDL_PollEvents( SDL_Event* e )doesn't send any events, and allways returns0, so I can't process any events. My event processing loop looks fine : ``` SDL_Event e; while( SDL_PollEvent( &e ) > 0 ) { //this is never reached ! printf( "recieved event %d\n", e.type ); switch(e.type) { case SDL_QUIT: quit = true; } } ``` On the other hand, it compiles fine, drawing works, and I'm sure it's not stuck in an infinite loop ( I made it print out a message at each frame ). I link againstSDL2and all other dependencies, I even makegcc/g++callsdl-config --cflags. How can this be fixed ?
You shouldn't callsdl-config --cflags. This is forSDL( the first version of the library ), notSDL2. It somehow conflicts and stops all events from reachingSDL_PollEvents(). Remove it and it should work !
How do I calculate the frequency count of each statement (i.e. the number of time each statement gets read/executed) in the following C code.The frequency count of each statement must be written in terms of 'n'. ``` for(i=1;i<=n;i++) for(j=1;j<=i;j++) for(k=1;k<=j;k++) x=x+1; ```
See this way, at maximum , ``` for(i=1;i<=n;i++) // Executes n times for(j=1;j<=i;j++) // Executes i times for every i -> (1 + 2 + 3 + 4....n) for(k=1;k<=j;k++) // Executes j times for every i,j ---> (1+(1+2)+(1+2+3).....(1+2+3...n)) x=x+1; // Executes every time for every i,j,k ---> (1+(1+2)+.....(1+2+3...n) So, you can figure out from this that : ``` n + n*(n+1)/2 + (n+(n-1)2+(n-2)3.....(1)n)*2 ...=n + n(n+1)/2+ ((n)(n+1)(n+2)/6)*2.. This is your answer.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question Before I start please keep in mind that I am still learning and need help with some stuff that may be easy to you but not to me. So here we go. I am having trouble using scanf in a custom function. It will not let me type anything. It just keeps running forever unless I stop it. How can I get scanf to work here: ``` #include <stdio.h> #include <stdlib.h> void function (); int main (void) { char sel; function (); return 0; } void function () { scanf("%c",&sel); } ```
There is no problem with scanf. The problem is with your loop.l = 1andl++will always keepl >= 0and hence it will keep on taking input infinite times. Also, it will keep on overriding the value ofvar.awith every input
I'm parsing a line to extract a string from inside a set of parens but in instances where there are multiple nested parens I don't get anything when I print procName. e.g. 109765 ((test)) blah blah ``` sscanf(line,"%*d (%[^'('')']", procName); ``` This format is supposed to find a left-paren then return the string while ignoring any number of left and right parens, but it doesn't work in this particular case. However if there is just one set of parens it works flawlessly. Any idea what I could be missing here? Thanks in Advance!
OP's"("matches exactly 1'('.Use"%*[(]"to scan 1 or more'('. Better to limit string input.Breaking up format input pieces is easier to see.Check return value. ``` char procName[100]; int cnt = sscanf(line,"%*d" " %*[(]" "%99[^()']", procName); if (cnt == 1) OK(); ```
This question already has answers here:Pointer arithmetic for void pointer in C(10 answers)Closed7 years ago. I have to write a function, in C on Linux, to read or write generic data. I can read (or write) big data so i made a while using how many bytes I read. At the next call i, for example, read in the original pointer + how many bytes I read. But I don't know the type so I used a void * but gcc says: ``` membox.c: In function ‘myRW’: membox.c:301:22: warning: pointer of type ‘void *’ used in arithmetic [-Wpointer-arith] w = read(fd, data + (s*type) , len - s); ^ membox.c:308:23: warning: pointer of type ‘void *’ used in arithmetic [-Wpointer-arith] w = write(fd, data + (s*type) , len - s); ``` Can i do this? I should ignore this warnings?
Cast thevoid *tochar *. That way, you have an underlying type of size 1 to do pointer arithmetic on. ``` (char*)data + (s*type) ```
For some code I'm writing, I have a function pointer. I use it for some time, but I don't know whether I need to explicitly deallocate the pointer. Here is a simplified version of my code ``` struct Person { void (*action) (); } void action() { printf("Action has been called\n"); } int main() { Person p; p->action = &action; // My question is whether or not I need to do this // free (p->action); // p->action = NULL; } ``` Thank you.
I have a function pointer. I use it for some time, but I don't know whether I need to explicitly deallocate the pointer. No.You don't need to deallocate anything usingfree(), you never had dynamically allocated withmalloc()or alike. In fact it would be practically impossible to create a function pointer usingmalloc().
I am trying to compile libssh2 under Windows with Visual Studio nmake. I am producing a shared library (DLL) but not producing a static library (LIB). I've gone through hours of reading their documentation but have found no mention of generating the static library. Normally, I'd assume it would be generated alongside the DLL but that is not the case. Command line looks like so: ``` nmake /f NMakefile ```
Figured it out. You have to create the build environment withCMake. Add your CMake bin directory to the environment PATH variable. With command prompt inside root libssh2: ``` mkdir build cd build cmake -G "Visual Studio 14 2015 Win64" .. cmake --build . ``` This will create aMDdstatic debug library. For a regularMDstatic release library, run: ``` cmake --build . --config Release ```
From the documentation at [1], an example output for thegdb xcommand in c format is as follows: ``` (gdb) x/c testArray 0xbfffef7b: 48 '0' (gdb) x/5c testArray 0xbfffef7b: 48 '0' 49 '1' 50 '2' 51 '3' 52 '4' ``` What does these numbers, such as48, 49, 50in the output mean? Is it some kind of relative address? Thank you very much! [1]http://visualgdb.com/gdbreference/commands/x
xis displaying the memory contents at a given address using the given format. In your specific case,x/5cis displaying the first 5 bytes at the memory locationtestArray, and printing the bytes as achar. The first 5 bytes oftestArrayare the characters0,1,2,3,4(the value in single quotes). The value before is the decimal value of the char.
When writing theStorableinstance of a C enum that has 5 options (using c2hs), the{# sizeof #}macro returns 4 (i.e. 4 bytes). Isn't this extremely wasteful, when 3 bits would suffice? Does this depend on the size of a memory word?
The size of enum is implementation-defined. The standard says: 6.7.2.2 Enumeration specifiers...Each enumerated type shall be compatible withchar, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined ... BTW, in C++ one could specify the underlying type explicitly, e.g.: ``` enum E : int { // ... }; ```
Everybody knows how to declare an array with constant elements: ``` const int a[10]; ``` Apparently, it is also possible to declare an array that isitselfconstant, via atypedef: ``` typedef int X[10]; const X b; ``` From a technical and a practical standpoint, doaandbhave the same type or different types?
Apparently, it is also possible to declare an array that is itself constant Nope. In N1256, §6.7.3/8: If the specification of an array type includes any type qualifiers, the element type is so-qualified, not the array type.118) Then footnote 118 says: Both of these can occur through the use oftypedefs.
Many framework require that your nvidia graphic card has a specific compute capability version. I am developing a C++ application that uses Cuda. I should get this information by code. so that I can assign the needed framework for each graphic compute capability. How to know the compute capability of my nvidia graphic in C/C++?
From theCUDA Runtime API ``` __host__ ​cudaError_t cudaGetDeviceProperties ( cudaDeviceProp* prop, int device ) Returns information about the compute-device. ``` Alternatively, you could usecudaDeviceGetAttributeto get the specific properties you want. precisely: Returns in *prop the properties of device dev. The cudaDeviceProp structure is defined as: ``` ‎ struct cudaDeviceProp { .... int major; int minor; ..... } ``` major, minor are the major and minor revision numbers defining the device's compute capability.
This question already has answers here:Creating C macro with ## and __LINE__ (token concatenation with positioning macro)(3 answers)Closed7 years ago. I would like to have a macro that produce something likeL17, where17is the line number when the macro is invoked. However the following only produceL__LINE__ ``` #define STOP L##__LINE__ ``` Wonder if there is a way to make the__LINE__evaluate before concatenation.
You need a double concat macro wrapper: ``` #define CONCAT0(x,y) x ## y #define CONCAT(x,y) CONCAT0(x,y) #define STOP CONCAT(L,__LINE__) int main() { int STOP = 42; L5 = 41; } ```
I am working with a C project using visual studio. I tried to compile the following code: ``` void shuffle(void *arr, size_t n, size_t size) { .... memcpy(arr+(i*size), swp, size); .... } ``` I get the following error with Visual studio Compiler: ``` error C2036: 'void *' : unknown size ``` The code compile well with GCC. How to solve this error?
You can't perform pointer arithmetic on avoid *becausevoiddoesn't have a defined size. Cast the pointer tochar *and it will work as expected. ``` memcpy((char *)arr+(i*size), swp, size); ```
I am building a C application that uses OpenCV. when compiling, I get the following error: ``` fatal error C1189: #error : core.hpp header must be compiled as C++ ``` I did not find how to resolve this error. How to use OpenCV from a C project?
Select the required file.Launch its properties windowGoto C/C++ -> Advanced, and changeCompile astoCompile as C++ Code (/TP)
``` int arrays[100]; fseek(fp, 30, SEEK_SET); fread(arrays, sizeof(int), 20, fp); printf("%i\n", arrays); int size = (sizeof(arrays)/ sizeof(int)); printf("There are %i numbers.", size); //Output: //6421876 //There are 100 numbers ``` Clearly the array has 7 numbers in it, so why is it saying 100?
No, the array has 100 elements. You may have only written to some of them (20, assuming yourfreadworked okay) but that doesn't change the array size. It's no different to pouring 250ml into a 1L jug. Thesizeof the jug doesn't magically reduce by 75% just because it isn't full. In any case, what you see as seven numbers (actuallyonenumber with seven digits) is nothing to do with what was written to the array. The expressionarraywill, under most circumstances, decay to the address of the first element of that array. So the number you see is where the array islocated,not what it holds.
I have a Python package that includes C code compiled into.so. In my Python code, I have docstrings. In my C code, I also have docstrings. Willsphinxbe also sensitive to the docstrings given in the C source code, so that I can generate documentation automatically?
Yes, assuming you mean docstrings that are available to the python interpreter as part of a compiled module. For example: ``` static PyMethodDef methods[] = { ... {"convolve", Pconvolve, METH_VARARGS, "convolve(xi,yi,x,dx,y): compute convolution of width dx[k] at points x[k],\nreturned in y[k]" }, ... {0} } ; ``` . The usualautodocmagic will pick them up. If you mean docstrings in C comments beside C functions like in doxygen, then no. You will have to write your own code to extract them and convert them to rst files.
I want to access strings from an array, just like one can access integers from arrays, sayA={1,2,3}then upon callingA[0]one would get1. Similarly what should be done for strings such thatA={a,b,c}so upon callingA[0]I geta. I tried this for the input, ``` char in[1000]; for (i=0;i<5;i++) { in[i]="A"; printf("in is %f",in[i]); } ``` but I am getting a warningassignment makes integer from pointer without a cast
Since you are making a character array, you need to supply a character value to it. Change your code to ``` in[i]='A' printf("in is %c",in[i]); ``` Hope this helps :)
I need to create a function in which there is a default argument: ``` void func ( int a, int b = 1 ); // and func (1, 2); func (1); ```
C doesn't support default arguments, though you can sometimes hack something like them using the preprocessor: ``` void func(int a, int b); #define TWO_ARGS(A, B, ...) A, B #define func(...) func(TWO_ARGS(__VA_ARGS__, 1)) func(1, 2); /* calls func(1, 2); */ func(1); /* calls func(1, 1); */ ```
I am trying to make a custom string class. Stuck on the a problem where I need to compare by struct to a constant string Example ``` typedef struct{ char *val; } STRING; int func (STRING* compare){ if ( compare == "a string" ){ return 1; return 0; } ```
You need to use strcmp. To keep with returning 1 if equal: ``` int func (STRING* compare){ if ( strcmp(compare, "a string" ) == 0) return 1; return 0; } ```
I have a Python package that includes C code compiled into.so. In my Python code, I have docstrings. In my C code, I also have docstrings. Willsphinxbe also sensitive to the docstrings given in the C source code, so that I can generate documentation automatically?
Yes, assuming you mean docstrings that are available to the python interpreter as part of a compiled module. For example: ``` static PyMethodDef methods[] = { ... {"convolve", Pconvolve, METH_VARARGS, "convolve(xi,yi,x,dx,y): compute convolution of width dx[k] at points x[k],\nreturned in y[k]" }, ... {0} } ; ``` . The usualautodocmagic will pick them up. If you mean docstrings in C comments beside C functions like in doxygen, then no. You will have to write your own code to extract them and convert them to rst files.
I want to access strings from an array, just like one can access integers from arrays, sayA={1,2,3}then upon callingA[0]one would get1. Similarly what should be done for strings such thatA={a,b,c}so upon callingA[0]I geta. I tried this for the input, ``` char in[1000]; for (i=0;i<5;i++) { in[i]="A"; printf("in is %f",in[i]); } ``` but I am getting a warningassignment makes integer from pointer without a cast
Since you are making a character array, you need to supply a character value to it. Change your code to ``` in[i]='A' printf("in is %c",in[i]); ``` Hope this helps :)
I need to create a function in which there is a default argument: ``` void func ( int a, int b = 1 ); // and func (1, 2); func (1); ```
C doesn't support default arguments, though you can sometimes hack something like them using the preprocessor: ``` void func(int a, int b); #define TWO_ARGS(A, B, ...) A, B #define func(...) func(TWO_ARGS(__VA_ARGS__, 1)) func(1, 2); /* calls func(1, 2); */ func(1); /* calls func(1, 1); */ ```
I am trying to make a custom string class. Stuck on the a problem where I need to compare by struct to a constant string Example ``` typedef struct{ char *val; } STRING; int func (STRING* compare){ if ( compare == "a string" ){ return 1; return 0; } ```
You need to use strcmp. To keep with returning 1 if equal: ``` int func (STRING* compare){ if ( strcmp(compare, "a string" ) == 0) return 1; return 0; } ```
I am "reviewing" some code that was written well before me and I'm noticing a pattern that I have some doubts about: The result of thePsGetCurrentProcess()function is stored and then comparisons are made with that pointer (which is a pointer to anEPROCESSstruct). However, I'm not finding anything in the documentation, which suggests this function is guaranteed to return the same pointer each time. What is much more surprising to me is that this code has been apparently working for a long time. Is this a bug, and would you recommend changing that logic to e.g. comparing Process IDs (Using PsGetProcessId)?
Yes, this is pretty much correct. The documentation ofEPROCESSmakes it clear that there is one such object per process, and anyPEPROCESSpoints to this. This meansPsGetCurrentProcess()does't return a pointer toanEPROCESSbut totheEPROCESS. And two pointers compare equal if they point to the same object.
I am working with ANSI C for the first time and I need to sum a series out to an N number of terms. My background is in physics, not CS, so I instinctively thought to use the old (-1)^N trick, but quickly realized that 1) it didn't work, and 2) ANSI C doesn't have a built in exponentiation operator. Since I now realize that exponentiation is slow, what is the best way to create an alternating series in for this? My second thought was checking the parity of N and then using an if statement that gives me either a 1 or -1 to multiply the term by, but I don't know any good methods to check parity on a computer, and I think it would be even slower than exponentiating -1. Are there better ways to accomplish this that won't heavily tax the CPU?
Just keep the sign as a separate variable, and negate it as you process each term: ``` int sign = 1; for ( int i = 0; i < N; i++ ) { printf( "%2d\n", sign ); sign = -sign; } ```