Newest questions tagged c - Stack Overflow most recent 30 from 2019-11-19T20:37:18Z /feeds/tag?tagnames=c&sort=newest /q/58942391 0 How to access array outside function of uncertain length? educationalmonkey97 /users/12055682 2019-11-19T20:34:19Z 2019-11-19T20:34:19Z <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; int s = user input; //assume the user typed in a value and I stored the value in s; int main() { int array[s]; My_Function ( 3 ); } int My_Function (int tag) { array[0] = tag; } </code></pre> <p>I would like to be able to change specific elements of array[0] from my function, but I cannot because array[s] is declared in main. I can't declare array[s] in My_Function because in my real programming assignment, I am now allowed. How can I change array[0] from my_function and any future changes change array[s]?</p> /q/58942374 0 The output of identical code is different between gcc in Ubuntu and an online compiler, why? sgtShaftoe /users/12399946 2019-11-19T20:32:54Z 2019-11-19T20:32:54Z <p>When I compile and run this code with gcc in Ubuntu terminal I am getting the incorrect output. Have used sublime text, text editor and VS Code to attempt, all failed. When I use an online compiler to run the same exact code, the output is correct. This is a simple program to calculate the sum of integers between 100-200 inclusive. I know that the output should be 15150 but gcc is giving me 37085. I am certain the code is correct but I'd like some input from any Linux gurus who may be able to explain this phenomena as I am new to both programming and Linux. I will first post my code and then the two different outputs. This is C standard, although you probably knew that. Thanks in advance for the helping hands.</p> <p><strong>code snippet:</strong></p> <pre><code>int forLoop() { int i, n; printf("Sum of all numbers between 100 and 200:\n"); for(i = 100; i &lt;= 200; ++i) { n += i; } printf("%d\n\n",n); return n; } </code></pre> <p><strong>gcc output:</strong></p> <p>alex@Metatron:~/Documents/cprogramming/programs$ ./assignment6 Sum of all numbers between 100 and 200: 37085</p> <p><strong>Online compiler output:</strong></p> <p>Sum of all numbers between 100 and 200:<br> 15150 </p> /q/58941889 -1 Incorrect Matrix scanned from txt file Amanda Shi /users/12399863 2019-11-19T19:54:05Z 2019-11-19T20:13:13Z <p>I scan a matrix from a txt file, and print out the scanned value. As shown in the first for loop, the matrix printed is correct. However, the matrix printed in the second for loop is incorrect in the second for loop. I even do not modify the for loop.</p> <pre><code>int a,b; for(a = 0; a &lt; N; a++) { for(b = 0; b &lt; N; b++) { if(!fscanf(fp, "%d", &amp;adj[a][b])) break; printf("%d", adj[a][b]); } printf("\n"); } fclose(fp); printf("\n"); for(a = 0; a &lt; N; a++) { for(b = 0; b &lt; N; b++) { printf("%d", adj[a][b]); } printf("\n"); } </code></pre> <p>what it prints:</p> <pre><code>09999 90123 91032 92308 93280 93280 93280 93280 93280 93280 </code></pre> /q/58941872 -1 C For loop output error (control may reach end of non-void function) Dragos Toader /users/10653449 2019-11-19T19:52:50Z 2019-11-19T20:07:03Z <p>I have the following code in Python and I want to translate it in C:</p> <pre><code>n=input('input a number between 1 and 8') for i in range(0,n): print (i*'#') </code></pre> <p>My for loop does nothing. Why? So far I have:</p> <pre><code>#include &lt;cs50.h&gt; #include &lt;stdio.h&gt; int get_positive_int(string prompt); char func(int n); int main(void) { int i = get_positive_int("Positive integer between 1 and 8: "); printf("%i\n", i); } int get_positive_int(string prompt) { int n; do { n = get_int("%s", prompt); } while (n&gt;8 || n&lt;1); printf("Stored: "); return n; } char func(int n) { for (int j=0;j&lt;n;j++) { for (int k=0;k&lt;n;k++) { return printf("#"); } printf("\n"); } } </code></pre> /q/58941639 -3 How to draw a square in C with different symbols and diagonals? BenTyler /users/3795296 2019-11-19T19:35:40Z 2019-11-19T19:57:51Z <p>Guys i'm pretty stuck here. I'm trying to learn c and create some very basic code which asks the user to insert a number. Then, this number enters the following formula : 2x+1, then I want it to print a hollow square pattern with a different symbol for rows and columns, and add a + in the corners, diagonals, and a "X" in the middle.</p> <p>I'm stuck in the very very beginning of the code. I don't know where should I even start. I mean I can't even learn how to make different symbols for the rows and columns.</p> <p>I'm trying to learn and study it for 3 hours already, watched 20 different YouTube videos and read 20 different coding guides. It's so frustrating..</p> <p>Thanks.</p> <p>I'm attaching a picture of my code &amp; my output, and the desired output on the right.<a href="" rel="nofollow noreferrer"><img src="" alt="enter image description here"></a></p> <p>the code itself:</p> <pre><code>int size; printf("Please enter a number that will define the size of the square: \n"); scanf("%d", &amp;size); size = 2 * size + 1; for (int i = 1; i &lt;= size-2; i++) { for (int j = 1; j &lt;= size-2; j++) { if (j == 1 || j == size - 1) { printf("|"); } else { printf(" "); } if (i==1 || i==size-2){ printf("-"); } else { printf(" "); } } printf("\n"); } </code></pre> /q/58941608 -2 The use 2d string arrays in structure in files [on hold] ajay kumar /users/12399758 2019-11-19T19:33:36Z 2019-11-19T19:33:36Z <p>I have written a code. It contains a 2d string array as an element in structure .Now how to write and read these structures into file?</p> <p>Thanks in advance</p> /q/58941409 -1 Having a problem with the type float (attempted overflow) in C language bla /users/10609569 2019-11-19T19:18:51Z 2019-11-19T19:31:11Z <p>I know the size of the float is 4 bytes, so I tried to put 2<sup>32</sup>, which worked and didn't show a limit.</p> <p>When I tried to put 50 billion, it presented the number with divergence. And just when I put 2<sup>64</sup> (8 bytes) it didn't work, but 2<sup>64</sup>-1, yes works. </p> <p>So why? Why it doesn't show a limit already over 4 bytes, And if it allows 8 bytes, why then there is a divergence after rebooting a number?</p> <p>I use VS 2019.</p> /q/58941292 -5 Substring of size is called good if the count of all 1s in this substring is not greater than m [on hold] Arijeet Acharyya /users/10814373 2019-11-19T19:11:41Z 2019-11-19T19:11:41Z <p>I am new to coding and I can't code this question as I can't understand how to detect the good substring in the binary string. It would be really nice if anyone can explain me with code, how it works or how it can happen. I am really feeling helpless after 4 hours of brainstorming.</p> <p>The question as it is :</p> <p>You are given a binary string s of size n containing only 0s and 1s. A substring of size is called good if the count of all 1s in this substring is not greater than m.</p> <p>You are required to transform a string in such a manner that every substring of size are good by performing some operations. In one operation, you can change the value of a character in a string from 1 to 0.</p> <p>Determine the minimum number of operations that are required such that every substring of size in the given string is good.</p> <p>Input format</p> <p>First line: Three space-separated integers n, k, and m Second line: Binary string s of size n. Output format</p> <p>First line: Print a single integer that denotes the minimum number of operations that are required. Second line: Print the strings that are transformed after applying the operations. If there are multiple such strings, then you can print any of them.</p> <p>SAMPLE INPUT 12 4 2 111000111011 SAMPLE OUTPUT 2 110000110011 Explanation The minimum operations required is 2.</p> <p>Operations: convert s[2] to 0 then convert s[8] to 0. Now the string becomes 110000110011 where all substrings of size 4 are good.</p> <p>The string 101000110011 also may be the answer because here also all the substrings of size 4 are good. Operations: convert s[1] to 0 then convert s[8] to 0.</p> <p>Languages like c, c++, Python or Javascript I can understand.</p> /q/58940945 2 OpenSSL: Encrypt a symmetric key with an ECC public key The Quantum Physicist /users/1317944 2019-11-19T18:48:49Z 2019-11-19T19:25:27Z <p>I have a symmetric key that I would like to encrypt with an ECC public key using OpenSSL. In its high-level portion, EVP, OpenSSL <a href="" rel="nofollow noreferrer">offers a solution</a> to encrypt "an envelop", which is exactly what I need. </p> <p>However, I would like to have these in separate steps, not all in one, as OpenSSL offers in EVP. I would like to have control where I encrypt the symmetric key myself with OpenSSL, and encrypt the message using my own C++ wrappers, and put them both in my selected format.</p> <p>How can I encrypt the just symmetric key with a public key using OpenSSL without having it encrypt the message as well? Is this doable?</p> <p>I've tried to have zero-length plaintext in the example provided, but it crashes. Is this possible?</p> <p>If not, how can I encrypt with a public key without EVP with an <code>EC_KEY</code>?</p> /q/58940813 -1 identifier "DDRB" is undefined - VS code / Visual studio Luuk Wuijster /users/7267640 2019-11-19T18:39:00Z 2019-11-19T19:15:12Z <p>I am getting the following error when using the identifier <code>DDRB</code>:</p> <blockquote> <p>identifier "DDRB" is undefined</p> </blockquote> <p>But, when I click “go to definition”, the IDE does shows that it can find them. The code also compiles without any problem. I was using VScode first and setting intellisense to "tag parser" did work, but it also got rid of the error checking. So, I switched over to Visual Studio, but the issue remains. In both cases I included the AVR library.</p> <p>I have googled quite a bit and found some solutions, but most were outdated or did not work. What can I do to resolve this issue?</p> <p><strong>"minimal reproducible example:"</strong></p> <pre><code>#include &lt;avr\io.h&gt; int main() { DDRB |= (1 &lt;&lt; DD3); } </code></pre> /q/58940764 -5 Systems programming questions help: UNIX files systems, File persmission, low level IO, standard IO, process control, IPC with PIPES [on hold] dockdack /users/12399508 2019-11-19T18:35:17Z 2019-11-19T19:02:08Z <ol> <li><p>When using low-level I/O in C on Unix, you are provided with a file descriptor, which is just an integer, on opening/creating a file. Explain, with diagrams, how the Unix kernel uses this file descriptor to access the actual file on the disk. Also, explain what happens when two processes open the same file.</p></li> <li><p>(a) Write a C function fcopy for a UNIX system that implements the following specification:</p> <pre><code>fcopy(char *srcfname, char *destfname) </code></pre> <p>if srcfname is a regular file, fcopy, copies the contents of srcfname to destfname (creating destfname if needed). Use only C System functions.</p> <p>(b) Write a C function dcopy for a UNIX system that implements the following specification:</p> <pre><code>dcopy(char *srcdir, char *destdir) </code></pre> <p>if srcdir is a directory, dcopy copies all regular unhidden files from srcdir to destdir (creating destdir if needed). If destdir exists, any copied file is replaced by the new version. You may use your fcopy and C System functions.</p></li> <li><p>Answer the following</p> <p>a. How do you determine which is the parent and which is the child after the fork() call.</p> <p>b. Why is it that each open file has only one entry in the vnode_table even if the file is opened by multiple processes</p> <p>c. Why do you sometimes need to use fflush() when using FILE * to write data?</p></li> <li><p>Consider the following Parent/Child arrangement with pipes.</p> <p><a href="" rel="nofollow noreferrer">figure1</a></p> <p>a. Does process main know the PID of process child4? Why or why not?</p> <p>b. Write the snippet of code that creates pipe2 and connects its read side to stdin.</p> <p>c. Write the code for the process main that creates this arrangement along with the two pipes connected as shown. Make sure to label each section with the child#.</p></li> </ol> /q/58940095 0 Error while using JNI: error while loading shared libraries: cannot open shared object file: No such file or directory Inver /users/10140216 2019-11-19T17:53:05Z 2019-11-19T17:53:05Z <p>I would like to call Java methods using C program. I've used <a href="" rel="nofollow noreferrer">this</a> tutorial to do that. Unfortunately I have been surprised by an error: <code>./base: error while loading shared libraries: cannot open shared object file: No such file or directory </code> Starage is that C file compiles without any problems.</p> <p>I use 3 files to make the program:</p> <ul> <li>/home/inver/dev/jni/<a href="" rel="nofollow noreferrer"></a></li> <li>/home/inver/dev/jni/<a href="" rel="nofollow noreferrer">base.c</a></li> <li>/home/inver/dev/jni/<a href="" rel="nofollow noreferrer"></a></li> </ul> <p>Of course is compiled.</p> <p>Any ideas what's wrong?</p> /q/58939915 -1 How to export error-handling to a function in C using <errno.h> Balázs Börcsök /users/10653163 2019-11-19T17:40:36Z 2019-11-19T19:08:03Z <p>I am checking if user enters the correct number and type of cmd arguments when calling main.</p> <p>I thought it would be a great idea to write a function, which prints out some text, so I can reuse it when checking for <code>NULL</code> pointers. I included <code>&lt;errno.h&gt;</code>.</p> <pre><code>void errcall() { perror("Error printed by perror()"); exit(EXIT_FAILURE); } </code></pre> <p>Then I wrote a function to check if arguments are right and sufficient.</p> <pre><code>void err_cmd_handle(int argc_input) { if(argc_input==1 || argc_input&gt;2) errcall(); } </code></pre> <p>When I call this in main, giving <code>int argc</code> as an argument to <code>err_cmd_handle()</code>, then I get a success, even when I did not give <em>any</em> arguments besides starting the program. Why does the condition fail to check correctly?</p> <pre><code>int main(int argc,char* argv[]) { err_cmd_handle(argc); return 0; } </code></pre> /q/58939902 -1 Problems with sums of chars in C EkoLogiko /users/10032844 2019-11-19T17:39:32Z 2019-11-19T18:20:30Z <p>I'm very new to C so I'll make it quick: I'm making a Caesar's Cipher but at some point it starts giving me ? symbols.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;ctype.h&gt; int main(void){ char c; int k; printf("Inserisci la chiave di cifratura: "); scanf("%d", &amp;k); if (k &gt; 26) k = (k%26); printf("%d", k); while ((c=getchar()) != '.') { if (isalpha(c)) { if (c &gt;= 'a' &amp;&amp; c &lt;= 'z') { c = c + k; if (c &gt; 'z') { c = c - 'z' + 'a' - 1; } } else if (c &gt;= 'A' &amp;&amp; c &lt;= 'Z') { c = c + k; if (c &gt; 'Z') { c = c - 'Z' + 'A' - 1; } } putchar(c); } else putchar(c); } printf("\n"); return 0; } </code></pre> <p>If k is 6, it starts giving me the symbol with z. If it is 7, it start with y. Etc...</p> <p>I can't find anything around, thank you to whoever helps me.</p> /q/58939755 0 Row size not declared in 2d array in C Harish Kanna /users/9594641 2019-11-19T17:30:22Z 2019-11-19T17:52:07Z <p>In some programs involving 2d array, written in C, I noted that row size is not mentioned and the compiler is also not throwing any error regarding this. But when I tried this by mentioning the row size but not the column size, the compiler throws an error.</p> <p>Eg:</p> <pre><code>int arr[][5]; // correct int arr[5][]; //compiler throws error </code></pre> <p>What's the reason?</p> /q/58939402 0 How to return an array and print it in main()? [duplicate] PatientJK /users/12247433 2019-11-19T17:07:31Z 2019-11-19T18:04:15Z <div class="question-status question-originals-of-duplicate"> <p>This question already has an answer here:</p> <ul> <li> <a href="/questions/11656532/returning-an-array-using-c" dir="ltr">Returning an array using C</a> <span class="question-originals-answer-count"> 8 answers </span> </li> </ul> </div> <p>Here is the question:</p> <blockquote> <p>Write a function that takes a file handle <code>f</code> as a parameter and returns the number of occurrences of all digits in the file found in the file. Write a program to show how this function can be used to find the number of digits in the file "abd.dat".</p> </blockquote> <p>After I finished this question, I noticed it need a return in the function, I just do the print inside of the function. I made some try to modify the code to do the print in <code>main()</code> function, but it seems not work, the output becomes weird.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #define BASE 10 int digits(FILE *); int main() { FILE *fp = fopen("abc.dat", r); digits(fp); fclose(fp); return EXIT_SUCCESS; } int digits(FILE *f) { long long num, digits; int i, lastDigit; int occu[BASE]; fscanf(f, "%lld", &amp;num); for (i = 0; i &lt; BASE; i++) { occu[i] = 0; } digits = num; while (digits != 0) { lastDigit = digits % 10; digits /= 10; occu[lastDigit]++; } printf(Occurrences of each digit in %lld is: \n, num); for (i = 0; i &lt; BASE; i++) { printf("Occurrences of %d = %d\n", i, occu[i]); } } </code></pre> /q/58939236 -3 How does the precedence works? [duplicate] Ankit Verma /users/12220617 2019-11-19T16:57:01Z 2019-11-19T16:57:01Z <div class="question-status question-originals-of-duplicate"> <p>This question already has an answer here:</p> <ul> <li> <a href="/questions/949433/why-are-these-constructs-using-pre-and-post-increment-undefined-behavior" dir="ltr">Why are these constructs using pre and post-increment undefined behavior?</a> <span class="question-originals-answer-count"> 14 answers </span> </li> </ul> </div> <p>I just tried a snippet in C</p> <pre><code>int a = 1; printf("%d", a++ + ++a + a-- * a++); //Output : 10 </code></pre> <p>Can anyone explains how it prints 10 as output?</p> <hr> <p>From where can I get to know the complete precedence order of all operators in C?</p> /q/58939176 -1 I'm having a hard time with pointers and dynamic arrays BloodLord /users/12398972 2019-11-19T16:53:58Z 2019-11-19T17:38:25Z <p>Edit: Thanks for all of the feedback! I have changed sizeof for strlen, thanks for pointing it out. As for the c++ code here's a tl;dr. We are suppose to learn pure C but the prof has C++ code in his lectures and notes. So unless its blatantly obvious (like std::vector), I can use some C++ function. I also saw someone mention a memory leak, how can I fix that? Edit 2: Someone mentioned the use of new[] instead of malloc and another that I should have another free() for my second malloc. Can I simply change it to new[]? Will it still be a dynamic array? I can't seem to find new[] it my notes so I search for it, but I just need confirmation that this is what I'm trying to do. I also changed the 2 problematic lines thanks to someone's insight. Thanks a lot.</p> <p>Context: this is for a small assignment for university. I'm trying to get a word as an input (e.g "Hello World!") which would then be transformed to remove consonants (e.g. "_e__o _o___!"). Everything is fine for now when it comes to swapping the letters in the array. The problem comes when I try to incorporate it in the main function. the function "wheelOfFortune" does its job but it doesn't seem to be passing the value to a_clue. Here's the code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;iostream&gt; #include &lt;string.h&gt; #include &lt;assert.h&gt; //prototypes char* wheelOfFortune(char* a_answer); //This checks if the letter is a consonant. If it is, it replaces it with '_' char convertChar(char letter, int isLowerCase); //this was done for learning purposes. It simply identifies whether the letter is upper or lower case int isLowerCase(char letter); int main() { /*aWord should be a user input, but it's easier in terms of debugging if I put I automatically gave it values*/ char aWord[15]; for (int i = 0; i &lt; strlen(aWord); i++) { aWord[i] = 'a' + (i / 3); } for (int k = 0; k &lt; strlen(aWord); k++) { printf_s("%c", aWord[k]); } printf_s("\n"); char* a_clue = wheelOfFortune(aWord); //This line has been edited printf_s("%s", a_clue); free(a_clue); } char* wheelOfFortune(char* a_answer) { unsigned int numChar = strlen(a_answer); char* guessWord = (char*)malloc(strlen(a_answer)); int numLowerCase = 0; for (int i = 0; i &lt; 15; i++) { numLowerCase = isLowerCase(a_answer[i]); printf("%c\t", a_answer[i]); guessWord[i] = convertChar(a_answer[i], numLowerCase); printf("%c\t", guessWord[i]); } return guessWord; } </code></pre> <p>I'm 99% sure the problem is with the lines "char* a_clue = (char*)malloc(sizeof(aWord)); a_clue = wheelOfFortune(aWord);" but I don't know what to do to fix it.</p> /q/58938632 -2 How to copy characters in an empty string in C? Yingqiang Gao /users/7759152 2019-11-19T16:22:51Z 2019-11-19T16:57:25Z <p>I have some strings that look like <code>&lt;12&gt;</code>, where the numbers range from 1 to 100. Now I want to extract the numbers from the string, i.e. drop the brackets.</p> <p>This is what I wrote:</p> <pre><code>char str[5] = "&lt;12&gt;"; char final[5] = ""; for(int i=0;i&lt;strlen(str);i++){ if(isdigit(str[i])){ final[i] = str[i]; } } </code></pre> <p>However, I wasn't able to copy the desired number into this empty string and I got nothing printed out. What's the problem?</p> /q/58938528 0 Problem of a simple float number serialization example Rick /users/5983841 2019-11-19T16:17:44Z 2019-11-19T18:22:19Z <p>I am reading the Serialization section of a tutorial <a href="" rel="nofollow noreferrer"></a> . </p> <p>And I am reviewing the code which <em>Encode the number into a portable binary form</em>.</p> <pre><code>#include &lt;stdint.h&gt; uint32_t htonf(float f) { uint32_t p; uint32_t sign; if (f &lt; 0) { sign = 1; f = -f; } else { sign = 0; } p = ((((uint32_t)f)&amp;0x7fff)&lt;&lt;16) | (sign&lt;&lt;31); // whole part and sign p |= (uint32_t)(((f - (int)f) * 65536.0f))&amp;0xffff; // fraction return p; } float ntohf(uint32_t p) { float f = ((p&gt;&gt;16)&amp;0x7fff); // whole part f += (p&amp;0xffff) / 65536.0f; // fraction if (((p&gt;&gt;31)&amp;0x1) == 0x1) { f = -f; } // sign bit set return f; } </code></pre> <p>I ran into problems with this line <code>p = ((((uint32_t)f)&amp;0x7fff)&lt;&lt;16) | (sign&lt;&lt;31); // whole part and sign</code> .</p> <p>According to the original code comments, this line extracts the <strong>whole part</strong> and <strong>sign</strong>, and the next line deals with <strong>fraction</strong> part.</p> <p>Then I found an image about how <code>float</code> is represented in memory and started the calculation by hand.</p> <p>From Wikipedia <a href="" rel="nofollow noreferrer">Single-precision floating-point format</a>: </p> <p><img src="" alt=""></p> <p>So I then presumed that <strong>whole part</strong> == <strong>exponent part</strong>.</p> <p>But this <code>(uint32_t)f)&amp;0x7fff)&lt;&lt;16)</code> is getting the <strong>last</strong> <code>15bits</code> of the fraction part, if based on the image above.</p> <p>Now I get confused, where did I get wrong?</p> /q/58938219 0 get_next_line implementation in C Hélène Brulin /users/12319576 2019-11-19T16:01:53Z 2019-11-19T17:35:22Z <p>I am trying to implement <code>get_next_line</code>, a function that enables me to read a file one line at a time until <code>EOF</code>, and store the lines in a table of pointers, <code>**line</code>. Here is my code: </p> <pre><code>int ft_fill_line(char **s, char **line) { char *tmp; int len; len = 0; while ((*s)[len] != '\n' &amp;&amp; (*s)[len]) len++; if((*s)[len] == '\n') { *line = ft_substr(*s, 0, len); tmp = ft_strdup((*s) + len + 1); free((*s)); (*s) = tmp; if ((*s)[0] == '\0') { free(*s); s = NULL; } } else if ((*s)[len] == '\0') { *line = ft_strdup(*s); free(*s); s = NULL; } return (1); } int get_next_line(int fd, char **line) { static char *s; char buf[BUFFER_SIZE +1]; char *tmp; int ret; if (fd &lt; 0 || line == NULL) return (-1); while ((ret = read(fd, buf, BUFFER_SIZE)) &gt; 0) { buf[ret] = '\0'; if (s == NULL) s = ft_strnew(1); tmp = ft_strjoin(s, buf); free(s); s = tmp; if (ft_strchr(buf, '\n')) break; } if (ret &lt; 0) return(-1); else if (ret == 0 &amp;&amp; (s == NULL || s[0] == '\0')) return (0); return (ft_fill_line(&amp;s, line)); } </code></pre> <p><code>ft_substr</code> being a program that truncates a string, <code>ft_strjoin</code> a program that joins two strings, <code>ft_strnew</code> a program that allocates a new string of the size it takes as input, <code>ft_strchr</code> a function that searches a character in a string and returns a pointer to it.</p> <p>When I compile, I keep getting the following error : "pointer being freed was not allocated". I can fix this error when I set my <code>static s</code> to NULL at the beginning of my <code>function get_next_line</code>, yet when I do that my program modifies the content of the file that is read.</p> <p>Here is my <code>main.c</code>:</p> <pre><code>int main(void) { int fd; char **line; int ret; fd = open("text.txt", O_RDONLY); if (!(line = (char **)malloc(sizeof(char*) * 10000))) return (0); while ((ret = get_next_line(fd, line)) &gt; 0) { printf("%s\n", *line); printf("%i\n", ret); free(*line); } printf("%s\n", *line); printf("%i\n", ret); free(line); return(0); </code></pre> <p>}</p> <p>Does anyone know what's wrong with my program? It seems to me that <code>s</code> is always allocated before I free it.</p> /q/58938028 0 How to parse a text file that have both numbers and text in C? mmm /users/12398706 2019-11-19T15:53:12Z 2019-11-19T16:02:57Z <p>I want to parse the text file below. I'm a little bit confused about the format of this text file since it includes text and numbers. I would like to store the first 6 lines (only the numbers) in a variable to be later used on my code. Then I would like to parse the rest of the data into a 2D array format. </p> <p>Example of the text file: </p> <pre><code>Resistance per unit length (ohm/um): 0.0165 Capacitance per unit length (F/um): 1.8400e-016 Sink node capacitance (F): 2.500000e-016 Buffer output resistance (ohm): 0.01 Sinkcount: 267 Nodecount: 965 %thisnode parnode lcnode rcnode length(um) xloc(um) yloc(um) 1 534 -1 -1 405.080000 29322.000000 41420.000000 2 535 -1 -1 1635.360000 26208.000000 51579.000000 3 536 -1 -1 561.000000 35565.000000 61661.000000 4 537 -1 -1 223.150000 36852.000000 64281.000000 5 538 -1 -1 648.000000 33416.000000 62525.000000 6 539 -1 -1 1828.300000 36915.000000 67124.000000 7 270 -1 -1 126.700000 32275.000000 58078.000000 8 327 -1 -1 1358.200000 30591.000000 67258.000000 9 540 -1 -1 648.000000 33180.000000 61229.000000 10 541 -1 -1 3871.620000 43063.000000 69393.000000 11 314 -1 -1 1084.900000 36871.000000 61100.000000 12 542 -1 -1 4248.380000 43027.000000 61273.000000 13 543 -1 -1 2887.870000 51342.000000 60304.000000 14 349 -1 -1 1500.600000 48402.000000 50963.000000 15 544 -1 -1 731.400000 47169.000000 48731.000000 16 545 -1 -1 2865.890000 52320.000000 39499.000000 17 546 -1 -1 104.000000 53329.000000 36125.000000 18 336 -1 -1 1290.400000 50974.000000 41565.000000 19 547 -1 -1 294.090000 54258.000000 39095.000000 20 548 -1 -1 2206.560000 63990.000000 36007.000000 21 348 -1 -1 1337.200000 57164.000000 37226.000000 22 906 -1 -1 718.500000 52707.000000 34101.000000 23 550 -1 -1 380.310000 49281.000000 28791.000000 24 382 -1 -1 1814.700000 46469.000000 31039.000000 25 551 -1 -1 1.000000 37908.000000 21556.000000 26 552 -1 -1 1272.020000 34929.000000 27721.000000 27 553 -1 -1 984.000000 34185.000000 24396.000000 28 554 -1 -1 945.300000 37959.000000 29214.000000 29 325 -1 -1 1153.400000 44933.000000 26816.000000 30 555 -1 -1 181.600000 41203.000000 23650.000000 31 389 -1 -1 2206.700000 47123.000000 25155.000000 32 556 -1 -1 411.290000 45869.000000 32701.000000 </code></pre> /q/58937664 1 CMPLX Yields Undefined Symbol with GCC Keith Prussing /users/4249913 2019-11-19T15:35:24Z 2019-11-19T15:35:24Z <p>I'm trying to hunt down a problem using complex literals when compiling with GCC. Consider the following</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;complex.h&gt; int main(void) { double complex z = CMPLX(0.0, -1.0); printf("z = %.1f%+.1fi\n", creal(z), cimag(z)); return 0; } </code></pre> <p>(slightly modified from <a href="" rel="nofollow noreferrer">the reference page</a>). If I compile with Clang, it works as expected. However, if I use GCC I get an undefined reference error</p> <pre><code>gcc -std=c11 mwe.c mwe.c: 6:24 warning: implicit declaration of function 'CMPLX' ... mwe.c:(...) undefined reference to `CMPLX' </code></pre> <p>I have tried this with GCC 4.7 and 7.2 on Linux and GCC 9 on MacOS. The error messages change, but the net result remains the same. Reviewing the <a href="/a/42122851/4249913">reference for <code>CMPLX</code></a>, this should be valid C11. Based on <a href="/a/42122851/4249913">this answer</a> and <a href="" rel="nofollow noreferrer">this post</a>, it appears like GCC accepted this construct before.</p> <p>My bottom line question is: Why can't I use <code>CMPLX</code> with GCC? </p> /q/58937343 -2 Are there any example of a MODBUS RTU implementation on a 8 bit EFM8UB2 microcontroller in C? [on hold] Zékány /users/10428650 2019-11-19T15:20:12Z 2019-11-19T15:20:12Z <p><strong>Hello guys!</strong> <em>I recently started with EFM8UB20F64G-B-QFP48R microcontroller. It seems to be a very powerful little thing. I want to communicate with another microcontroller that i'am using right now, via MODBUS RTU. ( rs232 or 485 doesn't matter ) The EFM8UB2 will be a slave Modbus rs232 device. Its work is to be a some kind of I/O expander for my ESP32. To be achive this, i want to use its UART peripherial to be able to communicate with multiple chips from the esp32.</em></p> <p>Right now i'am using Simplicity IDE for programming the EFM8UB2. The esp32 side programming is happening with Visual Studio Code and with Arduino framework. So as you can see from that information, the C language is a bit tricky for me. What i wanted to know is, are there any example code for Modbus rtu implementation in C language for the EFM8UB2 chip, or some another 8051 controller example. I found an UART example in the Simplicity IDE for the EFM8UB2 controller. It is pretty straight forward. But don't know how to proceed further, especially for MODBUS RTU. ( I have seen a dozen of videos from the modbus protocol so in theory i know how it works )</p> <p>Any help would be much appreciated. ( Where should i start, maybe an example c modbus rtu uart code )</p> <p><a href="" rel="nofollow noreferrer">The datasheet for the EFM8UB20F64G-B-QFP48R controller is found here:</a></p> /q/58937258 0 I am getting an error message when trying to split a string and put them into an array kindawg /users/12398481 2019-11-19T15:16:08Z 2019-11-19T16:36:52Z <p>I am trying to split the user's input and put each delimiter in an array.</p> <p>For some reasons, with the code I have here, I get an error message:</p> <blockquote> <p>called object type 'char *[10]' is not a function or function pointer</p> </blockquote> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #define MAX 10 #define SIZE 256 char *read_line(char *buf, size_t sz) { printf("&gt; "); fgets(buf, sz, stdin); buf[strcspn(buf, "\n")] = 0; return buf; } void split(char *buf, char *split[], size_t max) { char *temp = strtok(buf, " "); for (int i = 0; split[0] != '\0'; i++) { strcpy(split[i], temp); temp = strtok(NULL, buf); } } int main(int argc, char **argv) { char *buf = malloc(SIZE); char *split[MAX]; while(1) { char *input = read_line(buf, SIZE); split(input, split, MAX); } } </code></pre> <p>Any help would be much appreciated.</p> /q/58937235 0 How to kill Linux Kernel Thread? gaston /users/11958500 2019-11-19T15:15:21Z 2019-11-19T15:25:50Z <p>I am developing Linux kernel module. This module is communicating with my user-space C application. In this module, I am creating a thread. this is a part of my module where I am facing the problem :</p> <pre><code>static struct task_struct *thread1; static ssize_t read_pid(struct file *pfile, char __user *buffer, size_t length, loff_t *offset) { unsigned int rand; get_random_bytes(&amp;rand, sizeof(rand)); rand = rand % 250; char our_thread[20]; sprintf(our_thread, "thread%u", rand); if(thread1==NULL) { thread1 = kthread_create(read_in_thread,&amp;args,our_thread); if((thread1)) { printk(KERN_INFO "Thread is created\n"); printk("thread name %s\n", our_thread); // lancement du thread wake_up_process(thread1); printk(KERN_INFO "Thread is awake\n"); } } else printk("THREAD1 IS NOT NULL!!! CAN NOT CREATE THREAD!!!\n"); } </code></pre> <p>When I execute my user-space program for the first time, everything is working well and it prints for me on the console : </p> <pre><code>Thread is created thread name Thread is awake </code></pre> <p>But when I press <code>Ctrl+C</code> to exit the running user space code and execute it again, it prints :</p> <pre><code>THREAD1 IS NOT NULL!!! CAN NOT CREATE THREAD!!! </code></pre> <p>I think that <strong>*thread1</strong> is not free or the thread is not killed. I think that I need to kill the thread under <code>else</code> statement in order I can create another one when I re-run my program.</p> <p>Could anyone help me ? Thank you.</p> /q/58935952 0 Why is my C program not printing out the string? Jake Jackson /users/8902744 2019-11-19T14:08:13Z 2019-11-19T17:55:15Z <p>I am am making a program that prints out what the user types in, and it needs to be done with the method <code>read_line()</code> (for my homework), so I can't change too much.</p> <p>I don't understand why it isn't printing out what the user enters.</p> <pre><code>#include &lt;stdlib.h&gt; char *read_line(char *buf, size_t sz) { char tempBuf[sz]; char c; int pos = 0; printf("&gt; "); while(1) { c = getchar(); if (tempBuf[pos] == EOF || tempBuf[pos] == '\n') { buf = tempBuf; return buf; } else { tempBuf[pos] = c; } pos++; } } int main(int argc, char **argv) { char *buf; char *input = read_line(buf, 128); printf("Here: %s", input); } </code></pre> <p>I am new to C and I am finding it very confusing, so please explain anything in pretty simple terms. Any help would be much appreciated.</p> /q/58935636 -2 How to transfer int variable addresses in C? MTA /users/679099 2019-11-19T13:52:41Z 2019-11-19T14:18:19Z <p>I want to transfer <code>int</code> memory from program to program:</p> <p>This is how i get the <code>int</code> memory allocation, and i want to print it:</p> <pre><code>ioresult main (char *params) { int year=0, month=0, day=0, hour=0 ,min=0, i=0; char * token; char *p = params; printf("DateMethod: %s\n",params); token = strtok(params, " "); while( token != NULL ) { printf( " %s\n", token ); if(i == 0) { year = (void *)(strtol(token, NULL, 0)); } else if(i == 1) { month = (void *)(strtol(token, NULL, 0)); } else if(i == 2) { day = (void *)(strtol(token, NULL, 0)); } else if(i == 3) { hour = (void *)(strtol(token, NULL, 0)); } else if(i == 4) { min = (void *)(strtol(token, NULL, 0)); } token = strtok(NULL, " "); i++; } printf("Method Date: %d-%02d-%02d %02d:%02d\n", year, month, day, hour, min); return S_OK; } </code></pre> <p>The <code>params</code> print show me:</p> <pre><code>DateMethod: 0x904 0x905 0x906 0x907 0x908 </code></pre> <p>But in the other <code>printf</code> i get this:</p> <pre><code>Method Date: 2309-2310-2311 2312:00 </code></pre> <p>And this is not the values inside the int. Any idea what is the problem?</p> /q/58935467 0 One or two weird linking errors with some inline assembly Ferenc Deak /users/186193 2019-11-19T13:43:02Z 2019-11-19T13:54:38Z <p>I have the following short application (The original is taken from: <a href="" rel="nofollow noreferrer"></a>) I just modified it (tried to...) to make it compilable on linux too.</p> <pre><code>#include &lt;stdio.h&gt; unsigned char mema[4] = {0, 0, 0, 0}; void test4 (void) { asm ( "str mema\n" ); printf ("\n[+] Test 4: STR\n"); printf ("STR base: 0x%02x%02x%02x%02x\n", mema[0], mema[1], mema[2], mema[3]); if ((mema[0] == 0x00) &amp;&amp; (mema[1] == 0x40)) printf ("Result : VMware detected\n\n"); else printf ("Result : Native OS\n\n"); } int main () { test4(); } </code></pre> <p>and when I try to compile it:</p> <pre><code>$ gcc -ggdb -O0 -fPIC -x c ./pill.c -o pill </code></pre> <p>it gives me the wird error:</p> <pre><code>/usr/bin/ld: /tmp/ccDhGo05.o: relocation R_X86_64_32S against symbol `mema' can not be used when making a PIE object; recompile with -fPIC /usr/bin/ld: final link failed: Nonrepresentable section on output collect2: error: ld returned 1 exit status </code></pre> <p>However the same thing works on an online compiler: <a href="" rel="nofollow noreferrer"></a> </p> <p>... except if I move the variable <code>mema</code> to be a local variable in the function <code>test4</code> when it complains both places about </p> <pre><code>undefined symbol `mema' </code></pre> <p>And another weirdity: same stuff works when compiled with clang.</p> <p>Any idea why this happens? (Not considering the required privilege level for <code>STR</code>, and other thingies, I am just interested in the linking error and why does it work on one system / compiler and not on another.</p> /q/58935451 0 Two way communication from the file that run with exec in child Irem /users/9165700 2019-11-19T13:41:57Z 2019-11-19T15:52:36Z <p>I am creating a child process with fork in program y. In that child, I run another program with exec, in which I want the function in that program (let's call it program x) to return something to me. Is there a way to pass this returned value to the parent? I provided some sort of a pseudo code that demonstrates what I want to do below.</p> <p>program.x:</p> <pre><code> int main(int argc, char** argv) { if(argc != 2) { printf("argument count does not match\n"); return -1; } printf("task1!\n"); ... char *value = "want this"; // how to pass this to the parent in the program y? ... } </code></pre> <p>program y:</p> <pre><code>int main(int argc, char *argv[]) { int fd[2]; pipe(fd); pid_t p; p = fork(); if(p==-1) { printf("There is an error while calling fork()"); } if(p==0) { printf("We are in the child process\n"); printf("Calling hello.c from child process\n"); char *args[] = {"Hello", "C", "Programming", NULL}; execv("./hello", args); close(fd[0]); write(fd[1], ???, ??); close(fd[0]); } else { printf("We are in the parent process"); wait(NULL); close(fd[1]); read(fd[0], ???,???); close(fd[0]); } return 0; } </code></pre>