{"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nWrite a function to find the longest common prefix string amongst an array of strings.\n\nIf there is no common prefix, return an empty string \"\".\n\n### Examples\nInput: strs = [\"flower\",\"flow\",\"flight\"]\nOutput: \"fl\"\nInput: strs = [\"dog\",\"racecar\",\"car\"]\nOutput: \"\"\n\n### Algorithm\nTrie"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n string longestCommonPrefix(vector& strs) {\n int n = strs.size();\n for (int i = 0; i < strs[0].size(); ++i) {\n for (int j = 1; j < n; ++j) {\n if (strs[j].size() <= i || strs[j][i] != strs[0][i]) {\n return strs[0].substr(0, i);\n }\n }\n }\n return strs[0];\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nGiven an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where:\n\n\t'?' Matches any single character.\n\t'*' Matches any sequence of characters (including the empty sequence).\n\nThe matching should cover the entire input string (not partial).\n\n### Examples\nInput: s = \"aa\", p = \"a\"\nOutput: false\nInput: s = \"aa\", p = \"*\"\nOutput: true\nInput: s = \"cb\", p = \"?a\"\nOutput: false\n\n### Algorithm\nMemoization"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n int m = s.size(), n = p.size();\n int f[m + 1][n + 1];\n memset(f, -1, sizeof(f));\n function dfs = [&](int i, int j) {\n if (i >= m) {\n return j >= n || (p[j] == '*' && dfs(i, j + 1));\n }\n if (j >= n) {\n return false;\n }\n if (f[i][j] != -1) {\n return f[i][j] == 1;\n }\n if (p[j] == '*') {\n f[i][j] = dfs(i + 1, j) || dfs(i, j + 1) ? 1 : 0;\n } else {\n f[i][j] = (p[j] == '?' || s[i] == p[j]) && dfs(i + 1, j + 1) ? 1 : 0;\n }\n return f[i][j] == 1;\n };\n return dfs(0, 0);\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nGiven an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.\n\n### Examples\nInput: intervals = [[1,3],[2,6],[8,10],[15,18]]\nOutput: [[1,6],[8,10],[15,18]]\nInput: intervals = [[1,4],[4,5]]\nOutput: [[1,5]]\nInput: intervals = [[4,7],[1,4]]\nOutput: [[1,7]]\n\n### Algorithm\nSorting"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n vector> merge(vector>& intervals) {\n sort(intervals.begin(), intervals.end());\n int st = intervals[0][0], ed = intervals[0][1];\n vector> ans;\n for (int i = 1; i < intervals.size(); ++i) {\n if (ed < intervals[i][0]) {\n ans.push_back({st, ed});\n st = intervals[i][0];\n ed = intervals[i][1];\n } else {\n ed = max(ed, intervals[i][1]);\n }\n }\n ans.push_back({st, ed});\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nA path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.\n\nThe path sum of a path is the sum of the node's values in the path.\n\nGiven the root of a binary tree, return the maximum path sum of any non-empty path.\n\n### Examples\nInput: root = [1,2,3]\nOutput: 6\nInput: root = [-10,9,20,null,null,15,7]\nOutput: 42\n\n### Algorithm\nRecursion"}, {"role": "assistant", "content": "```cpp\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n int maxPathSum(TreeNode* root) {\n int ans = -1001;\n function dfs = [&](TreeNode* root) {\n if (!root) {\n return 0;\n }\n int left = max(0, dfs(root->left));\n int right = max(0, dfs(root->right));\n ans = max(ans, left + right + root->val);\n return root->val + max(left, right);\n };\n dfs(root);\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nGiven an unsorted array of integers nums, return the length of the longest consecutive elements sequence.\n\nYou must write an algorithm that runs in O(n) time.\n\n### Examples\nInput: nums = [100,4,200,1,3,2]\nOutput: 4\nInput: nums = [0,3,7,2,5,8,4,6,0,1]\nOutput: 9\nInput: nums = [1,0,1,2]\nOutput: 3\n\n### Algorithm\nHash Table"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int longestConsecutive(vector& nums) {\n unordered_set s(nums.begin(), nums.end());\n int ans = 0;\n for (int x : s) {\n if (!s.contains(x - 1)) {\n int y = x + 1;\n while (s.contains(y)) {\n y++;\n }\n ans = max(ans, y - x);\n }\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nGiven two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.\n\n### Examples\nInput: left = 5, right = 7\nOutput: 4\nInput: left = 0, right = 0\nOutput: 0\nInput: left = 1, right = 2147483647\nOutput: 0\n\n### Algorithm\nBit Manipulation"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int rangeBitwiseAnd(int left, int right) {\n while (left < right) {\n right &= (right - 1);\n }\n return right;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nThere is a singly-linked list head and we want to delete a node node in it.\n\nYou are given the node to be deleted node. You will not be given access to the first node of head.\n\nAll the values of the linked list are unique, and it is guaranteed that the given node node is not the last node in the linked list.\n\nDelete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:\n\n\tThe value of the given node should not exist in the linked list.\n\tThe number of nodes in the linked list should decrease by one.\n\tAll the values before node should be in the same order.\n\tAll the values after node should be in the same order.\n\nCustom testing:\n\n\tFor the input, you should provide the entire linked list head and the node to be given node. node should not be the last node of the list and should be an actual node in the list.\n\tWe will build the linked list and pass the node to your function.\n\tThe output will be the entire list after calling your function.\n\n### Examples\nInput: head = [4,5,1,9], node = 5\nOutput: [4,1,9]\nExplanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.\nInput: head = [4,5,1,9], node = 1\nOutput: [4,5,9]\nExplanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.\n\n### Algorithm\nLinked List"}, {"role": "assistant", "content": "```cpp\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n void deleteNode(ListNode* node) {\n node->val = node->next->val;\n node->next = node->next->next;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nGiven an integer array nums, return the length of the longest strictly increasing subsequence.\n\n### Examples\nInput: nums = [10,9,2,5,3,7,101,18]\nOutput: 4\nInput: nums = [0,1,0,3,2,3]\nOutput: 4\nInput: nums = [7,7,7,7,7,7,7]\nOutput: 1\n\n### Algorithm\nDynamic Programming"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int lengthOfLIS(vector& nums) {\n int n = nums.size();\n vector f(n, 1);\n for (int i = 1; i < n; ++i) {\n for (int j = 0; j < i; ++j) {\n if (nums[j] < nums[i]) {\n f[i] = max(f[i], f[j] + 1);\n }\n }\n }\n return *max_element(f.begin(), f.end());\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nGiven a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0.\n\n### Examples\nInput: words = [\"abcw\",\"baz\",\"foo\",\"bar\",\"xtfn\",\"abcdef\"]\nOutput: 16\nInput: words = [\"a\",\"ab\",\"abc\",\"d\",\"cd\",\"bcd\",\"abcd\"]\nOutput: 4\nInput: words = [\"a\",\"aa\",\"aaa\",\"aaaa\"]\nOutput: 0\n\n### Algorithm\nBit Manipulation"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int maxProduct(vector& words) {\n int n = words.size();\n int mask[n];\n memset(mask, 0, sizeof(mask));\n int ans = 0;\n for (int i = 0; i < n; ++i) {\n for (char& c : words[i]) {\n mask[i] |= 1 << (c - 'a');\n }\n for (int j = 0; j < i; ++j) {\n if ((mask[i] & mask[j]) == 0) {\n ans = max(ans, (int) (words[i].size() * words[j].size()));\n }\n }\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou have a graph of n nodes. You are given an integer n and an array edges where edges[i] = [ai, bi] indicates that there is an edge between ai and bi in the graph.\n\nReturn the number of connected components in the graph.\n\n### Examples\nInput: n = 5, edges = [[0,1],[1,2],[3,4]]\nOutput: 2\nInput: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]\nOutput: 1\n\n### Algorithm\nDFS"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int countComponents(int n, vector>& edges) {\n vector g[n];\n for (auto& e : edges) {\n int a = e[0], b = e[1];\n g[a].push_back(b);\n g[b].push_back(a);\n }\n vector vis(n);\n function dfs = [&](int i) {\n if (vis[i]) {\n return 0;\n }\n vis[i] = true;\n for (int j : g[i]) {\n dfs(j);\n }\n return 1;\n };\n int ans = 0;\n for (int i = 0; i < n; ++i) {\n ans += dfs(i);\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nGiven two strings s and t, return true if s is a subsequence of t, or false otherwise.\n\nA subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., \"ace\" is a subsequence of \"abcde\" while \"aec\" is not).\n\n### Examples\nInput: s = \"abc\", t = \"ahbgdc\"\nOutput: true\nInput: s = \"axc\", t = \"ahbgdc\"\nOutput: false\n\n### Algorithm\nTwo Pointers"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n bool isSubsequence(string s, string t) {\n int m = s.size(), n = t.size();\n int i = 0, j = 0;\n for (; i < m && j < n; ++j) {\n if (s[i] == t[j]) {\n ++i;\n }\n }\n return i == m;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nGiven a n * n matrix grid of 0's and 1's only. We want to represent grid with a Quad-Tree.\n\nReturn the root of the Quad-Tree representing grid.\n\nA Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:\n\n\tval: True if the node represents a grid of 1's or False if the node represents a grid of 0's. Notice that you can assign the val to True or False when isLeaf is False, and both are accepted in the answer.\n\tisLeaf: True if the node is a leaf node on the tree or False if the node has four children.\n\nclass Node {\n public boolean val;\n public boolean isLeaf;\n public Node topLeft;\n public Node topRight;\n public Node bottomLeft;\n public Node bottomRight;\n}\n\nWe can construct a Quad-Tree from a two-dimensional area using the following steps:\n\n\tIf the current grid has the same value (i.e all 1's or all 0's) set isLeaf True and set val to the value of the grid and set the four children to Null and stop.\n\tIf the current grid has different values, set isLeaf to False and set val to any value and divide the current grid into four sub-grids as shown in the photo.\n\tRecurse for each of the children with the proper sub-grid.\n\nIf you want to know more about the Quad-Tree, you can refer to the wiki.\n\nQuad-Tree format:\n\nYou don't need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal, where null signifies a path terminator where no node exists below.\n\nIt is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val].\n\nIf the value of isLeaf or val is True we represent it as 1 in the list [isLeaf, val] and if the value of isLeaf or val is False we represent it as 0.\n\n### Examples\nInput: grid = [[0,1],[1,0]]\nOutput: [[0,1],[1,0],[1,1],[1,1],[1,0]]\n\n### Algorithm\nDivide and Conquer"}, {"role": "assistant", "content": "```cpp\n/*\n// Definition for a QuadTree node.\nclass Node {\npublic:\n bool val;\n bool isLeaf;\n Node* topLeft;\n Node* topRight;\n Node* bottomLeft;\n Node* bottomRight;\n\n Node() {\n val = false;\n isLeaf = false;\n topLeft = NULL;\n topRight = NULL;\n bottomLeft = NULL;\n bottomRight = NULL;\n }\n\n Node(bool _val, bool _isLeaf) {\n val = _val;\n isLeaf = _isLeaf;\n topLeft = NULL;\n topRight = NULL;\n bottomLeft = NULL;\n bottomRight = NULL;\n }\n\n Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) {\n val = _val;\n isLeaf = _isLeaf;\n topLeft = _topLeft;\n topRight = _topRight;\n bottomLeft = _bottomLeft;\n bottomRight = _bottomRight;\n }\n};\n*/\n\nclass Solution {\npublic:\n Node* construct(vector>& grid) {\n return dfs(0, 0, grid.size() - 1, grid[0].size() - 1, grid);\n }\n\n Node* dfs(int a, int b, int c, int d, vector>& grid) {\n int zero = 0, one = 0;\n for (int i = a; i <= c; ++i) {\n for (int j = b; j <= d; ++j) {\n if (grid[i][j])\n one = 1;\n else\n zero = 1;\n }\n }\n bool isLeaf = zero + one == 1;\n bool val = isLeaf && one;\n Node* node = new Node(val, isLeaf);\n if (isLeaf) return node;\n node->topLeft = dfs(a, b, (a + c) / 2, (b + d) / 2, grid);\n node->topRight = dfs(a, (b + d) / 2 + 1, (a + c) / 2, d, grid);\n node->bottomLeft = dfs((a + c) / 2 + 1, b, c, (b + d) / 2, grid);\n node->bottomRight = dfs((a + c) / 2 + 1, (b + d) / 2 + 1, c, d, grid);\n return node;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are playing a game involving a circular array of non-zero integers nums. Each nums[i] denotes the number of indices forward/backward you must move if you are located at index i:\n\n\tIf nums[i] is positive, move nums[i] steps forward, and\n\tIf nums[i] is negative, move abs(nums[i]) steps backward.\n\nSince the array is circular, you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element.\n\nA cycle in the array consists of a sequence of indices seq of length k where:\n\n\tFollowing the movement rules above results in the repeating index sequence seq[0] -> seq[1] -> ... -> seq[k - 1] -> seq[0] -> ...\n\tEvery nums[seq[j]] is either all positive or all negative.\n\tk > 1\n\nReturn true if there is a cycle in nums, or false otherwise.\n\n### Examples\nInput: nums = [2,-1,1,2,2]\nOutput: true\nInput: nums = [-1,-2,-3,-4,-5,6]\nOutput: false\nInput: nums = [1,-1,5,1,4]\nOutput: true\n\n### Algorithm\nTwo Pointers"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n bool circularArrayLoop(vector& nums) {\n int n = nums.size();\n for (int i = 0; i < n; ++i) {\n if (!nums[i]) continue;\n int slow = i, fast = next(nums, i);\n while (nums[slow] * nums[fast] > 0 && nums[slow] * nums[next(nums, fast)] > 0) {\n if (slow == fast) {\n if (slow != next(nums, slow)) return true;\n break;\n }\n slow = next(nums, slow);\n fast = next(nums, next(nums, fast));\n }\n int j = i;\n while (nums[j] * nums[next(nums, j)] > 0) {\n nums[j] = 0;\n j = next(nums, j);\n }\n }\n return false;\n }\n\n int next(vector& nums, int i) {\n int n = nums.size();\n return (i + nums[i] % n + n) % n;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nIn the video game Fallout 4, the quest \"Road to Freedom\" requires players to reach a metal dial called the \"Freedom Trail Ring\" and use the dial to spell a specific keyword to open the door.\n\nGiven a string ring that represents the code engraved on the outer ring and another string key that represents the keyword that needs to be spelled, return the minimum number of steps to spell all the characters in the keyword.\n\nInitially, the first character of the ring is aligned at the \"12:00\" direction. You should spell all the characters in key one by one by rotating ring clockwise or anticlockwise to make each character of the string key aligned at the \"12:00\" direction and then by pressing the center button.\n\nAt the stage of rotating the ring to spell the key character key[i]:\n\n\tYou can rotate the ring clockwise or anticlockwise by one place, which counts as one step. The final purpose of the rotation is to align one of ring's characters at the \"12:00\" direction, where this character must equal key[i].\n\tIf the character key[i] has been aligned at the \"12:00\" direction, press the center button to spell, which also counts as one step. After the pressing, you could begin to spell the next character in the key (next stage). Otherwise, you have finished all the spelling.\n\n### Examples\nInput: ring = \"godding\", key = \"gd\"\nOutput: 4\nInput: ring = \"godding\", key = \"godding\"\nOutput: 13\n\n### Algorithm\nDynamic Programming"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int findRotateSteps(string ring, string key) {\n int m = key.size(), n = ring.size();\n vector pos[26];\n for (int j = 0; j < n; ++j) {\n pos[ring[j] - 'a'].push_back(j);\n }\n int f[m][n];\n memset(f, 0x3f, sizeof(f));\n for (int j : pos[key[0] - 'a']) {\n f[0][j] = min(j, n - j) + 1;\n }\n for (int i = 1; i < m; ++i) {\n for (int j : pos[key[i] - 'a']) {\n for (int k : pos[key[i - 1] - 'a']) {\n f[i][j] = min(f[i][j], f[i - 1][k] + min(abs(j - k), n - abs(j - k)) + 1);\n }\n }\n }\n int ans = 1 << 30;\n for (int j : pos[key[m - 1] - 'a']) {\n ans = min(ans, f[m - 1][j]);\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nA complex number can be represented as a string on the form \"real+imaginaryi\" where:\n\n\treal is the real part and is an integer in the range [-100, 100].\n\timaginary is the imaginary part and is an integer in the range [-100, 100].\n\ti2 == -1.\n\nGiven two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.\n\n### Examples\nInput: num1 = \"1+1i\", num2 = \"1+1i\"\nOutput: \"0+2i\"\nInput: num1 = \"1+-1i\", num2 = \"1+-1i\"\nOutput: \"0+-2i\"\n\n### Algorithm\nMath"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n string complexNumberMultiply(string num1, string num2) {\n int a1, b1, a2, b2;\n sscanf(num1.c_str(), \"%d+%di\", &a1, &b1);\n sscanf(num2.c_str(), \"%d+%di\", &a2, &b2);\n return to_string(a1 * a2 - b1 * b2) + \"+\" + to_string(a1 * b2 + a2 * b1) + \"i\";\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nDesign and implement a data structure for a compressed string iterator. The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string.\n\nImplement the StringIterator class:\n\n\tnext() Returns the next character if the original string still has uncompressed characters, otherwise returns a white space.\n\thasNext() Returns true if there is any letter needs to be uncompressed in the original string, otherwise returns false.\n\n### Examples\n\n### Algorithm\nArray"}, {"role": "assistant", "content": "```cpp\nclass StringIterator {\npublic:\n StringIterator(string compressedString) {\n int n = compressedString.size();\n int i = 0;\n while (i < n) {\n char c = compressedString[i];\n int x = 0;\n while (++i < n && isdigit(compressedString[i])) {\n x = x * 10 + (compressedString[i] - '0');\n }\n d.push_back({c, x});\n }\n }\n\n char next() {\n if (!hasNext()) return ' ';\n char ans = d[p].first;\n if (--d[p].second == 0) {\n ++p;\n }\n return ans;\n }\n\n bool hasNext() {\n return p < d.size() && d[p].second > 0;\n }\n\nprivate:\n vector> d;\n int p = 0;\n};\n\n/**\n * Your StringIterator object will be instantiated and called as such:\n * StringIterator* obj = new StringIterator(compressedString);\n * char param_1 = obj->next();\n * bool param_2 = obj->hasNext();\n */\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti.\n\nA pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in this fashion.\n\nReturn the length longest chain which can be formed.\n\nYou do not need to use up all the given intervals. You can select pairs in any order.\n\n### Examples\nInput: pairs = [[1,2],[2,3],[3,4]]\nOutput: 2\nInput: pairs = [[1,2],[7,8],[4,5]]\nOutput: 3\n\n### Algorithm\nGreedy"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int findLongestChain(vector>& pairs) {\n ranges::sort(pairs, {}, [](const auto& p) { return p[1]; });\n int ans = 0, pre = INT_MIN;\n for (const auto& p : pairs) {\n if (pre < p[0]) {\n pre = p[1];\n ++ans;\n }\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nThere is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step:\n\n\tCopy All: You can copy all the characters present on the screen (a partial copy is not allowed).\n\tPaste: You can paste the characters which are copied last time.\n\nGiven an integer n, return the minimum number of operations to get the character 'A' exactly n times on the screen.\n\n### Examples\nInput: n = 3\nOutput: 3\nInput: n = 1\nOutput: 0\n\n### Algorithm\nDynamic Programming"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n vector f;\n\n int minSteps(int n) {\n f.assign(n + 1, -1);\n return dfs(n);\n }\n\n int dfs(int n) {\n if (n == 1) return 0;\n if (f[n] != -1) return f[n];\n int ans = n;\n for (int i = 2; i * i <= n; ++i) {\n if (n % i == 0) {\n ans = min(ans, dfs(n / i) + i);\n }\n }\n f[n] = ans;\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nGiven an integer array nums, return the number of longest increasing subsequences.\n\nNotice that the sequence has to be strictly increasing.\n\n### Examples\nInput: nums = [1,3,5,4,7]\nOutput: 2\nInput: nums = [2,2,2,2,2]\nOutput: 5\n\n### Algorithm\nDynamic Programming"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int findNumberOfLIS(vector& nums) {\n int n = nums.size();\n int mx = 0, ans = 0;\n vector f(n, 1);\n vector cnt(n, 1);\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < i; ++j) {\n if (nums[j] < nums[i]) {\n if (f[i] < f[j] + 1) {\n f[i] = f[j] + 1;\n cnt[i] = cnt[j];\n } else if (f[i] == f[j] + 1) {\n cnt[i] += cnt[j];\n }\n }\n }\n if (mx < f[i]) {\n mx = f[i];\n ans = cnt[i];\n } else if (mx == f[i]) {\n ans += cnt[i];\n }\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs.\n\nYou are given an array of employees employees where:\n\n\temployees[i].id is the ID of the ith employee.\n\temployees[i].importance is the importance value of the ith employee.\n\temployees[i].subordinates is a list of the IDs of the direct subordinates of the ith employee.\n\nGiven an integer id that represents an employee's ID, return the total importance value of this employee and all their direct and indirect subordinates.\n\n### Examples\nInput: employees = [[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 1\nOutput: 11\nInput: employees = [[1,2,[5]],[5,-3,[]]], id = 5\nOutput: -3\n\n### Algorithm\nDFS"}, {"role": "assistant", "content": "```cpp\n/*\n// Definition for Employee.\nclass Employee {\npublic:\n int id;\n int importance;\n vector subordinates;\n};\n*/\n\nclass Solution {\npublic:\n int getImportance(vector employees, int id) {\n unordered_map d;\n for (auto& e : employees) {\n d[e->id] = e;\n }\n function dfs = [&](int i) -> int {\n int s = d[i]->importance;\n for (int j : d[i]->subordinates) {\n s += dfs(j);\n }\n return s;\n };\n return dfs(id);\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nGiven a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.\n\n### Examples\nInput: n = 5\nOutput: true\nInput: n = 7\nOutput: false\nInput: n = 11\nOutput: false\n\n### Algorithm\nBit Manipulation"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n bool hasAlternatingBits(int n) {\n n ^= (n >> 1);\n return (n & ((long) n + 1)) == 0;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nDesign a HashSet without using any built-in hash table libraries.\n\nImplement MyHashSet class:\n\n\tvoid add(key) Inserts the value key into the HashSet.\n\tbool contains(key) Returns whether the value key exists in the HashSet or not.\n\tvoid remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.\n\n### Examples\n\n### Algorithm\nLinked List"}, {"role": "assistant", "content": "```cpp\nclass MyHashSet {\nprivate:\n int size = 1000;\n vector> data;\n\npublic:\n MyHashSet()\n : data(size) {\n }\n\n void add(int key) {\n if (contains(key)) {\n return;\n }\n int idx = hash(key);\n data[idx].push_back(key);\n }\n\n void remove(int key) {\n if (!contains(key)) {\n return;\n }\n int idx = hash(key);\n data[idx].remove(key);\n }\n\n bool contains(int key) {\n int idx = hash(key);\n for (auto it = data[idx].begin(); it != data[idx].end(); it++) {\n if ((*it) == key) {\n return true;\n }\n }\n return false;\n }\n\n int hash(int key) {\n return key % size;\n }\n};\n\n/**\n * Your MyHashSet object will be instantiated and called as such:\n * MyHashSet* obj = new MyHashSet();\n * obj->add(key);\n * obj->remove(key);\n * bool param_3 = obj->contains(key);\n */\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nA k-booking happens when k events have some non-empty intersection (i.e., there is some time that is common to all k events.)\n\nYou are given some events [startTime, endTime), after each given event, return an integer k representing the maximum k-booking between all the previous events.\n\nImplement the MyCalendarThree class:\n\n\tMyCalendarThree() Initializes the object.\n\tint book(int startTime, int endTime) Returns an integer k representing the largest integer such that there exists a k-booking in the calendar.\n\n### Examples\n\n### Algorithm\nBinary Search"}, {"role": "assistant", "content": "```cpp\nclass Node {\npublic:\n Node* left;\n Node* right;\n int l;\n int r;\n int mid;\n int v;\n int add;\n\n Node(int l, int r) {\n this->l = l;\n this->r = r;\n this->mid = (l + r) >> 1;\n this->left = this->right = nullptr;\n v = add = 0;\n }\n};\n\nclass SegmentTree {\nprivate:\n Node* root;\n\npublic:\n SegmentTree() {\n root = new Node(1, 1e9 + 1);\n }\n\n void modify(int l, int r, int v) {\n modify(l, r, v, root);\n }\n\n void modify(int l, int r, int v, Node* node) {\n if (l > r) {\n return;\n }\n if (node->l >= l && node->r <= r) {\n node->v += v;\n node->add += v;\n return;\n }\n pushdown(node);\n if (l <= node->mid) {\n modify(l, r, v, node->left);\n }\n if (r > node->mid) {\n modify(l, r, v, node->right);\n }\n pushup(node);\n }\n\n int query(int l, int r) {\n return query(l, r, root);\n }\n\n int query(int l, int r, Node* node) {\n if (l > r) {\n return 0;\n }\n if (node->l >= l && node->r <= r) return node->v;\n pushdown(node);\n int v = 0;\n if (l <= node->mid) {\n v = max(v, query(l, r, node->left));\n }\n if (r > node->mid) {\n v = max(v, query(l, r, node->right));\n }\n return v;\n }\n\n void pushup(Node* node) {\n node->v = max(node->left->v, node->right->v);\n }\n\n void pushdown(Node* node) {\n if (!node->left) {\n node->left = new Node(node->l, node->mid);\n }\n if (!node->right) {\n node->right = new Node(node->mid + 1, node->r);\n }\n if (node->add) {\n Node* left = node->left;\n Node* right = node->right;\n left->v += node->add;\n right->v += node->add;\n left->add += node->add;\n right->add += node->add;\n node->add = 0;\n }\n }\n};\n\nclass MyCalendarThree {\npublic:\n SegmentTree* tree;\n\n MyCalendarThree() {\n tree = new SegmentTree();\n }\n\n int book(int start, int end) {\n tree->modify(start + 1, end, 1);\n return tree->query(1, 1e9 + 1);\n }\n};\n\n/**\n * Your MyCalendarThree object will be instantiated and called as such:\n * MyCalendarThree* obj = new MyCalendarThree();\n * int param_1 = obj->book(start,end);\n */\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given an integer array arr.\n\nWe split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.\n\nReturn the largest number of chunks we can make to sort the array.\n\n### Examples\nInput: arr = [5,4,3,2,1]\nOutput: 1\nInput: arr = [2,1,3,4,4]\nOutput: 4\n\n### Algorithm\nGreedy"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int maxChunksToSorted(vector& arr) {\n vector prefixMaxs; // Max of each arr[:i + 1]. 0 <= i < arr.size().\n\n for (const auto& num : arr) {\n if (prefixMaxs.empty()) {\n prefixMaxs.push_back(num);\n continue;\n }\n\n prefixMaxs.push_back(max(prefixMaxs.back(), num));\n }\n\n int maxChunks = 1; // Base case.\n int suffixMin = arr.back(); // Min of arr[i:]. 0 <= i < arr.size().\n\n for (int idx = arr.size() - 1; idx >= 1; idx--) {\n if (arr[idx] < suffixMin)\n suffixMin = arr[idx];\n\n if (prefixMaxs[idx - 1] <= suffixMin)\n maxChunks++;\n }\n\n return maxChunks;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.\n\nPermute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.\n\nReturn any permutation of s that satisfies this property.\n\n### Examples\n\n### Algorithm\nSorting"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n string customSortString(string order, string s) {\n int cnt[26] = {0};\n for (char& c : s) ++cnt[c - 'a'];\n string ans;\n for (char& c : order)\n while (cnt[c - 'a']-- > 0) ans += c;\n for (int i = 0; i < 26; ++i)\n if (cnt[i] > 0) ans += string(cnt[i], i + 'a');\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYour music player contains n different songs. You want to listen to goal songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that:\n\n\tEvery song is played at least once.\n\tA song can only be played again only if k other songs have been played.\n\nGiven n, goal, and k, return the number of possible playlists that you can create. Since the answer can be very large, return it modulo 109 + 7.\n\n### Examples\nInput: n = 3, goal = 3, k = 1\nOutput: 6\nInput: n = 2, goal = 3, k = 0\nOutput: 6\nInput: n = 2, goal = 3, k = 1\nOutput: 2\n\n### Algorithm\nDynamic Programming"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int numMusicPlaylists(int n, int goal, int k) {\n const int mod = 1e9 + 7;\n vector f(n + 1);\n f[0] = 1;\n for (int i = 1; i <= goal; ++i) {\n vector g(n + 1);\n for (int j = 1; j <= n; ++j) {\n g[j] = f[j - 1] * (n - j + 1);\n if (j > k) {\n g[j] += f[j] * (j - k);\n }\n g[j] %= mod;\n }\n f = move(g);\n }\n return f[n];\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given a binary array nums (0-indexed).\n\nWe define xi as the number whose binary representation is the subarray nums[0..i] (from most-significant-bit to least-significant-bit).\n\n\tFor example, if nums = [1,0,1], then x0 = 1, x1 = 2, and x2 = 5.\n\nReturn an array of booleans answer where answer[i] is true if xi is divisible by 5.\n\n### Examples\nInput: nums = [0,1,1]\nOutput: [true,false,false]\nInput: nums = [1,1,1]\nOutput: [false,false,false]\n\n### Algorithm\nMath"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n vector prefixesDivBy5(vector& nums) {\n vector ans;\n int x = 0;\n for (int v : nums) {\n x = (x << 1 | v) % 5;\n ans.push_back(x == 0);\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nA company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti.\n\nReturn the minimum cost to fly every person to a city such that exactly n people arrive in each city.\n\n### Examples\nInput: costs = [[10,20],[30,200],[400,50],[30,20]]\nOutput: 110\nExplanation: \nThe first person goes to city A for a cost of 10.\nThe second person goes to city A for a cost of 30.\nThe third person goes to city B for a cost of 50.\nThe fourth person goes to city B for a cost of 20.\n\nThe total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.\nInput: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]\nOutput: 1859\nInput: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]\nOutput: 3086\n\n### Algorithm\nGreedy"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int twoCitySchedCost(vector>& costs) {\n sort(costs.begin(), costs.end(), [](const vector& a, const vector& b) {\n return a[0] - a[1] < b[0] - b[1];\n });\n int n = costs.size() / 2;\n int ans = 0;\n for (int i = 0; i < n; ++i) {\n ans += costs[i][0] + costs[i + n][1];\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nGiven a string s, return the length of the longest repeating substrings. If no repeating substring exists, return 0.\n\n### Examples\nInput: s = \"abcd\"\nOutput: 0\nExplanation: There is no repeating substring.\nInput: s = \"abbaba\"\nOutput: 2\nExplanation: The longest repeating substrings are \"ab\" and \"ba\", each of which occurs twice.\nInput: s = \"aabcaabdaab\"\nOutput: 3\nExplanation: The longest repeating substring is \"aab\", which occurs 3 times.\n\n### Algorithm\nDynamic Programming"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int longestRepeatingSubstring(string s) {\n int n = s.length();\n int f[n][n];\n memset(f, 0, sizeof(f));\n int ans = 0;\n for (int i = 1; i < n; ++i) {\n for (int j = 0; j < i; ++j) {\n if (s[i] == s[j]) {\n f[i][j] = 1 + (j > 0 ? f[i - 1][j - 1] : 0);\n ans = max(ans, f[i][j]);\n }\n }\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nGiven an array nums of integers, a move consists of choosing any element and decreasing it by 1.\n\nAn array A is a zigzag array if either:\n\n\tEvery even-indexed element is greater than adjacent elements, ie. A[0] > A[1] < A[2] > A[3] < A[4] > ...\n\tOR, every odd-indexed element is greater than adjacent elements, ie. A[0] < A[1] > A[2] < A[3] > A[4] < ...\n\nReturn the minimum number of moves to transform the given array nums into a zigzag array.\n\n### Examples\nInput: nums = [1,2,3]\nOutput: 2\nInput: nums = [9,6,1,6,2]\nOutput: 4\n\n### Algorithm\nGreedy"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int movesToMakeZigzag(vector& nums) {\n vector ans(2);\n int n = nums.size();\n for (int i = 0; i < 2; ++i) {\n for (int j = i; j < n; j += 2) {\n int d = 0;\n if (j) d = max(d, nums[j] - nums[j - 1] + 1);\n if (j < n - 1) d = max(d, nums[j] - nums[j + 1] + 1);\n ans[i] += d;\n }\n }\n return min(ans[0], ans[1]);\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nGiven a list of phrases, generate a list of Before and After puzzles.\n\nA phrase is a string that consists of lowercase English letters and spaces only. No space appears in the start or the end of a phrase. There are no consecutive spaces in a phrase.\n\nBefore and After puzzles are phrases that are formed by merging two phrases where the last word of the first phrase is the same as the first word of the second phrase. Note that only the last word of the first phrase and the first word of the second phrase are merged in this process.\n\nReturn the Before and After puzzles that can be formed by every two phrases phrases[i] and phrases[j] where i != j. Note that the order of matching two phrases matters, we want to consider both orders.\n\nYou should return a list of distinct strings sorted lexicographically, after removing all duplicate phrases in the generated Before and After puzzles.\n\n### Examples\nInput: phrases = [\"writing code\",\"code rocks\"]\nOutput: [\"writing code rocks\"]\nInput: phrases = [\"mission statement\",\"a quick bite to eat\",\"a chip off the old block\",\"chocolate bar\",\"mission impossible\",\"a man on a mission\",\"block party\",\"eat my words\",\"bar of soap\"]\nOutput: [\"a chip off the old block party\",\"a man on a mission impossible\",\"a man on a mission statement\",\"a quick bite to eat my words\",\"chocolate bar of soap\"]\nInput: phrases = [\"a\",\"b\",\"a\"]\nOutput: [\"a\"]\nInput: phrases = [\"ab ba\",\"ba ab\",\"ab ba\"]\nOutput: [\"ab ba ab\",\"ba ab ba\"]\n\n### Algorithm\nSorting"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n vector beforeAndAfterPuzzles(vector& phrases) {\n int n = phrases.size();\n pair ps[n];\n for (int i = 0; i < n; ++i) {\n int j = phrases[i].find(' ');\n if (j == string::npos) {\n ps[i] = {phrases[i], phrases[i]};\n } else {\n int k = phrases[i].rfind(' ');\n ps[i] = {phrases[i].substr(0, j), phrases[i].substr(k + 1)};\n }\n }\n unordered_set s;\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < n; ++j) {\n if (i != j && ps[i].second == ps[j].first) {\n s.insert(phrases[i] + phrases[j].substr(ps[i].second.size()));\n }\n }\n }\n vector ans(s.begin(), s.end());\n sort(ans.begin(), ans.end());\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nA social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller time chunks based on a certain frequency (every minute, hour, or day).\n\nFor example, the period [10, 10000] (in seconds) would be partitioned into the following time chunks with these frequencies:\n\n\tEvery minute (60-second chunks): [10,69], [70,129], [130,189], ..., [9970,10000]\n\tEvery hour (3600-second chunks): [10,3609], [3610,7209], [7210,10000]\n\tEvery day (86400-second chunks): [10,10000]\n\nNotice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period (10000 in the above example).\n\nDesign and implement an API to help the company with their analysis.\n\nImplement the TweetCounts class:\n\n\tTweetCounts() Initializes the TweetCounts object.\n\tvoid recordTweet(String tweetName, int time) Stores the tweetName at the recorded time (in seconds).\n\tList getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime) Returns a list of integers representing the number of tweets with tweetName in each time chunk for the given period of time [startTime, endTime] (in seconds) and frequency freq.\n\t\n\t\tfreq is one of \"minute\", \"hour\", or \"day\" representing a frequency of every minute, hour, or day respectively.\n\n### Examples\n\n### Algorithm\nBinary Search"}, {"role": "assistant", "content": "```cpp\nclass TweetCounts {\npublic:\n TweetCounts() {\n }\n\n void recordTweet(string tweetName, int time) {\n data[tweetName].insert(time);\n }\n\n vector getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime) {\n int f = 60;\n if (freq == \"hour\")\n f = 3600;\n else if (freq == \"day\")\n f = 86400;\n vector ans((endTime - startTime) / f + 1);\n auto l = data[tweetName].lower_bound(startTime);\n auto r = data[tweetName].upper_bound(endTime);\n for (; l != r; ++l) {\n ++ans[(*l - startTime) / f];\n }\n return ans;\n }\n\nprivate:\n unordered_map> data;\n};\n\n/**\n * Your TweetCounts object will be instantiated and called as such:\n * TweetCounts* obj = new TweetCounts();\n * obj->recordTweet(tweetName,time);\n * vector param_2 = obj->getTweetCountsPerFrequency(freq,tweetName,startTime,endTime);\n */\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nGiven a string s consisting only of characters a, b and c.\n\nReturn the number of substrings containing at least one occurrence of all these characters a, b and c.\n\n### Examples\nInput: s = \"abcabc\"\nOutput: 10\nInput: s = \"aaacb\"\nOutput: 3\nInput: s = \"abc\"\nOutput: 1\n\n### Algorithm\nSliding Window"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int numberOfSubstrings(string s) {\n int ans = 0, l = 0;\n int cnt[3] = {0, 0, 0};\n for (int r = 0; r < (int) s.size(); r++) {\n cnt[s[r] - 'a']++;\n while (cnt[0] && cnt[1] && cnt[2]) {\n cnt[s[l] - 'a']--;\n l++;\n }\n ans += l;\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nGiven a binary tree where each path going from the root to any leaf form a valid sequence, check if a given string is a valid sequence in such binary tree. \n\nWe get the given string from the concatenation of an array of integers arr and the concatenation of all values of the nodes along a path results in a sequence in the given binary tree.\n\n### Examples\n\n### Algorithm\nDFS"}, {"role": "assistant", "content": "```cpp\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n bool isValidSequence(TreeNode* root, vector& arr) {\n function dfs = [&](TreeNode* root, int u) -> bool {\n if (!root || root->val != arr[u]) return false;\n if (u == arr.size() - 1) return !root->left && !root->right;\n return dfs(root->left, u + 1) || dfs(root->right, u + 1);\n };\n return dfs(root, 0);\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYour country has 109 lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake that is full of water, there will be a flood. Your goal is to avoid floods in any lake.\n\nGiven an integer array rains where:\n\n\trains[i] > 0 means there will be rains over the rains[i] lake.\n\trains[i] == 0 means there are no rains this day and you must choose one lake this day and dry it.\n\nReturn an array ans where:\n\n\tans.length == rains.length\n\tans[i] == -1 if rains[i] > 0.\n\tans[i] is the lake you choose to dry in the ith day if rains[i] == 0.\n\nIf there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array.\n\nNotice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes.\n\n### Examples\nInput: rains = [1,2,3,4]\nOutput: [-1,-1,-1,-1]\nInput: rains = [1,2,0,0,2,1]\nOutput: [-1,-1,2,1,-1,-1]\nInput: rains = [1,2,0,1,2]\nOutput: []\n\n### Algorithm\nGreedy"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n vector avoidFlood(vector& rains) {\n int n = rains.size();\n vector ans(n, -1);\n set sunny;\n unordered_map rainy;\n for (int i = 0; i < n; ++i) {\n int v = rains[i];\n if (v) {\n if (rainy.count(v)) {\n auto it = sunny.upper_bound(rainy[v]);\n if (it == sunny.end()) {\n return {};\n }\n ans[*it] = v;\n sunny.erase(it);\n }\n rainy[v] = i;\n } else {\n sunny.insert(i);\n ans[i] = 1;\n }\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a prerequisite relationship between course prevCoursei and course nextCoursei: course prevCoursei has to be taken before course nextCoursei. Also, you are given the integer k.\n\nIn one semester, you can take at most k courses as long as you have taken all the prerequisites in the previous semesters for the courses you are taking.\n\nReturn the minimum number of semesters needed to take all courses. The testcases will be generated such that it is possible to take every course.\n\n### Examples\nInput: n = 4, relations = [[2,1],[3,1],[1,4]], k = 2\nOutput: 3\nInput: n = 5, relations = [[2,1],[3,1],[4,1],[1,5]], k = 2\nOutput: 4\n\n### Algorithm\nDynamic Programming"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int minNumberOfSemesters(int n, vector>& relations, int k) {\n vector d(n + 1);\n for (auto& e : relations) {\n d[e[1]] |= 1 << e[0];\n }\n queue> q;\n q.push({0, 0});\n unordered_set vis{{0}};\n while (!q.empty()) {\n auto [cur, t] = q.front();\n q.pop();\n if (cur == (1 << (n + 1)) - 2) {\n return t;\n }\n int nxt = 0;\n for (int i = 1; i <= n; ++i) {\n if ((cur & d[i]) == d[i]) {\n nxt |= 1 << i;\n }\n }\n nxt ^= cur;\n if (__builtin_popcount(nxt) <= k) {\n if (!vis.count(nxt | cur)) {\n vis.insert(nxt | cur);\n q.push({nxt | cur, t + 1});\n }\n } else {\n int x = nxt;\n while (nxt) {\n if (__builtin_popcount(nxt) == k && !vis.count(nxt | cur)) {\n vis.insert(nxt | cur);\n q.push({nxt | cur, t + 1});\n }\n nxt = (nxt - 1) & x;\n }\n }\n }\n return 0;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.\n\nReturn the shuffled string.\n\n### Examples\nInput: s = \"codeleet\", indices = [4,5,6,7,0,2,1,3]\nOutput: \"leetcode\"\nInput: s = \"abc\", indices = [0,1,2]\nOutput: \"abc\"\n\n### Algorithm\nMath"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n string restoreString(string s, vector& indices) {\n int n = s.size();\n string ans(n, 0);\n for (int i = 0; i < n; ++i) {\n ans[indices[i]] = s[i];\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nGiven an array of positive integers arr, return the sum of all possible odd-length subarrays of arr.\n\nA subarray is a contiguous subsequence of the array.\n\n### Examples\nInput: arr = [1,4,2,5,3]\nOutput: 58\nExplanation: The odd-length subarrays of arr and their sums are:\n[1] = 1\n[4] = 4\n[2] = 2\n[5] = 5\n[3] = 3\n[1,4,2] = 7\n[4,2,5] = 11\n[2,5,3] = 10\n[1,4,2,5,3] = 15\nIf we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58\nInput: arr = [1,2]\nOutput: 3\nExplanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.\nInput: arr = [10,11,12]\nOutput: 66\n\n### Algorithm\nDynamic Programming"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int sumOddLengthSubarrays(vector& arr) {\n int ans = 0, f = 0, g = 0;\n for (int i = 0; i < arr.size(); ++i) {\n int ff = g + arr[i] * (i / 2 + 1);\n int gg = i ? f + arr[i] * ((i + 1) / 2) : 0;\n f = ff;\n g = gg;\n ans += f;\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nWe have an array of integers, nums, and an array of requests where requests[i] = [starti, endi]. The ith request asks for the sum of nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]. Both starti and endi are 0-indexed.\n\nReturn the maximum total sum of all requests among all permutations of nums.\n\nSince the answer may be too large, return it modulo 109 + 7.\n\n### Examples\nInput: nums = [1,2,3,4,5], requests = [[1,3],[0,1]]\nOutput: 19\nInput: nums = [1,2,3,4,5,6], requests = [[0,1]]\nOutput: 11\nInput: nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]]\nOutput: 47\n\n### Algorithm\nGreedy"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int maxSumRangeQuery(vector& nums, vector>& requests) {\n int n = nums.size();\n int d[n];\n memset(d, 0, sizeof(d));\n for (auto& req : requests) {\n int l = req[0], r = req[1];\n d[l]++;\n if (r + 1 < n) {\n d[r + 1]--;\n }\n }\n for (int i = 1; i < n; ++i) {\n d[i] += d[i - 1];\n }\n sort(nums.begin(), nums.end());\n sort(d, d + n);\n long long ans = 0;\n const int mod = 1e9 + 7;\n for (int i = 0; i < n; ++i) {\n ans = (ans + 1LL * nums[i] * d[i]) % mod;\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given a string s consisting only of characters 'a' and 'b'​​​​.\n\nYou can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'.\n\nReturn the minimum number of deletions needed to make s balanced.\n\n### Examples\nInput: s = \"aababbab\"\nOutput: 2\nInput: s = \"bbaaaaabb\"\nOutput: 2\n\n### Algorithm\nDynamic Programming"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int minimumDeletions(string s) {\n int lb = 0, ra = count(s.begin(), s.end(), 'a');\n int ans = ra;\n for (char& c : s) {\n ra -= c == 'a';\n ans = min(ans, lb + ra);\n lb += c == 'b';\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nThere are n buildings in a line. You are given an integer array heights of size n that represents the heights of the buildings in the line.\n\nThe ocean is to the right of the buildings. A building has an ocean view if the building can see the ocean without obstructions. Formally, a building has an ocean view if all the buildings to its right have a smaller height.\n\nReturn a list of indices (0-indexed) of buildings that have an ocean view, sorted in increasing order.\n\n### Examples\nInput: heights = [4,2,3,1]\nOutput: [0,2,3]\nInput: heights = [4,3,2,1]\nOutput: [0,1,2,3]\nInput: heights = [1,3,2,4]\nOutput: [3]\n\n### Algorithm\nArray"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n vector findBuildings(vector& heights) {\n vector ans;\n int mx = 0;\n for (int i = heights.size() - 1; ~i; --i) {\n if (heights[i] > mx) {\n ans.push_back(i);\n mx = heights[i];\n }\n }\n reverse(ans.begin(), ans.end());\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given an array nums​​​ and an integer k​​​​​. The XOR of a segment [left, right] where left <= right is the XOR of all the elements with indices between left and right, inclusive: nums[left] XOR nums[left+1] XOR ... XOR nums[right].\n\nReturn the minimum number of elements to change in the array such that the XOR of all segments of size k​​​​​​ is equal to zero.\n\n### Examples\nInput: nums = [1,2,0,3,0], k = 1\nOutput: 3\nExplanation: Modify the array from [1,2,0,3,0] to from [0,0,0,0,0].\nInput: nums = [3,4,5,2,1,7,3,4,7], k = 3\nOutput: 3\nExplanation: Modify the array from [3,4,5,2,1,7,3,4,7] to [3,4,7,3,4,7,3,4,7].\nInput: nums = [1,2,4,1,2,5,1,2,6], k = 3\nOutput: 3\nExplanation: Modify the array from [1,2,4,1,2,5,1,2,6] to [1,2,3,1,2,3,1,2,3].\n\n### Algorithm\nDynamic Programming"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int minChanges(vector& nums, int k) {\n int n = 1 << 10;\n unordered_map cnt[k];\n vector size(k);\n for (int i = 0; i < nums.size(); ++i) {\n cnt[i % k][nums[i]]++;\n size[i % k]++;\n }\n vector f(n, 1 << 30);\n f[0] = 0;\n for (int i = 0; i < k; ++i) {\n int mi = *min_element(f.begin(), f.end());\n vector g(n, mi + size[i]);\n for (int j = 0; j < n; ++j) {\n for (auto& [v, c] : cnt[i]) {\n g[j] = min(g[j], f[j ^ v] + size[i] - c);\n }\n }\n f = move(g);\n }\n return f[0];\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given an array of integers nums (0-indexed) and an integer k.\n\nThe score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j.\n\nReturn the maximum possible score of a good subarray.\n\n### Examples\nInput: nums = [1,4,3,7,4,5], k = 3\nOutput: 15\nInput: nums = [5,5,4,5,4,1,1,1], k = 0\nOutput: 20\n\n### Algorithm\nTwo Pointers"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int maximumScore(vector& nums, int k) {\n int n = nums.size();\n vector left(n, -1);\n vector right(n, n);\n stack stk;\n for (int i = 0; i < n; ++i) {\n int v = nums[i];\n while (!stk.empty() && nums[stk.top()] >= v) {\n stk.pop();\n }\n if (!stk.empty()) {\n left[i] = stk.top();\n }\n stk.push(i);\n }\n stk = stack();\n for (int i = n - 1; i >= 0; --i) {\n int v = nums[i];\n while (!stk.empty() && nums[stk.top()] > v) {\n stk.pop();\n }\n if (!stk.empty()) {\n right[i] = stk.top();\n }\n stk.push(i);\n }\n int ans = 0;\n for (int i = 0; i < n; ++i) {\n if (left[i] + 1 <= k && k <= right[i] - 1) {\n ans = max(ans, nums[i] * (right[i] - left[i] - 1));\n }\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given an array of integers nums (0-indexed) and an integer k.\n\nThe score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j.\n\nReturn the maximum possible score of a good subarray.\n\n### Examples\nInput: nums = [1,4,3,7,4,5], k = 3\nOutput: 15\nInput: nums = [5,5,4,5,4,1,1,1], k = 0\nOutput: 20\n\n### Algorithm\nTwo Pointers"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int maximumScore(vector& nums, int k) {\n int maxScore = nums[k], minNum = nums[k]; // Base case.\n\n int leftIdx = k, rightIdx = k;\n\n while (0 < leftIdx || rightIdx < nums.size() - 1) {\n if (leftIdx == 0) { // Can only go right.\n rightIdx++;\n minNum = min(minNum, nums[rightIdx]);\n }\n\n else if (rightIdx == nums.size() - 1) { // Can only go left.\n leftIdx--;\n minNum = min(minNum, nums[leftIdx]);\n }\n\n else { // Can go bidirectional.\n if (nums[leftIdx - 1] >= nums[rightIdx + 1]) {\n leftIdx--;\n minNum = min(minNum, nums[leftIdx]);\n }\n\n else {\n rightIdx++;\n minNum = min(minNum, nums[rightIdx]);\n }\n }\n\n int score = minNum * (rightIdx + 1 - leftIdx);\n maxScore = max(maxScore, score);\n }\n\n return maxScore;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given nums, an array of positive integers of size 2 * n. You must perform n operations on this array.\n\nIn the ith operation (1-indexed), you will:\n\n\tChoose two elements, x and y.\n\tReceive a score of i * gcd(x, y).\n\tRemove x and y from nums.\n\nReturn the maximum score you can receive after performing n operations.\n\nThe function gcd(x, y) is the greatest common divisor of x and y.\n\n### Examples\nInput: nums = [1,2]\nOutput: 1\nInput: nums = [3,4,6,8]\nOutput: 11\nInput: nums = [1,2,3,4,5,6]\nOutput: 14\n\n### Algorithm\nDynamic Programming"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int maxScore(vector& nums) {\n int m = nums.size();\n int g[m][m];\n for (int i = 0; i < m; ++i) {\n for (int j = i + 1; j < m; ++j) {\n g[i][j] = gcd(nums[i], nums[j]);\n }\n }\n int f[1 << m];\n memset(f, 0, sizeof f);\n for (int k = 0; k < 1 << m; ++k) {\n int cnt = __builtin_popcount(k);\n if (cnt % 2 == 0) {\n for (int i = 0; i < m; ++i) {\n if (k >> i & 1) {\n for (int j = i + 1; j < m; ++j) {\n if (k >> j & 1) {\n f[k] = max(f[k], f[k ^ (1 << i) ^ (1 << j)] + cnt / 2 * g[i][j]);\n }\n }\n }\n }\n }\n }\n return f[(1 << m) - 1];\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given a positive integer primeFactors. You are asked to construct a positive integer n that satisfies the following conditions:\n\n The number of prime factors of n (not necessarily distinct) is at most primeFactors.\n\n The number of nice divisors of n is maximized. Note that a divisor of n is nice if it is divisible by every prime factor of n. For example, if n = 12, then its prime factors are [2,2,3], then 6 and 12 are nice divisors, while 3 and 4 are not.\n\nReturn the number of nice divisors of n. Since that number can be too large, return it modulo 109 + 7.\n\nNote that a prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. The prime factors of a number n is a list of prime numbers such that their product equals n.\n\n### Examples\nInput: primeFactors = 5\nOutput: 6\nInput: primeFactors = 8\nOutput: 18\n\n### Algorithm\nMath"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int maxNiceDivisors(int primeFactors) {\n if (primeFactors < 4) {\n return primeFactors;\n }\n const int mod = 1e9 + 7;\n auto qpow = [&](long long a, long long n) {\n long long ans = 1;\n for (; n; n >>= 1) {\n if (n & 1) {\n ans = ans * a % mod;\n }\n a = a * a % mod;\n }\n return (int) ans;\n };\n if (primeFactors % 3 == 0) {\n return qpow(3, primeFactors / 3);\n }\n if (primeFactors % 3 == 1) {\n return qpow(3, primeFactors / 3 - 1) * 4L % mod;\n }\n return qpow(3, primeFactors / 3) * 2 % mod;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given n​​​​​​ tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where tasks[i] = [enqueueTimei, processingTimei] means that the i​​​​​​th​​​​ task will be available to process at enqueueTimei and will take processingTimei to finish processing.\n\nYou have a single-threaded CPU that can process at most one task at a time and will act in the following way:\n\n\tIf the CPU is idle and there are no available tasks to process, the CPU remains idle.\n\tIf the CPU is idle and there are available tasks, the CPU will choose the one with the shortest processing time. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.\n\tOnce a task is started, the CPU will process the entire task without stopping.\n\tThe CPU can finish a task then start a new one instantly.\n\nReturn the order in which the CPU will process the tasks.\n\n### Examples\nInput: tasks = [[1,2],[2,4],[3,2],[4,1]]\nOutput: [0,2,3,1]\nExplanation: The events go as follows: \n- At time = 1, task 0 is available to process. Available tasks = {0}.\n- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.\n- At time = 2, task 1 is available to process. Available tasks = {1}.\n- At time = 3, task 2 is available to process. Available tasks = {1, 2}.\n- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.\n- At time = 4, task 3 is available to process. Available tasks = {1, 3}.\n- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.\n- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.\n- At time = 10, the CPU finishes task 1 and becomes idle.\nInput: tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]\nOutput: [4,3,2,0,1]\nExplanation: The events go as follows:\n- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.\n- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.\n- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.\n- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.\n- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.\n- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.\n- At time = 40, the CPU finishes task 1 and becomes idle.\n\n### Algorithm\nSorting"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n vector getOrder(vector>& tasks) {\n int n = 0;\n for (auto& task : tasks) task.push_back(n++);\n sort(tasks.begin(), tasks.end());\n using pii = pair;\n priority_queue, greater> q;\n int i = 0;\n long long t = 0;\n vector ans;\n while (!q.empty() || i < n) {\n if (q.empty()) t = max(t, (long long) tasks[i][0]);\n while (i < n && tasks[i][0] <= t) {\n q.push({tasks[i][1], tasks[i][2]});\n ++i;\n }\n auto [pt, j] = q.top();\n q.pop();\n ans.push_back(j);\n t += pt;\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given two non-increasing 0-indexed integer arrays nums1​​​​​​ and nums2​​​​​​.\n\nA pair of indices (i, j), where 0 <= i < nums1.length and 0 <= j < nums2.length, is valid if both i <= j and nums1[i] <= nums2[j]. The distance of the pair is j - i​​​​.\n\nReturn the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0.\n\nAn array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length.\n\n### Examples\nInput: nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]\nOutput: 2\nInput: nums1 = [2,2,2], nums2 = [10,10,1]\nOutput: 1\nInput: nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]\nOutput: 2\n\n### Algorithm\nTwo Pointers"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int maxDistance(vector& nums1, vector& nums2) {\n int m = nums1.size(), n = nums2.size();\n int ans = 0;\n for (int i = 0, j = 0; i < m; ++i) {\n while (j < n && nums1[i] <= nums2[j]) {\n ++j;\n }\n ans = max(ans, j - i - 1);\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given an m x n integer matrix grid​​​.\n\nA rhombus sum is the sum of the elements that form the border of a regular rhombus shape in grid​​​. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding colored cells that should be included in each rhombus sum:\n\nNote that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner.\n\nReturn the biggest three distinct rhombus sums in the grid in descending order. If there are less than three distinct values, return all of them.\n\n### Examples\nInput: grid = [[3,4,5,1,3],[3,3,4,2,3],[20,30,200,40,10],[1,5,5,4,1],[4,3,2,2,5]]\nOutput: [228,216,211]\nInput: grid = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [20,9,8]\nInput: grid = [[7,7,7]]\nOutput: [7]\n\n### Algorithm\nBrute Force"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n vector getBiggestThree(vector>& grid) {\n int m = grid.size(), n = grid[0].size();\n vector> s1(m + 1, vector(n + 2));\n vector> s2(m + 1, vector(n + 2));\n for (int i = 1; i <= m; ++i) {\n for (int j = 1; j <= n; ++j) {\n s1[i][j] = s1[i - 1][j - 1] + grid[i - 1][j - 1];\n s2[i][j] = s2[i - 1][j + 1] + grid[i - 1][j - 1];\n }\n }\n set ss;\n for (int i = 1; i <= m; ++i) {\n for (int j = 1; j <= n; ++j) {\n int l = min({i - 1, m - i, j - 1, n - j});\n ss.insert(grid[i - 1][j - 1]);\n for (int k = 1; k <= l; ++k) {\n int a = s1[i + k][j] - s1[i][j - k];\n int b = s1[i][j + k] - s1[i - k][j];\n int c = s2[i][j - k] - s2[i - k][j];\n int d = s2[i + k][j] - s2[i][j + k];\n ss.insert(a + b + c + d - grid[i + k - 1][j - 1] + grid[i - k - 1][j - 1]);\n }\n while (ss.size() > 3) {\n ss.erase(ss.begin());\n }\n }\n }\n return vector(ss.rbegin(), ss.rend());\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nGiven an integer array nums of length n and an integer k, return the kth smallest subarray sum.\n\nA subarray is defined as a non-empty contiguous sequence of elements in an array. A subarray sum is the sum of all elements in the subarray.\n\n### Examples\nInput: nums = [2,1,3], k = 4\nOutput: 3\nExplanation: The subarrays of [2,1,3] are:\n- [2] with sum 2\n- [1] with sum 1\n- [3] with sum 3\n- [2,1] with sum 3\n- [1,3] with sum 4\n- [2,1,3] with sum 6 \nOrdering the sums from smallest to largest gives 1, 2, 3, 3, 4, 6. The 4th smallest is 3.\nInput: nums = [3,3,5,5], k = 7\nOutput: 10\nExplanation: The subarrays of [3,3,5,5] are:\n- [3] with sum 3\n- [3] with sum 3\n- [5] with sum 5\n- [5] with sum 5\n- [3,3] with sum 6\n- [3,5] with sum 8\n- [5,5] with sum 10\n- [3,3,5], with sum 11\n- [3,5,5] with sum 13\n- [3,3,5,5] with sum 16\nOrdering the sums from smallest to largest gives 3, 3, 5, 5, 6, 8, 10, 11, 13, 16. The 7th smallest is 10.\n\n### Algorithm\nTwo Pointers"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int kthSmallestSubarraySum(vector& nums, int k) {\n int l = 1 << 30, r = 0;\n for (int& x : nums) {\n l = min(l, x);\n r += x;\n }\n auto f = [&](int s) {\n int cnt = 0, t = 0;\n for (int i = 0, j = 0; i < nums.size(); ++i) {\n t += nums[i];\n while (t > s) {\n t -= nums[j++];\n }\n cnt += i - j + 1;\n }\n return cnt;\n };\n while (l < r) {\n int mid = (l + r) >> 1;\n if (f(mid) >= k) {\n r = mid;\n } else {\n l = mid + 1;\n }\n }\n return l;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nGiven a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it.\n\nA zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).\n\n### Examples\nInput: nums = [0,2,1,5,3,4]\nOutput: [0,1,2,4,5,3]\nExplanation: The array ans is built as follows: \nans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]\n = [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]]\n = [0,1,2,4,5,3]\nInput: nums = [5,0,1,2,3,4]\nOutput: [4,5,0,1,2,3]\n\n### Algorithm\nMath"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n vector buildArray(vector& nums) {\n vector ans;\n for (int& num : nums) {\n ans.push_back(nums[num]);\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given a binary string binary. A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of \"0\").\n\nFind the number of unique good subsequences of binary.\n\n\tFor example, if binary = \"001\", then all the good subsequences are [\"0\", \"0\", \"1\"], so the unique good subsequences are \"0\" and \"1\". Note that subsequences \"00\", \"01\", and \"001\" are not good because they have leading zeros.\n\nReturn the number of unique good subsequences of binary. Since the answer may be very large, return it modulo 109 + 7.\n\nA subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.\n\n### Examples\nInput: binary = \"001\"\nOutput: 2\nInput: binary = \"11\"\nOutput: 2\nInput: binary = \"101\"\nOutput: 5\n\n### Algorithm\nDynamic Programming"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int numberOfUniqueGoodSubsequences(string binary) {\n const int mod = 1e9 + 7;\n int f = 0, g = 0;\n int ans = 0;\n for (char& c : binary) {\n if (c == '0') {\n g = (g + f) % mod;\n ans = 1;\n } else {\n f = (f + g + 1) % mod;\n }\n }\n ans = (ans + f + g) % mod;\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given an integer array nums. We call a subset of nums good if its product can be represented as a product of one or more distinct prime numbers.\n\n\tFor example, if nums = [1, 2, 3, 4]:\n\n \n \t[2, 3], [1, 2, 3], and [1, 3] are good subsets with products 6 = 2*3, 6 = 2*3, and 3 = 3 respectively.\n \t[1, 4] and [4] are not good subsets with products 4 = 2*2 and 4 = 2*2 respectively.\n \n \n\nReturn the number of different good subsets in nums modulo 109 + 7.\n\nA subset of nums is any array that can be obtained by deleting some (possibly none or all) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.\n\n### Examples\nInput: nums = [1,2,3,4]\nOutput: 6\nInput: nums = [4,2,3,15]\nOutput: 5\n\n### Algorithm\nDynamic Programming"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int numberOfGoodSubsets(vector& nums) {\n int primes[10] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};\n int cnt[31]{};\n for (int& x : nums) {\n ++cnt[x];\n }\n int n = 10;\n const int mod = 1e9 + 7;\n vector f(1 << n);\n f[0] = 1;\n for (int i = 0; i < cnt[1]; ++i) {\n f[0] = f[0] * 2 % mod;\n }\n for (int x = 2; x < 31; ++x) {\n if (cnt[x] == 0 || x % 4 == 0 || x % 9 == 0 || x % 25 == 0) {\n continue;\n }\n int mask = 0;\n for (int i = 0; i < n; ++i) {\n if (x % primes[i] == 0) {\n mask |= 1 << i;\n }\n }\n for (int state = (1 << n) - 1; state; --state) {\n if ((state & mask) == mask) {\n f[state] = (f[state] + 1LL * cnt[x] * f[state ^ mask]) % mod;\n }\n }\n }\n long long ans = 0;\n for (int i = 1; i < 1 << n; ++i) {\n ans = (ans + f[i]) % mod;\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given a 2D integer grid of size m x n and an integer x. In one operation, you can add x to or subtract x from any element in the grid.\n\nA uni-value grid is a grid where all the elements of it are equal.\n\nReturn the minimum number of operations to make the grid uni-value. If it is not possible, return -1.\n\n### Examples\nInput: grid = [[2,4],[6,8]], x = 2\nOutput: 4\nInput: grid = [[1,5],[2,3]], x = 1\nOutput: 5\nInput: grid = [[1,2],[3,4]], x = 2\nOutput: -1\n\n### Algorithm\nGreedy"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int minOperations(vector>& grid, int x) {\n int m = grid.size(), n = grid[0].size();\n int mod = grid[0][0] % x;\n int nums[m * n];\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n if (grid[i][j] % x != mod) {\n return -1;\n }\n nums[i * n + j] = grid[i][j];\n }\n }\n sort(nums, nums + m * n);\n int mid = nums[(m * n) >> 1];\n int ans = 0;\n for (int v : nums) {\n ans += abs(v - mid) / x;\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given an integer array digits, where each element is a digit. The array may contain duplicates.\n\nYou need to find all the unique integers that follow the given requirements:\n\n\tThe integer consists of the concatenation of three elements from digits in any arbitrary order.\n\tThe integer does not have leading zeros.\n\tThe integer is even.\n\nFor example, if the given digits were [1, 2, 3], integers 132 and 312 follow the requirements.\n\nReturn a sorted array of the unique integers.\n\n### Examples\nInput: digits = [2,1,3,0]\nOutput: [102,120,130,132,210,230,302,310,312,320]\nInput: digits = [2,2,8,8,2]\nOutput: [222,228,282,288,822,828,882]\nInput: digits = [3,7,5]\nOutput: []\n\n### Algorithm\nSorting"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n vector findEvenNumbers(vector& digits) {\n int cnt[10]{};\n for (int x : digits) {\n ++cnt[x];\n }\n vector ans;\n for (int x = 100; x < 1000; x += 2) {\n int cnt1[10]{};\n for (int y = x; y; y /= 10) {\n ++cnt1[y % 10];\n }\n bool ok = true;\n for (int i = 0; i < 10 && ok; ++i) {\n ok = cnt[i] >= cnt1[i];\n }\n if (ok) {\n ans.push_back(x);\n }\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nA scenic location is represented by its name and attractiveness score, where name is a unique string among all locations and score is an integer. Locations can be ranked from the best to the worst. The higher the score, the better the location. If the scores of two locations are equal, then the location with the lexicographically smaller name is better.\n\nYou are building a system that tracks the ranking of locations with the system initially starting with no locations. It supports:\n\n\tAdding scenic locations, one at a time.\n\tQuerying the ith best location of all locations already added, where i is the number of times the system has been queried (including the current query).\n\t\n\t\tFor example, when the system is queried for the 4th time, it returns the 4th best location of all locations already added.\n\t\n\t\n\nNote that the test data are generated so that at any time, the number of queries does not exceed the number of locations added to the system.\n\nImplement the SORTracker class:\n\n\tSORTracker() Initializes the tracker system.\n\tvoid add(string name, int score) Adds a scenic location with name and score to the system.\n\tstring get() Queries and returns the ith best location, where i is the number of times this method has been invoked (including this invocation).\n\n### Examples\n\n### Algorithm\nHeap"}, {"role": "assistant", "content": "```cpp\n#include \n#include \nusing namespace __gnu_pbds;\n\ntemplate \nusing ordered_set = tree, rb_tree_tag, tree_order_statistics_node_update>;\n\nclass SORTracker {\npublic:\n SORTracker() {\n }\n\n void add(string name, int score) {\n st.insert({-score, name});\n }\n\n string get() {\n return st.find_by_order(++i)->second;\n }\n\nprivate:\n ordered_set> st;\n int i = -1;\n};\n\n/**\n * Your SORTracker object will be instantiated and called as such:\n * SORTracker* obj = new SORTracker();\n * obj->add(name,score);\n * string param_2 = obj->get();\n */\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given a 0-indexed string num of length n consisting of digits.\n\nReturn true if for every index i in the range 0 <= i < n, the digit i occurs num[i] times in num, otherwise return false.\n\n### Examples\nInput: num = \"1210\"\nOutput: true\nInput: num = \"030\"\nOutput: false\n\n### Algorithm\nHash Table"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n bool digitCount(string num) {\n int cnt[10]{};\n for (char& c : num) {\n ++cnt[c - '0'];\n }\n for (int i = 0; i < num.size(); ++i) {\n if (cnt[i] != num[i] - '0') {\n return false;\n }\n }\n return true;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given two strings s and sub. You are also given a 2D character array mappings where mappings[i] = [oldi, newi] indicates that you may perform the following operation any number of times:\n\n\tReplace a character oldi of sub with newi.\n\nEach character in sub cannot be replaced more than once.\n\nReturn true if it is possible to make sub a substring of s by replacing zero or more characters according to mappings. Otherwise, return false.\n\nA substring is a contiguous non-empty sequence of characters within a string.\n\n### Examples\nInput: s = \"fool3e7bar\", sub = \"leet\", mappings = [[\"e\",\"3\"],[\"t\",\"7\"],[\"t\",\"8\"]]\nOutput: true\nInput: s = \"fooleetbar\", sub = \"f00l\", mappings = [[\"o\",\"0\"]]\nOutput: false\nInput: s = \"Fool33tbaR\", sub = \"leetd\", mappings = [[\"e\",\"3\"],[\"t\",\"7\"],[\"t\",\"8\"],[\"d\",\"b\"],[\"p\",\"b\"]]\nOutput: true\n\n### Algorithm\nHash Table"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n bool matchReplacement(string s, string sub, vector>& mappings) {\n unordered_map> d;\n for (auto& e : mappings) {\n d[e[0]].insert(e[1]);\n }\n int m = s.size(), n = sub.size();\n for (int i = 0; i < m - n + 1; ++i) {\n bool ok = true;\n for (int j = 0; j < n && ok; ++j) {\n char a = s[i + j], b = sub[j];\n if (a != b && !d[b].count(a)) {\n ok = false;\n }\n }\n if (ok) {\n return true;\n }\n }\n return false;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nOn day 1, one person discovers a secret.\n\nYou are given an integer delay, which means that each person will share the secret with a new person every day, starting from delay days after discovering the secret. You are also given an integer forget, which means that each person will forget the secret forget days after discovering it. A person cannot share the secret on the same day they forgot it, or on any day afterwards.\n\nGiven an integer n, return the number of people who know the secret at the end of day n. Since the answer may be very large, return it modulo 109 + 7.\n\n### Examples\nInput: n = 6, delay = 2, forget = 4\nOutput: 5\nInput: n = 4, delay = 1, forget = 3\nOutput: 6\n\n### Algorithm\nDynamic Programming"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int peopleAwareOfSecret(int n, int delay, int forget) {\n const int mod = 1e9 + 7;\n int m = (n << 1) + 10;\n vector d(m), cnt(m);\n cnt[1] = 1;\n for (int i = 1; i <= n; i++) {\n if (cnt[i]) {\n d[i] = (d[i] + cnt[i]) % mod;\n d[i + forget] = (d[i + forget] - cnt[i] + mod) % mod;\n int nxt = i + delay;\n while (nxt < i + forget) {\n cnt[nxt] = (cnt[nxt] + cnt[i]) % mod;\n nxt++;\n }\n }\n }\n long long ans = 0;\n for (int i = 0; i <= n; i++) {\n ans += d[i];\n }\n return ans % mod;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given an n x n integer matrix grid.\n\nGenerate an integer matrix maxLocal of size (n - 2) x (n - 2) such that:\n\n\tmaxLocal[i][j] is equal to the largest value of the 3 x 3 matrix in grid centered around row i + 1 and column j + 1.\n\nIn other words, we want to find the largest value in every contiguous 3 x 3 matrix in grid.\n\nReturn the generated matrix.\n\n### Examples\nInput: grid = [[9,9,8,1],[5,6,2,6],[8,2,6,4],[6,2,2,2]]\nOutput: [[9,9],[8,6]]\nInput: grid = [[1,1,1,1,1],[1,1,1,1,1],[1,1,2,1,1],[1,1,1,1,1],[1,1,1,1,1]]\nOutput: [[2,2,2],[2,2,2],[2,2,2]]\n\n### Algorithm\nArray"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n vector> largestLocal(vector>& grid) {\n int n = grid.size();\n vector> ans(n - 2, vector(n - 2));\n for (int i = 0; i < n - 2; ++i) {\n for (int j = 0; j < n - 2; ++j) {\n for (int x = i; x <= i + 2; ++x) {\n for (int y = j; y <= j + 2; ++y) {\n ans[i][j] = max(ans[i][j], grid[x][y]);\n }\n }\n }\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given two non-negative integer arrays price and tastiness, both arrays have the same length n. You are also given two non-negative integers maxAmount and maxCoupons.\n\nFor every integer i in range [0, n - 1]:\n\n\tprice[i] describes the price of ith fruit.\n\ttastiness[i] describes the tastiness of ith fruit.\n\nYou want to purchase some fruits such that total tastiness is maximized and the total price does not exceed maxAmount.\n\nAdditionally, you can use a coupon to purchase fruit for half of its price (rounded down to the closest integer). You can use at most maxCoupons of such coupons.\n\nReturn the maximum total tastiness that can be purchased.\n\nNote that:\n\n\tYou can purchase each fruit at most once.\n\tYou can use coupons on some fruit at most once.\n\n### Examples\nInput: price = [10,20,20], tastiness = [5,8,8], maxAmount = 20, maxCoupons = 1\nOutput: 13\nInput: price = [10,15,7], tastiness = [5,8,20], maxAmount = 10, maxCoupons = 2\nOutput: 28\n\n### Algorithm\nMemoization"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int maxTastiness(vector& price, vector& tastiness, int maxAmount, int maxCoupons) {\n int n = price.size();\n memset(f, 0, sizeof f);\n function dfs;\n dfs = [&](int i, int j, int k) {\n if (i == n) return 0;\n if (f[i][j][k]) return f[i][j][k];\n int ans = dfs(i + 1, j, k);\n if (j >= price[i]) ans = max(ans, dfs(i + 1, j - price[i], k) + tastiness[i]);\n if (j >= price[i] / 2 && k) ans = max(ans, dfs(i + 1, j - price[i] / 2, k - 1) + tastiness[i]);\n f[i][j][k] = ans;\n return ans;\n };\n return dfs(0, maxAmount, maxCoupons);\n }\n\nprivate:\n int f[101][1001][6];\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given a string of length 5 called time, representing the current time on a digital clock in the format \"hh:mm\". The earliest possible time is \"00:00\" and the latest possible time is \"23:59\".\n\nIn the string time, the digits represented by the ? symbol are unknown, and must be replaced with a digit from 0 to 9.\n\nReturn an integer answer, the number of valid clock times that can be created by replacing every ? with a digit from 0 to 9.\n\n### Examples\nInput: time = \"?5:00\"\nOutput: 2\nInput: time = \"0?:0?\"\nOutput: 100\nInput: time = \"??:??\"\nOutput: 1440\n\n### Algorithm\nString"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int countTime(string time) {\n int ans = 0;\n for (int h = 0; h < 24; ++h) {\n for (int m = 0; m < 60; ++m) {\n char s[20];\n sprintf(s, \"%02d:%02d\", h, m);\n int ok = 1;\n for (int i = 0; i < 5; ++i) {\n if (s[i] != time[i] && time[i] != '?') {\n ok = 0;\n break;\n }\n }\n ans += ok;\n }\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nGiven an integer array nums of positive integers, return the average value of all even integers that are divisible by 3.\n\nNote that the average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.\n\n### Examples\nInput: nums = [1,3,6,10,12,15]\nOutput: 9\nInput: nums = [1,2,4,7,10]\nOutput: 0\n\n### Algorithm\nMath"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int averageValue(vector& nums) {\n int s = 0, n = 0;\n for (int x : nums) {\n if (x % 6 == 0) {\n s += x;\n ++n;\n }\n }\n return n == 0 ? 0 : s / n;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nThere exists an infinitely large grid. You are currently at point (1, 1), and you need to reach the point (targetX, targetY) using a finite number of steps.\n\nIn one step, you can move from point (x, y) to any one of the following points:\n\n\t(x, y - x)\n\t(x - y, y)\n\t(2 * x, y)\n\t(x, 2 * y)\n\nGiven two integers targetX and targetY representing the X-coordinate and Y-coordinate of your final position, return true if you can reach the point from (1, 1) using some number of steps, and false otherwise.\n\n### Examples\nInput: targetX = 6, targetY = 9\nOutput: false\nInput: targetX = 4, targetY = 7\nOutput: true\n\n### Algorithm\nMath"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n bool isReachable(int targetX, int targetY) {\n int x = gcd(targetX, targetY);\n return (x & (x - 1)) == 0;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given an integer array nums and an integer k.\n\nSplit the array into some number of non-empty subarrays. The cost of a split is the sum of the importance value of each subarray in the split.\n\nLet trimmed(subarray) be the version of the subarray where all numbers which appear only once are removed.\n\n\tFor example, trimmed([3,1,2,4,3,4]) = [3,4,3,4].\n\nThe importance value of a subarray is k + trimmed(subarray).length.\n\n\tFor example, if a subarray is [1,2,3,3,3,4,4], then trimmed([1,2,3,3,3,4,4]) = [3,3,3,4,4].The importance value of this subarray will be k + 5.\n\nReturn the minimum possible cost of a split of nums.\n\nA subarray is a contiguous non-empty sequence of elements within an array.\n\n### Examples\nInput: nums = [1,2,1,2,1,3,3], k = 2\nOutput: 8\nInput: nums = [1,2,1,2,1], k = 2\nOutput: 6\nInput: nums = [1,2,1,2,1], k = 5\nOutput: 10\n\n### Algorithm\nMemoization"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int minCost(vector& nums, int k) {\n int n = nums.size();\n int f[n];\n memset(f, 0, sizeof f);\n function dfs = [&](int i) {\n if (i >= n) {\n return 0;\n }\n if (f[i]) {\n return f[i];\n }\n int cnt[n];\n memset(cnt, 0, sizeof cnt);\n int one = 0;\n int ans = 1 << 30;\n for (int j = i; j < n; ++j) {\n int x = ++cnt[nums[j]];\n if (x == 1) {\n ++one;\n } else if (x == 2) {\n --one;\n }\n ans = min(ans, k + j - i + 1 - one + dfs(j + 1));\n }\n return f[i] = ans;\n };\n return dfs(0);\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given an array nums consisting of positive integers.\n\nYou are also given an integer array queries of size m. For the ith query, you want to make all of the elements of nums equal to queries[i]. You can perform the following operation on the array any number of times:\n\n\tIncrease or decrease an element of the array by 1.\n\nReturn an array answer of size m where answer[i] is the minimum number of operations to make all elements of nums equal to queries[i].\n\nNote that after each query the array is reset to its original state.\n\n### Examples\nInput: nums = [3,1,6,8], queries = [1,5]\nOutput: [14,10]\nInput: nums = [2,9,6,3], queries = [10]\nOutput: [20]\n\n### Algorithm\nBinary Search"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n vector minOperations(vector& nums, vector& queries) {\n sort(nums.begin(), nums.end());\n int n = nums.size();\n vector s(n + 1);\n for (int i = 0; i < n; ++i) {\n s[i + 1] = s[i] + nums[i];\n }\n vector ans;\n for (auto& x : queries) {\n int i = lower_bound(nums.begin(), nums.end(), x + 1) - nums.begin();\n long long t = s[n] - s[i] - 1LL * (n - i) * x;\n i = lower_bound(nums.begin(), nums.end(), x) - nums.begin();\n t += 1LL * x * i - s[i];\n ans.push_back(t);\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given a 0-indexed integer array nums representing the strength of some heroes. The power of a group of heroes is defined as follows:\n\n\tLet i0, i1, ... ,ik be the indices of the heroes in a group. Then, the power of this group is max(nums[i0], nums[i1], ... ,nums[ik])2 * min(nums[i0], nums[i1], ... ,nums[ik]).\n\nReturn the sum of the power of all non-empty groups of heroes possible. Since the sum could be very large, return it modulo 109 + 7.\n\n### Examples\nInput: nums = [2,1,4]\nOutput: 141\nInput: nums = [1,1,1]\nOutput: 7\n\n### Algorithm\nSorting"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int sumOfPower(vector& nums) {\n const int mod = 1e9 + 7;\n sort(nums.rbegin(), nums.rend());\n long long ans = 0, p = 0;\n for (long long x : nums) {\n ans = (ans + (x * x % mod) * x) % mod;\n ans = (ans + x * p % mod) % mod;\n p = (p * 2 + x * x % mod) % mod;\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given a root to a binary tree and an integer k. A node of this tree is called great enough if the followings hold:\n\n\tIts subtree has at least k nodes.\n\tIts value is greater than the value of at least k nodes in its subtree.\n\nReturn the number of nodes in this tree that are great enough.\n\nThe node u is in the subtree of the node v, if u == v or v is an ancestor of u.\n\n### Examples\nInput: root = [7,6,5,4,3,2,1], k = 2\nOutput: 3\nInput: root = [1,2,3], k = 1\nOutput: 0\nExplanation: Number the nodes from 1 to 3.\nThe values in the subtree of node 1: {1,2,3}. Since node.val == 1, there are no nodes having a smaller value than its value. So it's not great enough.\nThe values in the subtree of node 2: {2}. Since node.val == 2, there are no nodes having a smaller value than its value. So it's not great enough.\nThe values in the subtree of node 3: {3}. Since node.val == 3, there are no nodes having a smaller value than its value. So it's not great enough.\nSee the picture below for a better understanding.\nInput: root = [3,2,2], k = 2\nOutput: 1\nExplanation: Number the nodes from 1 to 3.\nThe values in the subtree of node 1: {2,2,3}. Since node.val == 3, there are 2 nodes having a smaller value than its value. So it's great enough.\nThe values in the subtree of node 2: {2}. Since node.val == 2, there are no nodes having a smaller value than its value. So it's not great enough.\nThe values in the subtree of node 3: {2}. Since node.val == 2, there are no nodes having a smaller value than its value. So it's not great enough.\nSee the picture below for a better understanding.\n\n### Algorithm\nDFS"}, {"role": "assistant", "content": "```cpp\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n int countGreatEnoughNodes(TreeNode* root, int k) {\n int ans = 0;\n function(TreeNode*)> dfs = [&](TreeNode* root) {\n if (!root) {\n return priority_queue();\n }\n auto left = dfs(root->left);\n auto right = dfs(root->right);\n while (right.size()) {\n left.push(right.top());\n right.pop();\n if (left.size() > k) {\n left.pop();\n }\n }\n if (left.size() == k && left.top() < root->val) {\n ++ans;\n }\n left.push(root->val);\n if (left.size() > k) {\n left.pop();\n }\n return left;\n };\n dfs(root);\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYour laptop keyboard is faulty, and whenever you type a character 'i' on it, it reverses the string that you have written. Typing other characters works as expected.\n\nYou are given a 0-indexed string s, and you type each character of s using your faulty keyboard.\n\nReturn the final string that will be present on your laptop screen.\n\n### Examples\nInput: s = \"string\"\nOutput: \"rtsng\"\nInput: s = \"poiinter\"\nOutput: \"ponter\"\n\n### Algorithm\nMath"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n string finalString(string s) {\n string t;\n for (char c : s) {\n if (c == 'i') {\n reverse(t.begin(), t.end());\n } else {\n t.push_back(c);\n }\n }\n return t;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou have a certain number of processors, each having 4 cores. The number of tasks to be executed is four times the number of processors. Each task must be assigned to a unique core, and each core can only be used once.\n\nYou are given an array processorTime representing the time each processor becomes available and an array tasks representing how long each task takes to complete. Return the minimum time needed to complete all tasks.\n\n### Examples\nInput: processorTime = [8,10], tasks = [2,2,3,1,8,7,4,5]\nOutput: 16\nInput: processorTime = [10,20], tasks = [2,3,1,2,5,8,4,3]\nOutput: 23\n\n### Algorithm\nGreedy"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int minProcessingTime(vector& processorTime, vector& tasks) {\n sort(processorTime.begin(), processorTime.end());\n sort(tasks.begin(), tasks.end());\n int ans = 0, i = tasks.size() - 1;\n for (int t : processorTime) {\n ans = max(ans, t + tasks[i]);\n i -= 4;\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given an m x n integer matrix mat and an integer k. The matrix rows are 0-indexed.\n\nThe following proccess happens k times:\n\n\tEven-indexed rows (0, 2, 4, ...) are cyclically shifted to the left.\n\n\tOdd-indexed rows (1, 3, 5, ...) are cyclically shifted to the right.\n\nReturn true if the final modified matrix after k steps is identical to the original matrix, and false otherwise.\n\n### Examples\nInput: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 4\nOutput: false\nInput: mat = [[1,2,1,2],[5,5,5,5],[6,3,6,3]], k = 2\nOutput: true\nInput: mat = [[2,2],[2,2]], k = 3\nOutput: true\n\n### Algorithm\nMath"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n bool areSimilar(vector>& mat, int k) {\n int m = mat.size(), n = mat[0].size();\n k %= n;\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n if (i % 2 == 1 && mat[i][j] != mat[i][(j + k) % n]) {\n return false;\n }\n if (i % 2 == 0 && mat[i][j] != mat[i][(j - k + n) % n]) {\n return false;\n }\n }\n }\n return true;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given an integer n and an array sick sorted in increasing order, representing positions of infected people in a line of n people.\n\nAt each step, one uninfected person adjacent to an infected person gets infected. This process continues until everyone is infected.\n\nAn infection sequence is the order in which uninfected people become infected, excluding those initially infected.\n\nReturn the number of different infection sequences possible, modulo 109+7.\n\n### Examples\nInput: n = 5, sick = [0,4]\nOutput: 4\nInput: n = 4, sick = [1]\nOutput: 3\n\n### Algorithm\nMath"}, {"role": "assistant", "content": "```cpp\nconst int MX = 1e5;\nconst int MOD = 1e9 + 7;\nint fac[MX + 1];\n\nauto init = [] {\n fac[0] = 1;\n for (int i = 1; i <= MX; ++i) {\n fac[i] = 1LL * fac[i - 1] * i % MOD;\n }\n return 0;\n}();\n\nint qpow(long long a, long long n) {\n long long ans = 1;\n for (; n > 0; n >>= 1) {\n if (n & 1) {\n ans = (ans * a) % MOD;\n }\n a = (a * a) % MOD;\n }\n return ans;\n}\n\nclass Solution {\npublic:\n int numberOfSequence(int n, vector& sick) {\n int m = sick.size();\n vector nums(m + 1);\n\n nums[0] = sick[0];\n nums[m] = n - sick[m - 1] - 1;\n for (int i = 1; i < m; i++) {\n nums[i] = sick[i] - sick[i - 1] - 1;\n }\n\n int s = accumulate(nums.begin(), nums.end(), 0);\n long long ans = fac[s];\n for (int x : nums) {\n if (x > 0) {\n ans = ans * qpow(fac[x], MOD - 2) % MOD;\n }\n }\n for (int i = 1; i < nums.size() - 1; ++i) {\n if (nums[i] > 1) {\n ans = ans * qpow(2, nums[i] - 1) % MOD;\n }\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given the head of a linked list of even length containing integers.\n\nEach odd-indexed node contains an odd integer and each even-indexed node contains an even integer.\n\nWe call each even-indexed node and its next node a pair, e.g., the nodes with indices 0 and 1 are a pair, the nodes with indices 2 and 3 are a pair, and so on.\n\nFor every pair, we compare the values of the nodes in the pair:\n\n\tIf the odd-indexed node is higher, the \"Odd\" team gets a point.\n\tIf the even-indexed node is higher, the \"Even\" team gets a point.\n\nReturn the name of the team with the higher points, if the points are equal, return \"Tie\".\n\n### Examples\n\n### Algorithm\nMath"}, {"role": "assistant", "content": "```cpp\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n string gameResult(ListNode* head) {\n int odd = 0, even = 0;\n for (; head != nullptr; head = head->next->next) {\n int a = head->val;\n int b = head->next->val;\n odd += a < b;\n even += a > b;\n }\n if (odd > even) {\n return \"Odd\";\n }\n if (odd < even) {\n return \"Even\";\n }\n return \"Tie\";\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given a string word and an integer k.\n\nWe consider word to be k-special if |freq(word[i]) - freq(word[j])| <= k for all indices i and j in the string.\n\nHere, freq(x) denotes the frequency of the character x in word, and |y| denotes the absolute value of y.\n\nReturn the minimum number of characters you need to delete to make word k-special.\n\n### Examples\n\n### Algorithm\nGreedy"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int minimumDeletions(string word, int k) {\n int freq[26]{};\n for (char& c : word) {\n ++freq[c - 'a'];\n }\n vector nums;\n for (int v : freq) {\n if (v) {\n nums.push_back(v);\n }\n }\n int n = word.size();\n int ans = n;\n auto f = [&](int v) {\n int ans = 0;\n for (int x : nums) {\n if (x < v) {\n ans += x;\n } else if (x > v + k) {\n ans += x - v - k;\n }\n }\n return ans;\n };\n for (int i = 0; i <= n; ++i) {\n ans = min(ans, f(i));\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given a string compressed representing a compressed version of a string. The format is a character followed by its frequency. For example, \"a3b1a1c2\" is a compressed version of the string \"aaabacc\".\n\nWe seek a better compression with the following conditions:\n\n\tEach character should appear only once in the compressed version.\n\tThe characters should be in alphabetical order.\n\nReturn the better compression of compressed.\n\nNote: In the better version of compression, the order of letters may change, which is acceptable.\n\n### Examples\nInput: compressed = \"a3c9b2c1\"\nOutput: \"a3b2c10\"\nInput: compressed = \"c2b3a1\"\nOutput: \"a1b3c2\"\nInput: compressed = \"a2b4c1\"\nOutput: \"a2b4c1\"\n\n### Algorithm\nTwo Pointers"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n string betterCompression(string compressed) {\n map cnt;\n int i = 0;\n int n = compressed.length();\n while (i < n) {\n char c = compressed[i];\n int j = i + 1;\n int x = 0;\n while (j < n && isdigit(compressed[j])) {\n x = x * 10 + (compressed[j] - '0');\n j++;\n }\n cnt[c] += x;\n i = j;\n }\n stringstream ans;\n for (const auto& entry : cnt) {\n ans << entry.first << entry.second;\n }\n return ans.str();\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nThere is a 50 x 50 chessboard with one knight and some pawns on it. You are given two integers kx and ky where (kx, ky) denotes the position of the knight, and a 2D array positions where positions[i] = [xi, yi] denotes the position of the pawns on the chessboard.\n\nAlice and Bob play a turn-based game, where Alice goes first. In each player's turn:\n\n\tThe player selects a pawn that still exists on the board and captures it with the knight in the fewest possible moves. Note that the player can select any pawn, it might not be one that can be captured in the least number of moves.\n\tIn the process of capturing the selected pawn, the knight may pass other pawns without capturing them. Only the selected pawn can be captured in this turn.\n\nAlice is trying to maximize the sum of the number of moves made by both players until there are no more pawns on the board, whereas Bob tries to minimize them.\n\nReturn the maximum total number of moves made during the game that Alice can achieve, assuming both players play optimally.\n\nNote that in one move, a chess knight has eight possible positions it can move to, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.\n\n### Examples\nInput: kx = 1, ky = 1, positions = [[0,0]]\nOutput: 4\nInput: kx = 0, ky = 2, positions = [[1,1],[2,2],[3,3]]\nOutput: 8\nInput: kx = 0, ky = 0, positions = [[1,2],[2,4]]\nOutput: 3\n\n### Algorithm\nMemoization"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int maxMoves(int kx, int ky, vector>& positions) {\n int n = positions.size();\n const int m = 50;\n const int dx[8] = {1, 1, 2, 2, -1, -1, -2, -2};\n const int dy[8] = {2, -2, 1, -1, 2, -2, 1, -1};\n int dist[n + 1][m][m];\n memset(dist, -1, sizeof(dist));\n for (int i = 0; i <= n; ++i) {\n int x = (i < n) ? positions[i][0] : kx;\n int y = (i < n) ? positions[i][1] : ky;\n queue> q;\n q.push({x, y});\n dist[i][x][y] = 0;\n for (int step = 1; !q.empty(); ++step) {\n for (int k = q.size(); k > 0; --k) {\n auto [x1, y1] = q.front();\n q.pop();\n for (int j = 0; j < 8; ++j) {\n int x2 = x1 + dx[j], y2 = y1 + dy[j];\n if (x2 >= 0 && x2 < m && y2 >= 0 && y2 < m && dist[i][x2][y2] == -1) {\n dist[i][x2][y2] = step;\n q.push({x2, y2});\n }\n }\n }\n }\n }\n\n int f[n + 1][1 << n][2];\n memset(f, -1, sizeof(f));\n auto dfs = [&](this auto&& dfs, int last, int state, int k) -> int {\n if (state == 0) {\n return 0;\n }\n if (f[last][state][k] != -1) {\n return f[last][state][k];\n }\n int res = (k == 1) ? 0 : INT_MAX;\n\n for (int i = 0; i < positions.size(); ++i) {\n int x = positions[i][0], y = positions[i][1];\n if ((state >> i) & 1) {\n int t = dfs(i, state ^ (1 << i), k ^ 1) + dist[last][x][y];\n if (k == 1) {\n res = max(res, t);\n } else {\n res = min(res, t);\n }\n }\n }\n return f[last][state][k] = res;\n };\n return dfs(n, (1 << n) - 1, 1);\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nIn the town of Digitville, there was a list of numbers called nums containing integers from 0 to n - 1. Each number was supposed to appear exactly once in the list, however, two mischievous numbers sneaked in an additional time, making the list longer than usual.\n\nAs the town detective, your task is to find these two sneaky numbers. Return an array of size two containing the two numbers (in any order), so peace can return to Digitville.\n\n### Examples\nInput: nums = [0,1,1,0]\nOutput: [0,1]\nInput: nums = [0,3,2,1,3,2]\nOutput: [2,3]\nInput: nums = [7,1,5,4,3,4,6,0,9,5,8,2]\nOutput: [4,5]\n\n### Algorithm\nBit Manipulation"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n vector getSneakyNumbers(vector& nums) {\n int n = nums.size() - 2;\n int xx = nums[n] ^ nums[n + 1];\n for (int i = 0; i < n; ++i) {\n xx ^= i ^ nums[i];\n }\n int k = __builtin_ctz(xx);\n vector ans(2);\n for (int x : nums) {\n ans[(x >> k) & 1] ^= x;\n }\n for (int i = 0; i < n; ++i) {\n ans[(i >> k) & 1] ^= i;\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given a tree rooted at node 0 that consists of n nodes numbered from 0 to n - 1. The tree is represented by an array parent of size n, where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1.\n\nYou are also given a string s of length n, where s[i] is the character assigned to node i.\n\nWe make the following changes on the tree one time simultaneously for all nodes x from 1 to n - 1:\n\n\tFind the closest node y to node x such that y is an ancestor of x, and s[x] == s[y].\n\tIf node y does not exist, do nothing.\n\tOtherwise, remove the edge between x and its current parent and make node y the new parent of x by adding an edge between them.\n\nReturn an array answer of size n where answer[i] is the size of the subtree rooted at node i in the final tree.\n\n### Examples\nInput: parent = [-1,0,0,1,1,1], s = \"abaabc\"\nOutput: [6,3,1,1,1,1]\nInput: parent = [-1,0,4,0,1], s = \"abbba\"\nOutput: [5,2,1,1,1]\n\n### Algorithm\nDFS"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n vector findSubtreeSizes(vector& parent, string s) {\n int n = s.size();\n vector g[n];\n vector d[26];\n for (int i = 1; i < n; ++i) {\n g[parent[i]].push_back(i);\n }\n vector ans(n);\n auto dfs = [&](this auto&& dfs, int i, int fa) -> void {\n ans[i] = 1;\n int idx = s[i] - 'a';\n d[idx].push_back(i);\n for (int j : g[i]) {\n dfs(j, i);\n }\n int k = d[idx].size() > 1 ? d[idx][d[idx].size() - 2] : fa;\n if (k >= 0) {\n ans[k] += ans[i];\n }\n d[idx].pop_back();\n };\n dfs(0, -1);\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given an n x n square matrix of integers grid. Return the matrix such that:\n\n\tThe diagonals in the bottom-left triangle (including the middle diagonal) are sorted in non-increasing order.\n\tThe diagonals in the top-right triangle are sorted in non-decreasing order.\n\n### Examples\nInput: grid = [[1,7,3],[9,8,2],[4,5,6]]\nOutput: [[8,2,3],[9,6,7],[4,5,1]]\nInput: grid = [[0,1],[1,2]]\nOutput: [[2,1],[1,0]]\nInput: grid = [[1]]\nOutput: [[1]]\n\n### Algorithm\nSorting"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n vector> sortMatrix(vector>& grid) {\n int n = grid.size();\n for (int k = n - 2; k >= 0; --k) {\n int i = k, j = 0;\n vector t;\n while (i < n && j < n) {\n t.push_back(grid[i++][j++]);\n }\n ranges::sort(t);\n for (int x : t) {\n grid[--i][--j] = x;\n }\n }\n for (int k = n - 2; k > 0; --k) {\n int i = k, j = n - 1;\n vector t;\n while (i >= 0 && j >= 0) {\n t.push_back(grid[i--][j--]);\n }\n ranges::sort(t);\n for (int x : t) {\n grid[++i][++j] = x;\n }\n }\n return grid;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nDesign a data structure that can efficiently manage data packets in a network router. Each data packet consists of the following attributes:\n\n\tsource: A unique identifier for the machine that generated the packet.\n\tdestination: A unique identifier for the target machine.\n\ttimestamp: The time at which the packet arrived at the router.\n\nImplement the Router class:\n\nRouter(int memoryLimit): Initializes the Router object with a fixed memory limit.\n\n\tmemoryLimit is the maximum number of packets the router can store at any given time.\n\tIf adding a new packet would exceed this limit, the oldest packet must be removed to free up space.\n\nbool addPacket(int source, int destination, int timestamp): Adds a packet with the given attributes to the router.\n\n\tA packet is considered a duplicate if another packet with the same source, destination, and timestamp already exists in the router.\n\tReturn true if the packet is successfully added (i.e., it is not a duplicate); otherwise return false.\n\nint[] forwardPacket(): Forwards the next packet in FIFO (First In First Out) order.\n\n\tRemove the packet from storage.\n\tReturn the packet as an array [source, destination, timestamp].\n\tIf there are no packets to forward, return an empty array.\n\nint getCount(int destination, int startTime, int endTime):\n\n\tReturns the number of packets currently stored in the router (i.e., not yet forwarded) that have the specified destination and have timestamps in the inclusive range [startTime, endTime].\n\nNote that queries for addPacket will be made in non-decreasing order of timestamp.\n\n### Examples\n\n### Algorithm\nBinary Search"}, {"role": "assistant", "content": "```cpp\nclass Router {\nprivate:\n int lim;\n unordered_set vis;\n deque> q;\n unordered_map idx;\n unordered_map> d;\n\n long long f(int a, int b, int c) {\n return ((long long) a << 46) | ((long long) b << 29) | (long long) c;\n }\n\npublic:\n Router(int memoryLimit) {\n lim = memoryLimit;\n }\n\n bool addPacket(int source, int destination, int timestamp) {\n long long x = f(source, destination, timestamp);\n if (vis.count(x)) {\n return false;\n }\n vis.insert(x);\n if ((int) q.size() >= lim) {\n forwardPacket();\n }\n q.push_back({source, destination, timestamp});\n d[destination].push_back(timestamp);\n return true;\n }\n\n vector forwardPacket() {\n if (q.empty()) {\n return {};\n }\n auto packet = q.front();\n q.pop_front();\n int s = packet[0], d_ = packet[1], t = packet[2];\n vis.erase(f(s, d_, t));\n idx[d_]++;\n return {s, d_, t};\n }\n\n int getCount(int destination, int startTime, int endTime) {\n auto& ls = d[destination];\n int k = idx[destination];\n auto i = lower_bound(ls.begin() + k, ls.end(), startTime);\n auto j = lower_bound(ls.begin() + k, ls.end(), endTime + 1);\n return j - i;\n }\n};\n\n/**\n * Your Router object will be instantiated and called as such:\n * Router* obj = new Router(memoryLimit);\n * bool param_1 = obj->addPacket(source,destination,timestamp);\n * vector param_2 = obj->forwardPacket();\n * int param_3 = obj->getCount(destination,startTime,endTime);\n */\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given a string s consisting of lowercase English letters, and an integer k.\n\nYour task is to delete some (possibly none) of the characters in the string so that the number of distinct characters in the resulting string is at most k.\n\nReturn the minimum number of deletions required to achieve this.\n\n### Examples\nInput: s = \"abc\", k = 2\nOutput: 1\nInput: s = \"aabb\", k = 2\nOutput: 0\nInput: s = \"yyyzz\", k = 1\nOutput: 2\n\n### Algorithm\nGreedy"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n int minDeletion(string s, int k) {\n vector cnt(26);\n for (char c : s) {\n ++cnt[c - 'a'];\n }\n ranges::sort(cnt);\n int ans = 0;\n for (int i = 0; i + k < 26; ++i) {\n ans += cnt[i];\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nThere is an undirected tree with n nodes labeled from 1 to n, rooted at node 1. The tree is represented by a 2D integer array edges of length n - 1, where edges[i] = [ui, vi] indicates that there is an edge between nodes ui and vi.\n\nInitially, all edges have a weight of 0. You must assign each edge a weight of either 1 or 2.\n\nThe cost of a path between any two nodes u and v is the total weight of all edges in the path connecting them.\n\nYou are given a 2D integer array queries. For each queries[i] = [ui, vi], determine the number of ways to assign weights to edges in the path such that the cost of the path between ui and vi is odd.\n\nReturn an array answer, where answer[i] is the number of valid assignments for queries[i].\n\nSince the answer may be large, apply modulo 109 + 7 to each answer[i].\n\nNote: For each query, disregard all edges not in the path between node ui and vi.\n\n### Examples\n\n### Algorithm\nDynamic Programming"}, {"role": "assistant", "content": "```cpp\n\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given four integers sx, sy, tx, and ty, representing two points (sx, sy) and (tx, ty) on an infinitely large 2D grid.\n\nYou start at (sx, sy).\n\nAt any point (x, y), define m = max(x, y). You can either:\n\n\tMove to (x + m, y), or\n\tMove to (x, y + m).\n\nReturn the minimum number of moves required to reach (tx, ty). If it is impossible to reach the target, return -1.\n\n### Examples\nInput: sx = 1, sy = 2, tx = 5, ty = 4\nOutput: 2\nInput: sx = 0, sy = 1, tx = 2, ty = 3\nOutput: 3\nInput: sx = 1, sy = 1, tx = 2, ty = 2\nOutput: -1\n\n### Algorithm\nMath"}, {"role": "assistant", "content": "```cpp\n\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given an integer array nums of length n.\n\nYou start at index 0, and your goal is to reach index n - 1.\n\nFrom any index i, you may perform one of the following operations:\n\n\tAdjacent Step: Jump to index i + 1 or i - 1, if the index is within bounds.\n\tPrime Teleportation: If nums[i] is a prime number p, you may instantly jump to any index j != i such that nums[j] % p == 0.\n\nReturn the minimum number of jumps required to reach index n - 1.\n\n### Examples\nInput: nums = [1,2,4,6]\nOutput: 2\nInput: nums = [2,3,4,7,9]\nOutput: 2\nInput: nums = [4,6,5,8]\nOutput: 3\n\n### Algorithm\nBFS"}, {"role": "assistant", "content": "```cpp\nconst int mx = 1e6 + 1;\nvector factors[mx];\n\nint init = [] {\n for (int i = 2; i < mx; ++i) {\n if (factors[i].empty()) {\n for (int j = i; j < mx; j += i) {\n factors[j].push_back(i);\n }\n }\n }\n return 0;\n}();\n\nclass Solution {\npublic:\n int minJumps(vector& nums) {\n int n = nums.size();\n unordered_map> g;\n for (int i = 0; i < n; i++) {\n int x = nums[i];\n for (int p : factors[x]) {\n g[p].push_back(i);\n }\n }\n int ans = 0;\n vector vis(n, false);\n vis[0] = true;\n queue q;\n q.push(0);\n while (true) {\n queue nq;\n while (!q.empty()) {\n int i = q.front();\n q.pop();\n if (i == n - 1) {\n return ans;\n }\n vector idx = g[nums[i]];\n idx.push_back(i + 1);\n if (i > 0) {\n idx.push_back(i - 1);\n }\n for (int j : idx) {\n if (!vis[j]) {\n vis[j] = true;\n nq.push(j);\n }\n }\n g[nums[i]].clear();\n }\n q = nq;\n ans++;\n }\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given two strings s and target, both having length n, consisting of lowercase English letters.\n\nReturn the lexicographically smallest permutation of s that is strictly greater than target. If no permutation of s is lexicographically strictly greater than target, return an empty string.\n\nA string a is lexicographically strictly greater than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b.\n\n### Examples\nInput: s = \"abc\", target = \"bba\"\nOutput: \"bca\"\nInput: s = \"leet\", target = \"code\"\nOutput: \"eelt\"\nInput: s = \"baba\", target = \"bbaa\"\nOutput: \"\"\n\n### Algorithm\nGreedy"}, {"role": "assistant", "content": "```cpp\n\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given two integer arrays, technique1 and technique2, each of length n, where n represents the number of tasks to complete.\n\n\tIf the ith task is completed using technique 1, you earn technique1[i] points.\n\tIf it is completed using technique 2, you earn technique2[i] points.\n\nYou are also given an integer k, representing the minimum number of tasks that must be completed using technique 1.\n\nYou must complete at least k tasks using technique 1 (they do not need to be the first k tasks).\n\nThe remaining tasks may be completed using either technique.\n\nReturn an integer denoting the maximum total points you can earn.\n\n### Examples\nInput: technique1 = [5,2,10], technique2 = [10,3,8], k = 2\nOutput: 22\nInput: technique1 = [10,20,30], technique2 = [5,15,25], k = 2\nOutput: 60\nInput: technique1 = [1,2,3], technique2 = [4,5,6], k = 0\nOutput: 15\n\n### Algorithm\nGreedy"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n long long maxPoints(vector& technique1, vector& technique2, int k) {\n int n = technique1.size();\n vector idx(n);\n iota(idx.begin(), idx.end(), 0);\n\n sort(idx.begin(), idx.end(), [&](int i, int j) {\n return (technique1[j] - technique2[j]) < (technique1[i] - technique2[i]);\n });\n\n long long ans = 0;\n for (int x : technique2) {\n ans += x;\n }\n\n for (int i = 0; i < k; i++) {\n int index = idx[i];\n ans -= technique2[index];\n ans += technique1[index];\n }\n\n for (int i = k; i < n; i++) {\n int index = idx[i];\n if (technique1[index] >= technique2[index]) {\n ans -= technique2[index];\n ans += technique1[index];\n }\n }\n\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given two integer arrays nums1 and nums2 of lengths n and m respectively, and an integer k.\n\nYou must choose exactly k pairs of indices (i1, j1), (i2, j2), ..., (ik, jk) such that:\n\n\t0 <= i1 < i2 < ... < ik < n\n\t0 <= j1 < j2 < ... < jk < m\n\nFor each chosen pair (i, j), you gain a score of nums1[i] * nums2[j].\n\nThe total score is the sum of the products of all selected pairs.\n\nReturn an integer representing the maximum achievable total score.\n\n### Examples\nInput: nums1 = [1,3,2], nums2 = [4,5,1], k = 2\nOutput: 22\nInput: nums1 = [-2,0,5], nums2 = [-3,4,-1,2], k = 2\nOutput: 26\nInput: nums1 = [-3,-2], nums2 = [1,2], k = 2\nOutput: -7\n\n### Algorithm\nDynamic Programming"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n long long maxScore(vector& nums1, vector& nums2, int K) {\n int n = nums1.size(), m = nums2.size();\n long long NEG = LLONG_MIN / 4;\n vector f(n + 1, vector(m + 1, vector(K + 1, NEG)));\n f[0][0][0] = 0;\n for (int i = 0; i <= n; i++) {\n for (int j = 0; j <= m; j++) {\n for (int k = 0; k <= K; k++) {\n if (i > 0) {\n f[i][j][k] = max(f[i][j][k], f[i - 1][j][k]);\n }\n if (j > 0) {\n f[i][j][k] = max(f[i][j][k], f[i][j - 1][k]);\n }\n if (i > 0 && j > 0 && k > 0) {\n f[i][j][k] = max(\n f[i][j][k],\n f[i - 1][j - 1][k - 1] + 1LL * nums1[i - 1] * nums2[j - 1]);\n }\n }\n }\n }\n return f[n][m][K];\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given a string s consisting of lowercase English letters and an integer k.\n\nTwo equal characters in the current string s are considered close if the distance between their indices is at most k.\n\nWhen two characters are close, the right one merges into the left. Merges happen one at a time, and after each merge, the string updates until no more merges are possible.\n\nReturn the resulting string after performing all possible merges.\n\nNote: If multiple merges are possible, always merge the pair with the smallest left index. If multiple pairs share the smallest left index, choose the pair with the smallest right index.\n\n### Examples\nInput: s = \"abca\", k = 3\nOutput: \"abc\"\nInput: s = \"aabca\", k = 2\nOutput: \"abca\"\nInput: s = \"yybyzybz\", k = 2\nOutput: \"ybzybz\"\n\n### Algorithm\nHash Table"}, {"role": "assistant", "content": "```cpp\nclass Solution {\npublic:\n string mergeCharacters(string s, int k) {\n unordered_map last;\n string ans;\n for (char c : s) {\n int cur = ans.size();\n if (last.count(c) && cur - last[c] <= k) {\n continue;\n }\n ans += c;\n last[c] = cur;\n }\n return ans;\n }\n};\n```"}]} {"messages": [{"role": "system", "content": "You are a competitive programming assistant. Given a problem, its examples, and a required algorithm/technique, write a correct C++ solution."}, {"role": "user", "content": "### Problem\nYou are given an m x n integer matrix grid.\n\nTwo players move across the grid:\n\n\tPlayer 1 starts at the top-left cell (0, 0) and can move only right or down. Their destination is the bottom-right cell (m - 1, n - 1).\n\tPlayer 2 starts at the bottom-left cell (m - 1, 0) and can move only right or up. Their destination is the top-right cell (0, n - 1).\n\nEach player must choose a valid path from their respective starting cell to their destination.\n\nA cell is called shared if it belongs to both chosen paths.\n\nReturn an integer denoting the maximum possible sum of values of all shared cells.\n\n### Examples\n\n### Algorithm\nDynamic Programming"}, {"role": "assistant", "content": "```cpp\n\n```"}]} {"messages": [{"role": "user", "content": "How to make fabs() for __m128 vector ?\n\nDoes I have to use sign bits to multiply the original vector by 1.0f/-1.0f ?\n\nDidn't find any instruction set to do it.\n\nI don't want __m256 or 512. I'm searching for __m128 data type"}, {"role": "assistant", "content": "A single AND-NOT using a prepared constant to turn off the sign bits suffices:\n\n```\n#include \n\n#include \n\nint main(void)\n{\n static const __m128 MinusZero = { -0.f, -0.f, -0.f, -0.f };\n\n __m128 x = { +1, -2, +3, -4 };\n\n __m128 y = _mm_andnot_ps(MinusZero, x);\n\n printf(\"%g %g %g %g\\n\", y[0], y[1], y[2], y[3]);\n}\n```\n\nOutput:\n\n```\n1 2 3 4\n```"}]} {"messages": [{"role": "user", "content": "I am tasked with creating a C program that writes a python program (which prints \"hello world\") and executes it.\n\nI have completed the first part (writing the python program to a file) but when I try to execute the python program from C, nothing happens. I directly tested the created file and it has the expected input so I am likely doing something wrong when attempting to execute the python program.\n\nI am attempting to use system() in order to execute the python program:\n\n```\n#include \n#include \n#include \n\nint main() {\n FILE *pfile;\n pfile = fopen(\"execute.py\", \"w\");\n fprintf(pfile, \"print(\\\"hello world\\\")\");\n int system(const char *command);\n system(\"python3 execute.py\");\n return 0;\n}\n```"}, {"role": "assistant", "content": "As the comments suggest,\n\n```\nfclose(pfile);\n```\n\nfixes the issue"}]} {"messages": [{"role": "user", "content": "I am trying to get the y value of a Vector3 (the camera), and i have looked at the documentation and haven't found a function to get a single value from the Vector3.\n\nI have tried using it like a list, but that obviously doesn't work. I have found some C++ documentation, but i am using plain C, and I don't want to mess with C++. Thanks!"}, {"role": "assistant", "content": "AVector3is atypedef of a struct:\n\n```\n// Vector3, 3 components\ntypedef struct Vector3 {\n float x; // Vector x component\n float y; // Vector y component\n float z; // Vector z component\n} Vector3;\n```\n\nSo you can access theyfield as with any other struct. Ifmy_vect3is aVector3then you can access it withmy_vect3.y, and ifmy_vect3_pis a pointer to aVector3you can access it withmy_vect3_p->y."}]} {"messages": [{"role": "user", "content": "When developing a library for PlatformIO and ESP32 (but also other platforms/environments), what ifdef macro name can be used to determine if the code is being compiled using PlatformIO?\n\nFor example,#ifdef ESP32can be used to determine whether the build target is an ESP32. Is there a similar#ifdef PLATFORM_IOmacro that PlatformIO automatically sets that determines whether it's being built using PlatformIO?\n\nI tried Googling for a macro set by PlatformIO, but no results."}, {"role": "assistant", "content": "You could add your own inbuild_flags. Since such a macro would be defined in platformio.ini, it would be implicit that it is a PlatformIO build environment.\n\nOtherwise inspect platformio.ini, there may already be a suitable macro.Thissuggests thatPLATFORMIOmay be defined, further suggests:pio run -vorpio run -t envdumpto check macros predefined in the build environment. YMMV - I'm just Googling this stuff!"}]} {"messages": [{"role": "user", "content": "I've been reading a book detailing the C/C++ build process, and it mentions that there's a GNU extension that allows you to specify a function to be run before main() is started.\n\nWhat would be some good use cases for such a function? What's the difference with just doing it first thing when main() starts? I am more after theoretical answers rather than any specific code."}, {"role": "assistant", "content": "It's useful for libraries to initialize their global state. Without it, the application has to call the libraries' initialization functions frommain().\n\nExamples in the standard C runtime are the initialization ofstdin,stdout, andstderr. While these are initialized by the C runtime itself, the feature you're referencing allows user-written libraries to do similar initialization.\n\nC++ probably uses this for calling constructors of global variables."}]} {"messages": [{"role": "user", "content": "I came across this code in the wild and got very confused.\n\n```\n#ifdef __STDC__\n double cos(double x)\n#else\n double cos(x)\n double x;\n#endif\n{\n // ...\n}\n```\n\nI fail to see why the latter in the#elsewould be preferable in any circumstances. Are there any reasons to write function definitions as above as opposed to the very standard and widely accepted way as shown below?\n\n```\ndouble cos(double x) {\n // ... \n}\n```"}, {"role": "assistant", "content": "It may be necessary to use the latter form when compiling code with an ancient compiler or when compiling with a modern compiler but it is necessary to use an ancient version of the C language because some of the code being compiled uses old C features that are incompatible with modern C. Either of these is exceptionally rare these days."}]} {"messages": [{"role": "user", "content": "I need some array of array of const strings.\nThis compiles just fine in C\n\n```\nchar* names[] = {\"John\", \"Adrian\", \"Mary\", NULL};\nchar* towns[] = {\"Paris\", \"London\", \"Amsterdam\", \"Madrid\", NULL};\nchar** test[] = {names, towns, NULL};\n```\n\nIs there a shorter way to do them all in one, like this?\n\n```\nchar** test[] = {{\"John\", \"Adrian\", \"Mary\", NULL}, {\"Paris\", \"London\", \"Amsterdam\", \"Madrid\", NULL}, NULL};\n```\n\nGives a\n\n```\nwarning: excess elements in scalar initializer\n```\n\nThank you in advance!"}, {"role": "assistant", "content": "You can usecompound literalof array type from C99.\n\n```\nchar** test[] = {(char*[]){\"John\", \"Adrian\", \"Mary\", NULL},\n (char*[]){\"Paris\", \"London\", \"Amsterdam\", \"Madrid\", NULL},\n NULL};\n```"}]} {"messages": [{"role": "user", "content": "I have to get a string from keyboard, and then print only the numbers from the char, but with the actual value.\n\n**Example\n**\nInput: I am 19 years old\noutput: 19 (as an integer)\n\nI wrote this code, but I cant convert it whatever I do.\n\n```\n#define _CRT_SECURE_NO_WARNINGS\n#include \nvoid main()\n{\n char sir[20];\n int i=0;\n printf(\"Introduceti varsta sub forma - Eu am X ani. - : \");\n gets(sir);\n while(sir[i]!='\\0')\n {\n if(sir[i]>='0' && sir[i]<='9')\n {\n int nr = atoi(sir[i]);\n printf(\"%d\", nr);\n }\n i++;\n }\n```"}, {"role": "assistant", "content": "The functionatoiexpects a pointer of the typechar *while you are passing an object of the typechar.\n\nInstead of this record\n\n```\nint nr = atoi(sir[i]);\n```\n\njust write\n\n```\nint nr = sir[i] - '0';\n```\n\nPay attention to that the function gets is unsafe and is not supported by the C Standard. Instead use fgets."}]} {"messages": [{"role": "user", "content": "I would like to know, how to calculate 2D array's size in bytes.\n\nArray: int data[][5] = {{1, 2, 3}, {0}, {4, 3, 2}};\n\nAnd how should I calculate the size of this array in bytes.\n\nProgramming language is C."}, {"role": "assistant", "content": "You can use thesizeofoperator. The expressionsizeof datawill give you the size of the array, in bytes.\n\nHere is a short demonstration program:\n\n```\n#include \n\nint main( void )\n{\n int data[][5] = {{1, 2, 3}, {0}, {4, 3, 2}};\n\n printf( \"The size of the array is: %zu\\n\", sizeof data );\n}\n```\n\nIn my test environment, this program has the following output:\n\n```\nThe size of the array is: 60\n```\n\nThe size of the array may be different on different platforms, but on most modern platforms,sizeof(int)is4, so the array's total size is4 * 3 * 5, which is60."}]} {"messages": [{"role": "user", "content": "I needed a square root approximation in C so I looked upthis postand got this following implementation:\n\n```\nfloat squareroot(float n)\n{\n float x = n;\n float y = 1;\n float e = 0.001; // Accuracy level\n if (n == 0)\n return 0;\n while ((x - y) > e)\n {\n x = (x + y) / 2;\n if (n == 0 || x == 0)\n return 0;\n y = n / x;\n }\n return x; \n}\n```\n\nWhat is the time complexity of this?"}, {"role": "assistant", "content": "Hint:\n\nObserve that\n\n```\n(x[k+1] - √n)/(x[k+1] + √n) = (x[k] + n/x[k] - 2√n)/(x[k] + n/x[k] + 2√n) \n = (x[k] - √n)²/(x[k] + √n)².\n```\n\nSo by induction,\n\n```\n(x[k] - √n)/(x[k] + √n) = (x[0] - √n)^(2^k)/(x[0] + √n)^(2^k)\n = (√n - 1)^(2^k)/(√n + 1)^(2^k).\n```\n\nFrom this we find the number of iterations after which the error ise:\n\n```\nk = lg(lg(e / (2√n - e)) / lg((√n - 1)/(√n + 1)).\n```\n\n(base-2 logarithm.)"}]} {"messages": [{"role": "user", "content": "When I try to run some very basic code(literally 5 lines) I get the error: \"'gcc' is not recognized as an internal or external command,\noperable program or batch file.\" mingw is installed and added to path and when I type gcc --version in cmd everything is fine. I'm using the VSCode editor and I'm running Windows 10."}, {"role": "assistant", "content": "Try to restart VSCode. I know that if you add/remove anything from PATH and VSCode was already running, you need to re-launch it for any PATH changes to work."}]} {"messages": [{"role": "user", "content": "I have the following option set in my.clang-format:\n\n```\nAlwaysBreakAfterReturnType: All\n```\n\nHowever, if I have a function of the form\n\n```\nint __attribute__((deprecated))\nsomeFunc(void);\n```\n\nit gets reformatted to\n\n```\nint __attribute__((deprecated)) someFunc(void);\n```\n\nIs there a way to get clang-format to getAlwaysBreakAfterReturnTypeto work with__attribute__?\n\nThis is version 14.0.0."}, {"role": "assistant", "content": "It appears as though\n\n```\nint\nsomeFunc(void) __attribute__((deprecated));\n```\n\nis equally valid and works just fine with clang-format."}]} {"messages": [{"role": "user", "content": "I have to complete a project for university where I need to be able to optimise using compiler optimisation levels.\nI am using OpenMP and as a result I have got the gcc-11 compiler from brew.\nI have watched this videohttps://www.youtube.com/watch?v=U161zVjv1rsand tried the same thing but I am getting an error:\n\n```\ngcc-11 -fopenmp jacobi2d1.c -o1 out/jacobi2d1\n```\n\nBut I am getting the following error:\n\nHow do I do this?\n\nAny advice would be appreciated"}, {"role": "assistant", "content": "Optimization levels are specified with-O1etc, using capital letter O, not lower-case letter o.\n\nLower-case-o1specifies that the output file should be1, and thenout/jacobi2d1is an input file to be linked, but it is an existing executable and you can't link one executable into another — hence the error from the linker."}]} {"messages": [{"role": "user", "content": "Say I run the following in my command line\n\n$./(file name) abcd efg hijkl\n\nHow would I best find the length of argv[1],argv[2], etc.\n\nIn this example, I would like to hold argv[1], or \"abcd\", as an integer with a value of 4, argv[2], or \"efg\", as an integer value of 3, and argv[3], or \"hijkl\", as an integer value of 5.\n\nEDIT: realized I forgot to write #include ... smh"}, {"role": "assistant", "content": "strlenis used to find the length of strings.\n\n```\n#include \n#include \n \nint main(int argc, char *argv[])\n{\n int i;\n\n for (i = 0; i < argc; i++)\n printf(\"%zu\\n\", strlen(argv[i]));\n}\n```"}]} {"messages": [{"role": "user", "content": "The texture that gets rendered to the window is bound to Framebuffer 0. Is it possible to bind this texture to a texture unit, for use as a uniform sampler2D in a drawcall?"}, {"role": "assistant", "content": "No. The default framebuffer (which is what is provided by the window system) has no corresponding texture object that you could sample from.\n\nIf you want to sample from any render output, you are going to need to create a custom framebuffer object and render to some texture object attachments that you can then sample from.\n\nAnother option is to blit the default framebuffer color buffer into another framebuffer color attachment. See:https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBlitFramebuffer.xhtml"}]} {"messages": [{"role": "user", "content": "I am new to c language and I am trying to compile my first program, following a tutorial.\n\nMy file hello.c :\n\n```\n#include \n\nint main(void)\n{\n printf(\"hello, world\\n\");\n}\n```\n\nI use \"make hello\" command to compile it but I get the error:\n\n```\ncc hello.c -o hello\nprocess_begin: CreateProcess(NULL, cc hello.c -o hello, ...) failed.\nmake (e=2): The system cannot find the file specified.\n: recipe for target 'hello' failed\nmake: *** [hello] Error 2\n```\n\nI have MinGW installed and I have it in my environment variables PATH.\nI am trying it on Windows 8.\n\nPlease any help I would very appreciate.\nMaybe there is another way to compile a c files?"}, {"role": "assistant", "content": "MinGW is actually a gcc compiler. So the C compiler is invoked withgccinstead ofcc. Try running this command:\n\n```\nmake hello CC=gcc\n```"}]} {"messages": [{"role": "user", "content": "I'm pretty newbie in C language and I have this little code in which I want to do some test in the main code.\n\n```\nstruct ListNode\n{\n int val;\n struct ListNode *next;\n};\n```\n\nI want to create some examples (For example: 4 -> 9 -> 1) in the main code, but I don't really know how to initialize them. Thank you in advance."}, {"role": "assistant", "content": "I would do something like this:\n\n```\nstruct ListNode* addnode(struct ListNode *head,int val)\n{\n struct ListNode* newnode = malloc(sizeof(*this));\n newnode->val = val;\n newnode->next = NULL;\n if (!head) head = newnode;\n else {\n struct ListNode *this = head;\n while(this->next)\n this = this->next;\n this->next = newnode;\n }\n return head;\n}\n\nint main(void)\n{\n struct ListNode *head = NULL;\n\n head = addnode(head,4);\n addnode(head,9);\n addnode(head,1);\n\n return 0;\n}\n```"}]} {"messages": [{"role": "user", "content": "Trying to compile a c project then encountered error like below\n\n```\nundefined reference to `__llvm_profile_instrument_target'\nundefined reference to `llvm_gcda_start_file'\nundefined reference to `llvm_gcov_init'\n```"}, {"role": "assistant", "content": "It works withllvmcompiler too, just add--coverage.\n\nhttps://clang.llvm.org/docs/SourceBasedCodeCoverage.html"}]} {"messages": [{"role": "user", "content": "When i compile and run it tons of random letters appear in it closes\n\n```\n#include \n\nint main(int argc, int* argv[])\n{\n\n int x;\n for(x = 0; x < argc; x++)\n {\n while(*argv[x])\n {\n putchar(*argv[x]);\n *argv[x]++;\n }\n putchar('\\n');\n }\n return 0;\n\n}\n```\n\nThis Programm should take the input from the comand line\nand print it(i wanted it in this format to test why and how *argv[] works)"}, {"role": "assistant", "content": "You may consider checking for errors.\n\n```\n#include \n\nint main(int argc, char *argv[])\n{\n // Exit status if the argument count is incorrect\n if (argc != 2)\n {\n printf(\"Usage: ./program string\\n\");\n return 1;\n }\n```\n\nAlso you may want to print the string without writing a loop usingprintf()fucntion.\n\n```\n// Print the whole string in one step\nprintf(\"%s\\n\", argv[1]);\nreturn 0;\n}\n```"}]} {"messages": [{"role": "user", "content": "Here I have tried to create a linked list and create a function which adds any given number to the staring of the linked list.\n\n```\n#include \n#include \nstruct Node{\n int data;\n struct Node* next;\n};\nstruct Node* head=NULL;\n\nvoid Add(int n){\n head=(struct Node*)malloc(sizeof(struct Node));\n head->data=n;\n head->next=NULL;\n return;\n}\n```\n\nNow my doubt is, here we have definedheadto be a pointer variable of datatypestruct Node. InAddfunction, we have assigned the address of new memory allocated toheadpointer variable.\n\nBut when we are writinghead->data=n, why are we not dereferencingheadfirst, sinceheadwas a pointer variable, so it stores address, and to store variables like data, why shouldn't it be*head->data? Similar for*head->next=NULL."}, {"role": "assistant", "content": "The operator->is already a dereferencing operator.head->datais equivalent to(*head).data."}]} {"messages": [{"role": "user", "content": "When Iprintffollowing code, I gethex escape sequence out of range.\\x1bisnumeric escapeforESC. If my string is literally the1ESC1, how to represent it?\n\n```\n#include \n#include \n\nint main(void){\n printf(\"1\\x1b1\\n\");\n return EXIT_SUCCESS; \n}\n```"}, {"role": "assistant", "content": "\"\\x1b is numeric escape for ESC\" is true, but thehex escape sequencehere is\\x1b1, not\\x1b.\n\nAvoidprintf(st)to print astringst. The first argument toprintf()is for a format. OK in OP's case, but better to avoid that maybe some escape sequence was used that was the same as%.\n\nTryputs(\"1\" \"\\x1b\" \"1\");."}]} {"messages": [{"role": "user", "content": "Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed1 year ago.Improve this question\n\nThis is used heredo {....} while(ch!=?.?);what doesch!=?.?mean here can anybody please help with it."}, {"role": "assistant", "content": "It's a syntax error with both clang and gcc.\n\n@JonathanLeffler is usually right and I think he nailed the root cause. I used to see this when text was being copied from Microsoft Word to the web (lack of transcode from a Windows code page to ascii/utf8?)."}]} {"messages": [{"role": "user", "content": "Using#ifdef #endifallows one to have verbose messages displayed only during development and is quite handy. I wonder if something like the code below is possible, becoming even shorter:\n\n```\n// pseudo-code:\n\n#define IN_DEV\n#define DEBUG_ONLY(statement) (#ifdef IN_DEV (statement) #endif)\n\nint main(void)\n{\n DEBUG_ONLY(printf(\"hello from debug mode\\n\");)\n //...\n}\n```\n\nThis would only cost me a very readable one-liner which can be turned on or off. Is something like this / close to this possible?"}, {"role": "assistant", "content": "You could change the meaning ofDEBUG_ONLYdependent on ifIN_DEVis defined:\n\n```\n// pseudo-code:\n\n#ifdef IN_DEV\n#define DEBUG_ONLY(statement) {statement}\n#else\n#define DEBUG_ONLY(statement) // Nothing\n#endif\n\nint main(void)\n{\n DEBUG_ONLY(printf(\"hello from debug mode\\n\");)\n //...\n}\n```\n\nRunning example:Link"}]} {"messages": [{"role": "user", "content": "Context: C compiler option/Zeenables allMicrosoft extensions to C and C++.\n\nA simple question: is it possible to enable specific language extensions (i.e. not all at once)?"}, {"role": "assistant", "content": "/Zais super-ancient... ANSI 89. The/Zeflag is deprecated. Don't use either of them.\n\nFor modern language conformance, the/Zc,/permissive-, and/std:*switches are the way to go.\n\nIf you are looking for C rather than C++ conformance, seeMicrosoft Docsfor details on the new/std:c11and/std:c17switch in VS 2019 (16.8 or later)."}]} {"messages": [{"role": "user", "content": "Apparently, I am trying to usegif-hlibrary for gif creation with qt 4.7 for a C++ project. After embedding the library to the project, I can generate GIF through my qt GUI app, however, the colours on the final/actual GIF are swapped. What I mean is that:below red framebecomes below blue frameand same goes for other way round (i.e. blue frame becomes red frame).\n\nJust like above, below orange framebecomes below sky blue frameand same goes for other way round (i.e. sky blue frame becomes orange frame).\n\nCould someone familiar with the library or graphics or gif creation in code guide me?\n\nI am happy to provide more information about image capturing and such, as and when needed.\n\nThank you in advance."}, {"role": "assistant", "content": "Ok, I have managed to resolve the problem by using QImage::rgbSwapped() function. Thank you to @Pablo Yaggi particularly for the hint.\n\nI will have to remove the code snippet from the question due to security reasons."}]} {"messages": [{"role": "user", "content": "Here is an example code:\n\n```\nint* arr = (int*)malloc(2 * sizeof(int));\n\narr = arr + 1;\n*arr = 11;\narr[-1] = 22;\n\nint x = arr[0]; // x = 11\nint y = arr[1]; // y = 194759710\n```\n\nAfter a memory allocationarrpointer is incremented. I have expected to get the following results:\n\n```\nx == 22\ny == 11\n```\n\nCould you explain how it works ?"}, {"role": "assistant", "content": "When you setxandy, you forgot thatarrno longer points on allocated memory.\n\nThis code do what you want:\n\n```\n#include \n#include \n\nint main(void) {\n\n int* arr = (int*)malloc(2 * sizeof(int));\n int *original = arr;\n\n arr = arr + 1;\n\n *arr = 11;\n arr[-1] = 22;\n\n int x = original [0]; // x = arr[-1]\n int y = original [1]; // y = arr[0]\n\n printf(\"%d, %d\\n\", x, y);\n}\n```"}]} {"messages": [{"role": "user", "content": "Why I am getting a warning when shrinking arrays?There is no any way of losing the pointer value.\n\nWarning C6308 'realloc' might return null pointer: assigning null pointer to 'arr_all_guests', which is passed as an argument to 'realloc', will cause the original memory block to be leaked.\n\narr_all_guests = (char**)realloc(arr_all_guests,--(*guest_counter) * sizeof(char*));"}, {"role": "assistant", "content": "It means that as it is written the functionrealloccan return a null pointer. In this case an access to all the early allocated memory will be lost\n\n```\narr_all_guests = (char**)realloc(arr_all_guests,--(*guest_counter) * sizeof(char*));\n```\n\nbecause the original pointerarr_all_guestswill be reassigned with a null pointer.\n\nYou need to use a temporary pointer as for example\n\n```\nchar **tmp = realloc(arr_all_guests, ( *guest_counter - 1 ) * sizeof(char*)); \nif ( tmp != NULL ) \n{\n arr_all_guests = tmp;\n --*guest_counter;\n}\n```"}]} {"messages": [{"role": "user", "content": "I would like to printf doubles such that the overall length is always the same and the number is rounded if too long.\n\nFor example, with overall length 7:\n\n```\ndouble a = 1.23456789;\ndouble b = 12.3456789;\ndouble c = 123.456789;\nprintf(\"a: %f\\n\", a);\nprintf(\"b: %f\\n\", b);\nprintf(\"c: %f\\n\", c);\n```\n\nwould print:\n\n```\na: 1.23457\nb: 12.3457\nc: 123.457\n```\n\nIs there a simple way to achieve this?"}, {"role": "assistant", "content": "Yes, there is. See thespecificationsforprintfconversion specifiers. Use a#to select thealternative formto keep the trailing zeros. Use thegto obtain a representation with a fixed total number of digits. The.6specifies the exact number of digits.\n\n```\nprintf(\"a: %#.6g\\n\", a);\nprintf(\"b: %#.6g\\n\", b);\nprintf(\"c: %#.6g\\n\", c);\n```\n\nA precision of 6 digits happens to be the default, so this works as well\n\n```\nprintf(\"a: %#g\\n\", a);\n```"}]} {"messages": [{"role": "user", "content": "I have some large structure (> 64bytes), can I assure that each struct begins at a separated cacheline? Or is there some way to enforce that?"}, {"role": "assistant", "content": "The C standard provides_Alignof (constant-expression)to request extra alignment. For a structure, apply it to the first element:\n\n```\nstruct MyTag\n{\n _Alignas(64) char x[10];\n};\n\n#include \n\nint main(void)\n{\n printf(\"%zu\\n\", _Alignof (struct MyTag)); // Prints 64.\n}\n```\n\nThis requires that you have the cache line size as a compile-time constant.\n\nCompilers are not required to support extended alignments but will diagnose if the requested alignment is too large.\n\nIf accepted by the compiler, this will provide the requested alignment for objects allocated by the compiler. However,mallocmight return addresses without the desired alignment. For this, usestruct MyTag *p = aligned_alloc(64,size);, wheresizeissizeof *pfor one structure orN* sizeof *pforNstructures."}]} {"messages": [{"role": "user", "content": "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.Closed2 years ago.Improve this question\n\nI am having trouble evaluating 8-bit unsigned binary values with the & operator.\n\nFor example: would 0b11110101 & 0b11111100 = 0b01001010.\n\nIf not, then what would be the correct binary value?"}, {"role": "assistant", "content": "```\n(a) 0b11110101 &\n(b) 0b11111100 =\n----------------\n 0b11110100\n----------------\n```\n\nThis is anANDoperation, and both inputs (a)and(b) must be logical 1\n\nBoolean algebra basics"}]} {"messages": [{"role": "user", "content": "The following compiles:\n\n```\nmain()\n{\n int(asdf);\n\n}\n```\n\nIt seems this is some strange kind of declaration. I have tried to find code like this, but was unable to. Could someone explain?"}, {"role": "assistant", "content": "It turns out the line\n\n```\nint(asdf);\n```\n\nis equivalent to\n\n```\nint asdf;\n```\n\nwhich obviously declares an ordinary local variable namedasdf.\n\nBut you can put parentheses around various parts of the declarator, whether you need to or not. So it's just the same if you write\n\n```\nint asdf;\n```\n\nor\n\n```\nint (asdf);\n```\n\nor\n\n```\nint ((asdf));\n```\n\nParentheses are allowed in declarators because, sometimes, they're necessary in order to make a significant distinction. For example,\n\n```\nint *ap[10];\n```\n\ndeclares an array of 10 pointers, while\n\n```\nint (*pa)[10];\n```\n\ndeclares a pointer to an array."}]} {"messages": [{"role": "user", "content": "This question already has answers here:With arrays, why is it the case that a[5] == 5[a]?(20 answers)Closed2 years ago.\n\nI saw such a piece of C code:\n\n```\nint main()\n{\n static int a[] = {7,8,9};\n printf(\"%d\", 2[a] + a[2]);;\n \n return 0;\n}\n```\n\nWhat does2[a]mean here?"}, {"role": "assistant", "content": "a[b]andb[a]are 100% equivalent in C. What you have there is a very unidiomatic way of writinga[2].\n\nBy way of more complete explanation, array subscript notationa[b]is also 100% equivalent to*(a + b), which may make the reason it works both ways clearer."}]} {"messages": [{"role": "user", "content": "I am learning C Programming currently on VS Code. I run program a lot of time repeatedly which mess up terminal. Mostly I useclsbefore running program to clear previous output of terminal. My default terminal is PowerShell in VS Code. Is there any way to clean terminal before each run.\n\nWhat I have tried after google search:-I have tried addingclsto powershell profile but it does not work on every code run.-Checkingclear previous outputincoderunnersettings didn't work either."}, {"role": "assistant", "content": "The easiest way is to add cls to the beginning of your code, but that's not always best:\n\nYou can also set a keyboard shortcut forclearing the console(Used to bectrl+k, but was removed)\n\nYou don't want to replace the existing behavior when running code, but a pretty simple one-button solution could be setting up a vs code macro to doTerminal: Clear, and alsorunyour open file in the terminal."}]} {"messages": [{"role": "user", "content": "I am checking the existence of a file in a function.\n\n```\nint main(int argc, char* argv[])\n{\n foo(argc, argv);\n // File exists\n // Do something\n}\n\nvoid foo(int argc, char** argv)\n{\n int f = open(argv[1], O_RDONLY);\n if(f == -1)\n {\n exit(1);\n }\n}\n```\n\nDoes the file go out of scope or closes when the function call returns or will it stay open and affect the performance as I am writing a c code to copy the contents of one file to another with system calls."}, {"role": "assistant", "content": "The file doesn't close since there's no code to close it. The file doesn't go out of scope because only a variable or object can go out of scope. However, whenfgoes out of scope, the descriptor (or handle) used to access the file goes out of scope leaving no way to access or close it."}]} {"messages": [{"role": "user", "content": "I need to get information about running processing Windows.\n\nWhat can I write to make the program give a list like this:\nworking applications: Opera, Teamspeak. It's a little bit like task manager in Windows."}, {"role": "assistant", "content": "Get a list of processes withEnumProcesses(), which you can then iterate to get information on the individual processes using theProcess APIfunctions such asGetModuleBaseName()as described in the example athttps://learn.microsoft.com/en-us/windows/win32/psapi/enumerating-all-processes"}]} {"messages": [{"role": "user", "content": "Is there a way (using gcc) to set the stack size of a shared library ?I build a.sothat contain a single function that uses a big buffer as local variable.Something like that:\n\n```\nvoid foo ( void )\n {\n int table [1000000] ; // 4 millions bytes table !\n ...\n }\n```\n\nI added the option-Wl,-z,stack-size=4100000but it has no effet (not even an error message).By the way, this lib is meant to be invoked from java code (using JNA).Since I didn't find any post about this peculiar question, I'm afraid it's not possible..."}, {"role": "assistant", "content": "No, this is not possible - functions from shared library work in the context of thread which calls them and that thread will either be a main application thread (which started inmain) or a thread created with Pthreads (which will have stack allocated at thread creation time inpthread_create).\n\n-Wl,-z,stack-sizeflag is only applicable to applications, not libraries, and sets the size of main thread's stack."}]} {"messages": [{"role": "user", "content": "I'm working with a game engine that uses escape codes in strings to perform commands such as setting color. eg to set the color to red, you write\"Red text:\\x81\\xFF\\x00\\x00\\xFFhello!\"(0x81, red, green, blue, alpha).\n\nIs it possible to create a macro likeTEXT_COLOR(r,g,b,a)such thatTEXT_COLOR(255,0,0,255)would expand to\"\\x81\\xFF\\x00\\x00\\xFF\"for use in constant strings?"}, {"role": "assistant", "content": "It takes a mix of token pasting and stringification in different macros, but, yeah, it's possible using base-16 numbers:\n\n```\n#include \n\n#define TEXT_COLOR2(r,g,b,a) \"\\x81\" #r #g #b #a\n#define TEXT_COLOR(r,g,b,a) TEXT_COLOR2(\\x ##r, \\x ##g, \\x ##b, \\x ##a)\n\nint main(void) {\n char s[] = \"Red text:\" TEXT_COLOR(FF, 00, 00, FF) \"hello!\";\n for (const char *c = s; c < s + sizeof(s); c++) {\n printf(\"\\\\x%02hhX\", *c);\n }\n putchar('\\n');\n return 0;\n}\n```"}]} {"messages": [{"role": "user", "content": "If you input even numbers, only the odd numbers will be printed until it reaches 0. (0 will not be printed). For example, if you input 10, the output would be 9, 7, 5, 3, 1.\n\nThis is what I came up with. I'm wondering what should I decrement x by to get the desired output.\n\n```\nint x;\nscanf(\"%d\", &x);\nwhile (x >= 0) {\n printf(\"%d\", x);\n x = x - 2;\n}\n```"}, {"role": "assistant", "content": "I'm wondering what should I decrement x by to get the desired output.\n\nSubtracting 2 is fine, as long as you always start from an odd number. So you could change the loop into something like this:\n\n```\nfor ( int i = x % 2 ? x : x - 1; // Is x odd? good. \n // Otherwise, start from the previous one.\n i > 0;\n i -= 2 ) {\n printf(\"%d\\n\", i);\n}\n```"}]} {"messages": [{"role": "user", "content": "I have been trying to write a file from memory in C, more specifically an executable file. Every time I try to usefputsit detects a '00' in memory after a bit and stops writing. But there is still the rest of the file that it has to write. In the file that I am trying to write there are '00's all over the place for padding. I have some code below for reference:\n\n```\nchar *buffer;\nbuffer = malloc(size);\n// ...\nFILE *file;\nfile = fopen(\"somename\",\"w\");\nfputs(buffer,file);\nfclose(file);\n```\n\nIs there any way I would be able to have '00's in memory withoutfputstaking it as an EOF?Thanks!"}, {"role": "assistant", "content": "you should use 'fwrite' take the place of fpus"}]} {"messages": [{"role": "user", "content": "I want to declare a global variable inside a main() function...\n\nBelow is what I want the program to act like\n\n```\n#include\nint a[6];\nint main()\n{\n int n;\n scanf(\"%d\",&n);\n}\n```\n\nI want to create an array of user given size (here n-size) and I want to access that array globally.\nSo instead of creating array of size '6' outside the main() function, I want to create array of 'n' size globally instead of passing array whenever function is called..."}, {"role": "assistant", "content": "You can declare a pointer as global variable and assign buffer to that inmain().\n\n```\n#include\n#include\nint *a;\nint main()\n{\n int n;\n scanf(\"%d\",&n);\n a = calloc(n, sizeof(*a)); /* calloc() initializes the allocated buffer to zero */\n if (a == NULL)\n {\n /* calloc() failed, handle error (print error message, exit program, etc.) */\n }\n}\n```"}]} {"messages": [{"role": "user", "content": "We got a program and it holds 6 students we specified them at the beginning.\nAnd the problem is i know how to print them in command line.\nBut how to edit them?\nHow to add more so we will have 7 students?\nI also need to delete that student but teacher told me it would be good if its just empty space or Null.\n\n```\ntypedef struct Student{\n int NrAlbumu;\n char Imie[20];\n char Nazwisko[20];\n int RokStudiow;\n char Plec[20];\n char Zaleglosci[20];\n}s;\n```\n\nLets say its my struct."}, {"role": "assistant", "content": "I think that you done something different than the statement. I think you should use a Linked List Data Structure so you need have a struct like this.\n\n```\ntypedef struct Student{\n char name[20];\n struct Student *next;\n}s;\n```\n\nIn order to make a list of them. You can take a lookhere(it use int as data, so you must use string).\n\nFeel free to ask me more!"}]} {"messages": [{"role": "user", "content": "As I was following an example from a book,\n\n```\n#include \n\nmain()\n{\n int c;\n\n c = getchar();\n while (c != EOF) { \n putchar(c)\n c = getchar();\n }\n}\n```\n\nI thought it would make more sense to read character first, then print it so switched putchar and getchar around\n\n```\nc = getchar();\nputchar(c);\n```\n\nnow when I run it, what happens is the first output of putchar is missing the first character of c? This is the output:\n\n```\nkingvon@KingVon:~/Desktop/C$ ./a.out\nfirst letter is missing?\nirst letter is missing?\nbut now it is not \nbut now it is not\n```\n\nThis is interesting, why does this happen?"}, {"role": "assistant", "content": "Because you're getting a characterbeforethe loop. That means c is equal to that first character, but in the loop it's getting every character after that. So,\n\n```\nGet: f\nStart the loop\nGet: i\nPrint: i\nAnd so on\n```"}]} {"messages": [{"role": "user", "content": "```\n#include\nint main(void){\n float a = 0.7;\n if(a<0.7)\n printf(\"C\");\n else\n printf(\"c++\");\n}\n```\n\nI was going through a text book test your c skills by an Indian author. I found this question in a floating point problems chapter. I am comparing(0.7<0.7)which is false. So why is the outputcand notc++."}, {"role": "assistant", "content": "Explanation:\n0.7 is double constant (Default). Its binary value is\nwritten in 64 bit.\nBinary value of 0.7 = (0.1011 0011 0011 0011 0011 0011\n0011 0011 0011 0011 0011)\nNow here variable a is a floating-point variable while\n0.7 is double constant. So variable a will contain only\n32 bit value i.e.\n\n```\na = 0.1011 0011 0011 0011 0011 0011 0011 0011 \nwhile\n0.7 = 0.1011 0011 0011 0011 0011 0011 0011 0011 0011\n0011 0011....\n```\n\nIt is obvious a < 0.7"}]} {"messages": [{"role": "user", "content": "This question already has answers here:How to read from stdin with fgets()?(6 answers)Closed2 years ago.\n\n```\nvoid name(record *el)\n{\n char k[100];\n printf(\"Name: \");\n fgets(k,100,stdin);\n printf(\"\\n\");\n}\n```\n\nI'm trying to write a function that reads a line from console and then searches for it in a list. I'm having some problem with reading a whole line. The program just skips the fgets line. The same happens if i try with scanf(\"%[^\\n]%*c\")."}, {"role": "assistant", "content": "You probably read an integer before calling the function and the '\\n' was left on the input stream.\n\nTry calling the function as the first command you do in main and you will see that it works.\n\nIf you read a number right before the call with scanf for example, you could add a '\\n' in the parameter string before calling the fgets:\n\n```\nscanf(\"%d\\n\", &x);\n```"}]} {"messages": [{"role": "user", "content": "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.Closed2 years ago.Improve this question\n\nI need to send a signed short integer but thesendtofunction requires me to give a char buffer.\n\nThe buffer:char SendBuffer[1024];\n\nI was thinking of making the integer into a string and storing it like that but I am wondering if there is a better way to do it."}, {"role": "assistant", "content": "Actually, this is the declaration of sendto():\n\n```\nssize_t sendto(int sockfd, const void *buf, size_t len, int flags,\n const struct sockaddr *dest_addr, socklen_t addrlen);\n```\n\nThe buffer is of type void* so you can pass it a pointer to any type of variable.\n\nIn your case:\n\n```\nshort your_variable;\nshort *buffer = &your_variable;\n\nsendto(sockfd, buffer, sizeof(your_variable), flags, ...);\n```"}]} {"messages": [{"role": "user", "content": "I need to change the config bits in a EZBL bootloader project.\n\nI'm able to compile it, with version 2.11 and MPLAB X ide 5.4\n\nThe problem is that config bits are fully wrong, and if i modify them in mplab ide they are gone to the old value after recompile. That means that config bits are set programally or set in project.\n\nSo, how do you change config bits in the project?"}, {"role": "assistant", "content": "You can do it in your source code like this:\n\n```\n/*Config1*/\n#pragma config FEXTOSC = OFF\n#pragma config RSTOSC = HFINT32\n#pragma config CLKOUTEN = OFF\n...\n```\n\nHave a look in the filepic_chipinfo.htmlwhich configuration bits are handeld in your controller"}]} {"messages": [{"role": "user", "content": "I've use cURL command-line tool with --libcurl and a url of mine(the url works in normal C), however I get the error \"curl.h\" does not exist, although it is in the same directory. I can't figure out how to include headers in emscripten. All of the supposed documentation on this usually ends up being about something else entirely."}, {"role": "assistant", "content": "I figured it out, I was being dumb"}]} {"messages": [{"role": "user", "content": "Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed2 years ago.Improve this question\n\nAFAIK, Some part of C compilation phases can be multi-threaded.\n\nFor example, At least Preprocessing and Parsing (creating AST) is only related its source file itself so each file can be parallelized.\n\nIs there any reason that GCC has no multi-threaded compile option?"}, {"role": "assistant", "content": "You can build C/C++ in paralell if you use and setup a proper build system, which handles this for you.\n\nBasically in C/C++ every .c/.cpp file is complied to an .o file. All these .o files are then linked to the resulting binary.\n\nA build system (make for instance) can be used, to build all the .o files in paralell."}]} {"messages": [{"role": "user", "content": "```\n#include \n#include \n\nint main() {\n\n initscr();\n\n int height, width;\n getmaxyx(stdscr, height, width);\n\n endwin();\n\n printf(\"width : %i\\n\", width);\n printf(\"height : %i\\n\", height);\n\n return 0;\n}\n```\n\nresult iswidth : 148height : 38\n\nHow the width and height were changed without passing a pointer"}, {"role": "assistant", "content": "If you readhttps://linux.die.net/man/3/getmaxyxyou'll see:\n\nNotes All of these interfaces are macros. A \"&\" is not necessary\nbefore the variables y and x."}]} {"messages": [{"role": "user", "content": "I am trying to separately run server and client on the port number 19345, but I want to compile them all at once by simply typingmakeusingMakefile. To do so, I created the followingMakefile:\n\n```\ntarget: run_server run_client\n\nrun_server:\n ./server 19345\n \nrun_client:\n ./client 19345\n\nserver: server.c\n gcc -o server.c\n\nclient: client.c\n gcc -o client.c\n\nclean:\n rm *.o run_server run_client target\n```\n\nUnfortunately, when I typedmake, the terminal result shows as follows:\n\n```\n./server 19345\nmake: ./server: Command not found\nMakefile:4: recipe for target 'run_server' failed\nmake: *** [run_server] Error 127\n```\n\nHow can I fix this problem?"}, {"role": "assistant", "content": "You can probably just do:\n\n```\n.PHONY: target run_server run_client\ntarget: run_server run_client\n\nrun_server: server\n ./server 19345\n \nrun_client: client\n ./client 19345\n\nclean:\n rm -f *.o server client\n```"}]} {"messages": [{"role": "user", "content": "How does one definecopyanddeepcopymethods for a Python type defined in a C extension?\n\nLooking at thedocumentation, there doesn't appear to be atp_slot for these methods."}, {"role": "assistant", "content": "There's no slot. You just define the same methods you'd define in Python, but in C. (Typically, that means implementing__reduce__and getting the default__reduce__-basedcopy.copyandcopy.deepcopybehavior, but you can also implement__copy__and__deepcopy__if you want.)"}]} {"messages": [{"role": "user", "content": "This question already has answers here:Using Quick Sort in C to sort in reverse direction (descending)?(3 answers)Closed3 years ago.\n\n```\nvoid sort_array(void)\n{\n int sorted_arr[arr_count];\n\n qsort(sorted_arr, arr_count, sizeof(*sorted_arr), compare_qsort);\n return;\n}\n```\n\nI can't figure out how to use qsort in reverse can anyone help me?"}, {"role": "assistant", "content": "This would be how I would solve it:\n\n```\nint compare_qsort(const void *pointer1, const void *pointer2)\n{\n //Returns a sorted array in descending order.\n const int *pointeri = pointer1;\n const int *pointerj = pointer2;\n return *pointerj - *pointeri;\n}\n```\n\nNotice how you flip it so that thepointerjvariable is subtracting thepointerivariable.\n\nI found this other question that you could refer to:Using Quick Sort in C to sort in reverse direction (descending)?"}]} {"messages": [{"role": "user", "content": "I have the following code snippet for a PIC controller:\n\n```\nvoid __interrupt() ISR(void\n{\n // do some stuff\n}\n```\n\nwhen I use PC-Lint I always get the error message:\n\nError 10: Expecting identifier or other declarator\n\nWhat can I do to handle the interrupt in PC-Lint?"}, {"role": "assistant", "content": "You can define a dummy preprocessor macro by using the option-d__interrupt()="}]} {"messages": [{"role": "user", "content": "See this answer\n\nI understood it except for the last statement.\n\nthe conversion specifier \"%d\" skips optional leading whitespace and (tries to) converts the rest of the input to integer (if no errors occur).\n\nI understood the point regarding theoptional whitespace. But what does\"converts the rest of the input to integer\"means? I mean why will it convert the input to integer if the input itself is an integer?"}, {"role": "assistant", "content": "The input itself is an integer?\n\nNo, the input from key board is string(ascii), So the scanf Convert it to integer and store it in the variable.\n\nSee this:\n\n```\n#include \n\nint main()\n{\n char cnum[] = \"123\";\n int num = 0;\n\n int i=0;\n while(cnum[i])\n {\n num*=10;\n num+= cnum[i]-'0';\n i++;\n }\n\n printf(\"%d\",num); //This also converts int to string to print\n\n return 0;\n}\n```\n\nThanks."}]} {"messages": [{"role": "user", "content": "These are example of incrementing each element of an array by 10.\n\n```\nfor (i = 0; i< 100; i++){\n arr[i] += 10;\n}\n```\n\nor\n\n```\nfor (i = 0; i< 100; i+=2){\n arr[i] += 10;\n arr[i+1] += 10;\n}\n```\n\nwhich is the efficient way to solve this problem out of these these two in C language?"}, {"role": "assistant", "content": "Don't worry about it. Your compiler will make this optimization if necessary.\n\nFor example,clang 10 unrolls this completely and uses vector instructions to do multiple at once."}]} {"messages": [{"role": "user", "content": "I try to make pgbouncer in windows\n\nThey haveusuallibrary (libusual) for work with ip-sokets.\n\nWhen pgbouncer tune socket, it callssocket_setupfrom usual library\n\nsocket_setupcallres = fcntl(sock, F_SETFD, FD_CLOEXEC);andresis -1 now.\n\nHow can I fix one?\n\nMy build system is mingw64 from msys."}, {"role": "assistant", "content": "Just for someone who find this page.\n\nProblem occurred because theusuallibrary in some (not in all) places useintinsteadSOCKETwhich isint*and has a size more than size ofinton a 64-bit platform."}]} {"messages": [{"role": "user", "content": "what is the meaning of \"D type qualifier is meaningless on cast type at this line of code\"\n\n```\n(*((volatile RCC_t * const)0x400FE060)).USESYSDIV = 1;\n```\n\nand how to solve it?"}, {"role": "assistant", "content": "volatile RCC_t * constsays the pointer (not the thing it points to) isconst. But this is for avalue, which is just a result used in an expression. Qualifiers likeconstare properties ofobjectsin memory. So it serves no purpose in this cast."}]} {"messages": [{"role": "user", "content": "Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed3 years ago.Improve this question\n\nI recently came across this piece of code online,here,\nI was unable to read it due to the strange if statement.\n\n```\n//Send some data\n if( send(sock , message , strlen(message) , 0) < 0)\n {\n puts("Send failed");\n return 1;\n }\n```\n\nI am specifically referring to the< 0following thesend()function.\nI have never seen this use and am having trouble describing it to google.\n\nCan anyone explain this use or link to any resources that may contain more information on it?"}, {"role": "assistant", "content": "The code went through HTML encoding. Replace<with\n#include \n#include \n#include \n\nint main() {\n char *s = malloc(1024*sizeof(char));\n scanf(\"%[^\\n]\", s);\n int* freq = (int*)calloc(10,sizeof(int));\n for(int i=0;i\n#include \n#include \n\nint main() {\n if(!fork()) {\n printf(\"child pid=%d\\n\", getpid());\n exit(0);\n }\n\n sleep(20);\n\n printf(\"parent pid=%d\\n\",getpid());\n exit(0);\n}\n```"}, {"role": "assistant", "content": "A zombie process is a dead child process that the parent process hasn’t checked on. In the original code, the child ends 20 seconds earlier than the parent, so it’s a zombie for 20 seconds. If you remove the firstexit(0), they both stay alive for 20 seconds because in the child, control passes right out the bottom of theifblock unless something stops it.\n\nThus, if you remove the child'sexit()then not only is it unlikely to go zombie for an observable amount of time, but you should see it print a \"parent pid\" message in addition to its \"child pid\" message."}]} {"messages": [{"role": "user", "content": "This question already has answers here:How does the Comma Operator work(9 answers)Closed4 years ago.\n\nI was readingthis questionabout sequence points and I saw this line:\n\ni = (i, ++i, 1) + 1; // well defined (AFAIK)\n\nI was wondering how is the following syntax called and what are its effects?\n\ni = (a1, a2, ...,an);"}, {"role": "assistant", "content": "This is the comma operator forintoperands, together with grouping through parentheses, which is always allowed. First,\n\n```\n(i, ++i, 1)\n```\n\nevaluatesi, then++i, then1and returns the result of the last expression (which is1). Then\n\n```\n(i, ++i, 1) + 1\n```\n\nis the same as\n\n```\n1 + 1;\n```\n\nwhich results in2, soiis set to2here. Note that without the parentheses, the result would in most cases not be the same, as the comma operator has the lowest possible precedence (thanks to @dbush for helping me out here in the comments)."}]} {"messages": [{"role": "user", "content": "This is a C program in which the code from \"int k\" and \"for\" loop are enclosed in the curly brackets. What is the purpose of those curly brackets?\n\n```\nint main(){\n int k;\n {\n int k;\n for (k=0;k<10;k++);\n }\n }\n```"}, {"role": "assistant", "content": "There are no \"unwanted braces\" in this code. There is an anonymous block, which is not an error. In fact, it is allowed by the spec.\n\nYour variablekis defined in the main scope, but then shadowed in the anonymous block.\n\n```\nint main() {\n int k = 0;\n {\n int k = 1;\n // do more stuff with k\n }\n // k is still 0 here.\n}\n```\n\nWhen I was programming C, something like 1000 years ago, I would have had stern words for a dev on my team who tried using this trick."}]} {"messages": [{"role": "user", "content": "I know that x++ refers to post increment. It first uses the original value and then resorts to the incremented value.\n\nBut when does that actually happen? \nDoes it happen when the next immediate line in code is executed?\nDoes it happen when original value is returned once?"}, {"role": "assistant", "content": "It happens between sequence points.\n\nOther than that, it's unspecified when it happens.\n\nImagine this\n\n```\nx = y = z = 42\n; // sequence point A\nn = x++ + y++ + z++\n; // sequence point B\n```\n\nAt seq. point A x, y, and z are all 42; at sequence point B they are all 43. For all you care, the compiler could emit code to update all 3 variables at the same time.\n\n```\n// pseudo code\nn = 126;\n[vector increment][x,y,z];\n//n = 126;\n```"}]} {"messages": [{"role": "user", "content": "Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed4 years ago.Improve this question\n\nI need to implement a function that can count the number of digits in a string, and here is my code which is not working and i need to know what's the problem.\nint main() {\n\n```\n/* Enter your code here. Read input from STDIN. Print output to STDOUT */\nchar s[100];\nscanf(\"%s\",s);\nint i,j=0;\nfor(i=0;i<10;i++)\n{\n int freq=0;\n while(s[j] != '\\0')\n {\n if(s[j] == i +'0')\n {\n freq++;\n }\n j++;\n }\n printf(\"%d \",freq);\n\n} \nreturn 0;\n```\n\n}"}, {"role": "assistant", "content": "Resetjto 0 after eachforloop iteration"}]} {"messages": [{"role": "user", "content": "I have a function taking a function pointer, and I want to store the return value if the function pointed to by the pointer returns, and just run the function otherwise. Something like this:\n\n```\nstatic void threadStart(void (*function)(void*), void* arg) { \n if(function does not return void) (void*) store = function(arg); \n else(function())\n};\n```\n\nHow can I do this? I tried just doing:\n\n```\nstatic void threadStart(void (*function)(void*), void* arg) { \n (void*) store = function(arg); \n};\n```\n\nBut this produces a compilation error."}, {"role": "assistant", "content": "You can't.\n\nBecausefunctionis declared asvoid (*function)(void*)it always returns void, so you don't need to."}]} {"messages": [{"role": "user", "content": "Hi guys I'm new to C and pointers so I hope you'll forgive me.\n\nI have the following code:\n\n```\nchar *str = NULL;\n*str = 'a';\nprintf(\"My string is :%s\\n\",str);\n```\n\nIt compiles but I'm getting a segmentation error everytime. What is the cause of this and what how can I change it so that I can assign 'a' to my string?\n\nThanks in advance!"}, {"role": "assistant", "content": "```\nchar *str = NULL;\n```\n\nThe pointer str is not allocated yet. So you can not dereference it. Then you tried to deference by\n\n```\n*str = 'a';\n```\n\nThe segmentation fault will occur.\n\nIf you want str with \"a\" value, you can do this way:\n\n```\nchar *str = \"a\";\nprintf(\"My string is :%s\\n\",str);\n```"}]} {"messages": [{"role": "user", "content": "I tried to construct a function that has the reference as a parameter.\n\nBut the compile gave me a error warning, saying that expected')', I don't know what is the problem.Can't we use reference as parameter in C?The following is the code segment.\n\n```\ntypedef struct Qnode{\n struct Qnode* first;\n struct Qnode* rear;\n int value;\n}Queue;\n\nint init_Queue(Queue &q) //expected')' as the compiler warned me.\n{\n return 1;\n}\n```\n\nShould I use a pointer instead of a reference as a parameter??"}, {"role": "assistant", "content": "C doesn't have references. That's a C++ construct.\n\nYou'll need to change the function to accept a pointer.\n\n```\nint init_Queue(Queue *q)\n{\n printf(\"value=%d\\n\", q->value);\n return 1;\n}\n```"}]} {"messages": [{"role": "user", "content": "Its my exams next week and we were given a bank of questions out of which we need to provide valid solutions with explanations of the given code. I am not able to understand this code. Attaching the code.\n\n```\n#include \n int main()\n { \n int a = 800, b = 100, c; \n if(!a >= 400) \n b = 500; \n c = 900; \n printf(\"b = %d c = %d\\n\", b, c); \n return 0; \n }\n```\n\nThe answer after execution of this problem is b=100 and c=900. But i have not understood how."}, {"role": "assistant", "content": "```\nif(!a >= 400)\n```\n\nSince logical not!has higher precedence, this is equivalent to(!a) >= 400. The left side evaluates to0(because a is non-zero, so!ais0) making the entire expression is false. Also note the code indentation isn't significant to the compiler."}]} {"messages": [{"role": "user", "content": "I've got the following situation:\n\n```\n#include \n\nint main(void) {\n int first = 0x08;\n\n printf(\"%d\\n\", first & 0b10);\n printf(\"%d\\n\", first & 0b10 == 0);\n\n if (first & 0b10 == 0) {\n printf(\"SET\");\n } else {\n printf(\"NOT\");\n }\n\n return 0;\n}\n```\n\nTwo0s print out, followed byNOT. What is happening here? It seems to be thatfirst & 0b01is zero, so should pass the condition."}, {"role": "assistant", "content": "This is an issue of operator precedence.\n\nThe bitwise AND operator&has lower precedence than the equality operator==. So this:\n\n```\nfirst & 0b10 == 0\n```\n\nIs the same as:\n\n```\nfirst & (0b10 == 0)\n```\n\nWhich is not what you want. It compares0b10for equality with 0, which is false. Thenfirst & 0is evaluated which is 0.\n\nAdd parenthesis to get the desired behavior:\n\n```\n(first & 0b10) == 0\n```"}]} {"messages": [{"role": "user", "content": "I was studying the book \"Data Structure and algorithms made easy\" and but I got confused while learning \"Comparing Linked Lists and Unrolled Linked list\"...\n\nwhat is overhead?\nWhy he is only stating 8 bytes of overhead for 100 elements array?"}, {"role": "assistant", "content": "Overhead is all the stuff that is not part of the data that you want to store. Like the pointers to the next and previous element.\n\nThe block list is a list of arrays. Each array contains a number of elements. In principle your entire list could consist of a single block node with an array of all your elements. So less overhead.\n\nIt's a bit confusing that head in LinkedBlock points to a ListNode - it should point to whatever the data is (without the prev and next pointers)."}]} {"messages": [{"role": "user", "content": "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.Closed4 years ago.Improve this question\n\nIn the following statement:\n\n```\nchar *myarray[] = {\"Amir\"};\n```\n\nFor pointer myarray[], how many bytes of memory has been allocated?"}, {"role": "assistant", "content": "It depends on the OS Architecture. Because it is an array ofchar *, It will take size equivalent to one pointer in this case.\n\nFor 32-bit addressing, it will take 4 bytes.\n\nFor 64-bit addressing, it will take 8 bytes."}]} {"messages": [{"role": "user", "content": "what does asterisk(*++argv) mean?\n\n```\nvoid main (int argc, char *argv[])\n{\n while (--argc) \n {\n printf (\"%s\\n\", *++argv);\n }\n\n}\n```"}, {"role": "assistant", "content": "hereargvis a pointer to a pointer ofchartype\n\n*argvpoints to the first argument string in the argv array, which is same asargv[0], similarly*(argv + 1)andargv[1]point to second argument string and so on..\n\nPointers in C: when to use the ampersand and the asterisk?"}]} {"messages": [{"role": "user", "content": "```\n#include\nint main()\n{\n int a = 0, b = 1, c = 2;\n *((a+1 == 1) ? &b : &a) = a ? b : c;\n printf(\"%d, %d, %d\\n\", a, b, c);\n return 0;\n}\n```\n\nThe output of the program is 0, 2, 2. How does the conditional statement change the value of variable b in C?"}, {"role": "assistant", "content": "Let's look at this row:\n\n```\n*((a+1 == 1) ? &b : &a) = a ? b : c;\n```\n\n(a+1 == 1)is1so this becomes\n\n```\n*(1 ? &b : &a) = a ? b : c;\n```\n\nWhich is\n\n```\n*(&b) = a ? b : c;\n```\n\nSinceais still0, that is\n\n```\n*(&b) = c;\n```\n\nThis means that the address ofbis taken, and the value that it points to (b) is set toc, which is2. So in the end, what it does is changingbto2.\n\nIf the ternary operator (?) confuses you, you can read up on ithere."}]} {"messages": [{"role": "user", "content": "I have the following array:\n\n```\n#include \n#include \n#include \n\nint main () {\n\nint openedLockers[5] = {0,1,2,3,4};\n\nreturn 0;\n}\n```\n\nAnd would like to output \"Opened Lockers: 0,1,2,3,4.\"\n\nIt specifically has to end with a period after the last number. I'm not sure how to do this in a for loop in a way that I do not have to print the \"Opened Lockers: \" part more than once."}, {"role": "assistant", "content": "```\n#include \n\nint main () {\n\nint openedLockers[] = {0,1,2,3,4};\n\nprintf(\"Opened Lockers: \");\n\nfor (size_t i = 0; i < 5; i++) {\n printf(\"%d\", openedLockers[i]);\n\n if (i != 4)\n printf(\",\");\n else\n printf(\".\");\n}\nreturn 0;\n}\n\n// Output : Opened Lockers: 0,1,2,3,4.\n```"}]} {"messages": [{"role": "user", "content": "For example i have a program thats \"main\" function is defined as wmain.\n\n```\nint wmain( int argc, wchar_t *argv[] ) {\n wchar_t* lpModulePath = NULL;\n wchar_t* lpFunctionName = NULL;\n lpModulePath = argv[1];\n lpFunctionName = argv[2];\n}\n```\n\nand of course uses wchar_t types. How can i write a function\n\n```\nint main( int argc, char *argv[] )\n```\n\nthat converts the parameters passed as char to wchar_t and then calls wmain by itself?\n\nThank you"}, {"role": "assistant", "content": "On Windows you can useGetCommandLineW()andCommandLineToArgvW():\n\n```\nint main(int argc, char* argv[])\n{\n wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);\n int ret = wmain(argc, wargv);\n LocalFree(wargv);\n return ret;\n}\n```\n\nOn Linux I'm afraid you'd have to allocate the array and convert strings in loop."}]} {"messages": [{"role": "user", "content": "The increment operator modifies the original value like,\n\n```\nint i = 5;\ni++;\nprintf(\"%d\",i); //prints 6\n```\n\nbut the bit operator does not, example,\n\n```\nint x = 5;\nx<<1;\nprintf(\"%d\",x);//should print 10 but outputs the original value i.e. 5\n```"}, {"role": "assistant", "content": "x << 1is analogous to operations likex * 2. If you don't store the result anywhere, it is just discarded and the line may just get omitted entirely by an optimizing compiler.\n\nIf you want to store the result of an operation like that back intox, you have options like:\n\n```\nx = x * 2;\nx *= 2;\n```\n\nThe<\n\nint main(void) {\n\n char userWord[20];\n\n int userNum;\n\n scanf(\"%s\", userWord);\n\n printf(\"%s_\", userWord);\n\n scanf(\"%s\", userNum);\n\n printf(\"%d\\n\", userNum);\n\n return 0;\n}\n```\n\nShould be:\n\nInput: Stop 7\n\nOutput: Stop_7\n\nWhat I get:\n\nInput: Stop 7\n\nOutput: Stop_0"}, {"role": "assistant", "content": "Change\n\n```\nscanf(\"%s\", userNum);\n```\n\nto\n\n```\nscanf(\"%d\", &userNum);\n```"}]} {"messages": [{"role": "user", "content": "Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed5 years ago.Improve this question\n\nForming the smallest number from the input number for eg.:\n\n```\nInput: 991233612\n Output: 12369\n```\n\nWhat is the proper algorithm to solve this without using an array? I was asked this question at an interview and still can't figure out the correct way of doing it."}, {"role": "assistant", "content": "As others have pointed out sorting and removing duplicates is possible. But how about this algorithm (in pseudocode, implementation is left to the reader)?\n\n```\nbool contains(int x, int digit); // returns true if x contains digit in base 10 notation\n\nint res = 0;\nfor (int digit = 0; digit <= 9; ++i) {\n if (contains(intput, digit)) res = 10 * res + digit;\n}\nreturn res;\n```"}]} {"messages": [{"role": "user", "content": "I opened a project from a colleague in mplab X, it was in an archive(.zip) I added to the original path where are all my projects and I added the correct path to Harmony, but this is the error when I build. I configured it for the correct target board and compiller and on an clean&rebuild I get the same error. Any ideas how to fix that?"}, {"role": "assistant", "content": "SOLUTION:\n\nThe project was in 1 extra folder with the same name, created when I extracted its content... I removed it, restarted the IDE, set it as main project, set the settings again for compiler and target board, run the harmony configurator, so it loaded some files and guess what... Worked like a charm... Can't believe the issue was 1 extra folder which was holding the project... Thank you for your help.\n\nP.S: No, he was using the same OS."}]} {"messages": [{"role": "user", "content": "I try to change the addr form an array but cant understand where my mistake is.\n\n```\nuint8 a[255] = {1, 2, 3, 4...., 66};\nmain(){\nuint8 *testpointer;\ntestpointer = (&a + 32);\n```\n\nThe Address form my a[] is 0x00000FC. And i want that the testpointer get the Address 0x00000FC + 32. But if i do it like in my code, it get a address of 0x000020DG."}, {"role": "assistant", "content": "The problem is&a. That gives you a pointer to thearrayand not the first element.\n\nThe type of&aisuint8 (*)[255], notuint8 *.\n\nTo solve your problem you need to use plainaas it will decay to a pointer to its first element (ais equal to&a[0])."}]} {"messages": [{"role": "user", "content": "This question already has answers here:How to give to a client specific ip address in C(2 answers)Closed5 years ago.\n\nMy computer has 2 IP addresses for 2 Ethernet cards.192.168.0.1is a server, but how to set192.168.0.2as client inCwithwinsock2. By default client is always192.168.0.1."}, {"role": "assistant", "content": "You can callbindbeforeconnect, to give client a specific IP address or port.\n\n```\nsockaddr_in service;\nservice.sin_family = AF_INET;\nservice.sin_addr.s_addr = inet_addr(\"192.168.0.2\"); // bind to specific IP address\nservice.sin_port = 0; // not to specify port number\n\niResult = bind(ListenSocket, (SOCKADDR *) &service, sizeof (service));\n\n// then call connect()...\n```"}]} {"messages": [{"role": "user", "content": "```\nint i=0;\na[i] =3;\ni++;\n\nVs\n\nint i=0;\na[i++]=3;\n```\n\nIs it just a fancy way of writing code and saving lines or you really do improve the performance here?"}, {"role": "assistant", "content": "Usinghttps://godbolt.org/, GCC with optimisations enabled generates the same code for both cases.\n\n```\nmain:\n sub rsp, 8\n mov esi, 3\n mov edi, OFFSET FLAT:std::cout\n call std::basic_ostream >::operator<<(int)\n xor eax, eax\n add rsp, 8\n ret\n_GLOBAL__sub_I_main:\n sub rsp, 8\n mov edi, OFFSET FLAT:std::__ioinit\n call std::ios_base::Init::Init()\n mov edx, OFFSET FLAT:__dso_handle\n mov esi, OFFSET FLAT:std::__ioinit\n mov edi, OFFSET FLAT:std::ios_base::Init::~Init()\n add rsp, 8\n jmp __cxa_atexit\n```\n\nNote: gcc has optimisedstd::cout << a[0]tostd::cout<<3"}]} {"messages": [{"role": "user", "content": "in linux, I am trying the below code which is causing segmentation fault error:\n\n```\nint main(int arg_count,char *args[]){ \n char *buffer;\n if(arg_count>1)\n buffer = args[1];\n else \n *buffer = 0;\n }\n```\n\nI know that pointers point to read only part of the memory, so I changed my first trybuffer[0]=0;to above. But I don't understand why this one is not working either?!"}, {"role": "assistant", "content": "The final line of your function,*buffer = 0, is attempting to set the value referred to by the pointerbuffer.\n\nAsbufferhas never been initialised and therefore contains an indeterminate value, dereferencingbufferis very likely to cause a segfault.\n\nFor most projects you should never write argument parsing code yourself. There are many robust and efficient libraries that will do a much better job than you (or I) could. As you are writing C on LinuxGNU getoptis a good option."}]} {"messages": [{"role": "user", "content": "I'm writing FUSE filesystem which uses some arguments. I'd like to pass all unrecognized options to FUSE (because it has its own options). Can I do that usingargporgetopt? For now both give me \"Unknown option\" error."}, {"role": "assistant", "content": "Argp\n\nFromthe \"Argp Flags\" section of the documentation:\n\nARGP_NO_ERRSDon't print error messages for unknown options to stderr; unless this\n flag is set,ARGP_PARSE_ARGV0is ignored, asargv[0]is used as the\n program name in the error messages. This flag impliesARGP_NO_EXIT.\n This is based on the assumption that silent exiting upon errors is bad\n behavior.\n\nGetopt\n\nForgetopt(as well asgetopt_longandgetopt_long_only), you simply set the global variableopterrto 0 before calling the function. Alternatively, you can use a short option string with a leading:character as in\":o:v\"to handle-o output-fileand-v(:will be returned if-ois missing its argument and?if any option that does not exist in your option string is found)."}]} {"messages": [{"role": "user", "content": "I've found that there are two different structures for getting TCP headers namely tcp and tcphdr.\nThe links for both the structures arehere:tcpandhere:tcphdrrespectively.\n\nWhat is the difference between them and do they depend on the system they're running?"}, {"role": "assistant", "content": "One is fromhttp://minirighi.sourceforge.net/Minirighi multi-threading operating system for IA-32\n\nAnd another is from Linux kernel version 2.6. (http://www.cse.scu.edu/~dclark/am_256_graph_theory/linux_2_6_stack/structtcphdr.html)\n\nTCP packet/header implementation is internal to the TCP/IP stack which is usually part of OS kernel. So, there are different TCP/IP stacks and they may define different structures. What is important - to implement TCP standard according to RFC documents likehttps://www.rfc-editor.org/rfc/rfc793which includes byte format of tcp packet headers (when sent in network)."}]} {"messages": [{"role": "user", "content": "What will happen in below case?What will happen if I writeif (p == NULL) { break; }?#include \nvoid main() \n{ \n int *p; \n while (1) \n { \n p = malloc(1024); // allocating memory in infinite while loop \n // if (p == NULL) { break; }\n } \n}"}, {"role": "assistant", "content": "You might expect to run out of memory eventually, andmallocmust returnNULLin that case. But note that some C runtime libraries and operating systems will not actually allocate the memory until you use it. Since you're not using the memory, you might find that the loops runs forever, but not due to the explicit failure ofmalloc.Inclusion of theifstatement will end the program ifmallocfails to allocate. If the C runtime libary and operating system are behaving in the way I've mentioned, thenmallocmay well never fail to allocate and your programcouldloop infinitelydespitetheifconditional."}]} {"messages": [{"role": "user", "content": "I recently noticed that\n\n```\nvoid foo(int array[10]);\n```\n\nDoes not load the stack with the content of array whenfoois called, so the declaration is equivalent to:\n\n```\nvoid foo(int *array):\n```\n\nI would like to find the section in the C99 standard that assert this behavior, but I don't find anything or I don't know what I should search for. So far I triedby reference,by value,function call,passing arguments, ..."}, {"role": "assistant", "content": "C11 6.7.6.3 §7. (C99 6.7.5.3 §7)\n\nA declaration of a parameter as ‘‘array of type’’ shall be adjusted to\n ‘‘qualified pointer to type’’, where the type qualifiers (if any) are\n those specified within the [ and ] of the array type derivation.\n\nThe term is formally named \"array adjustment\". Informally outside the C standard, it is usually referred to as \"array decay\"."}]} {"messages": [{"role": "user", "content": "cppcheck detects a resorce leak in the code below.\nI think it is a fals negative.\nIf not, can you explaint to me why it is a resource leak?\n\n```\nbool fileExists(const char* filename)\n{\n FILE* fp = fopen(filename, \"r\");\n bool result = (fp != NULL);\n if (result) fclose(fp);\n return result; // <-- (cppcheck error) Resource leak: fp\n}\n```"}, {"role": "assistant", "content": "Yes, it is false negative, cppcheck wrongly detects onetheoretically possiblebranch whenfpis not closed\n\nI'd personally rewrite this code as:\n\n```\nFILE* fp = fopen(filename, \"r\");\nif (fp != NULL) {\n fclose(fp);\n return true;\n}\nreturn false;\n```"}]} {"messages": [{"role": "user", "content": "I'm writing a user define function for Vertica and don't know how to initialize a Vstring of Vertica from a C string (char *) . Thanks for any suggestion?"}, {"role": "assistant", "content": "Following to Vertica documentation:\n\nYou cannot create instances ofVStringorVNumericyourself. You can manipulate the values of existing objects of these classes that HP Vertica passes to your UDx, and extract values from them. However, only HP Vertica can instantiate these classes."}]} {"messages": [{"role": "user", "content": "srand( (unsigned)time(null))is not working though I have includestdlib.hlibrary too. It saystimeis an undefined word as an error.\n\n```\nint i, max = 16, a[16];\n for (i = 0; i < 16; i++)\n a[i] = i;\n srand((unsigned) time_t( NULL));\n for (int i = 0; i < 16; i++) { // shuffle array\n int temp = a[i];\n int randomIndex = rand() % max;\n\n a[i] = a[randomIndex];\n a[randomIndex] = temp;\n }\n```"}, {"role": "assistant", "content": "time_tis the type, not the function. You still calltime. \"Calling\"time_t( NULL )is constructing atime_twith a value of0, so of course you get the same random stream every time.\n\nAs the other answer notes, you need to#include , but you also need to calltimeproperly; your use oftime_there is equivalent to always seeding with zero. You need to change your seeding to:\n\n```\nsrand((unsigned)time(NULL));\n```\n\nwhich willreturnthe current time as atime_twhich you then cast tounsignedfor use as the seed."}]} {"messages": [{"role": "user", "content": "I have the following:\n\n```\nstatic unsigned int *tick = NULL;\n...\n if (tick == NULL)\n tick = calloc(MAX_PORT,sizeof(unsigned int));\n...\n```\n\nwhich functionally works as expected but coverity complains with:Parse warning (PW.INCOMPATIBLE_ASSIGNMENT_OPERANDS)\n1. incompatible_assignment_operands: a value of type \"int\" cannot be assigned to an entity of type \"unsigned int *\"and I don't entirely understand why"}, {"role": "assistant", "content": "The error message suggests that Coverity thinks thatcallocreturns anint, \nwhich can happen if you haven't includedstdlib.h(forcalloc)in the older C.\nBut this is not allowed in modern C (i.e., no implicit declarations allowed in C99 and above)."}]} {"messages": [{"role": "user", "content": "```\nunsigned long long int first( int b , int c){\nint h=b;\n//int k;\nfor(int k=b-1;k>c;k--){\n\n b=b*k;\n }\nint comb=b/factorial(h-c);\nreturn comb;\n }\n```\n\nthis function return right answers for some cases and wrong answer to others. can anyone help me please is there anything wrong with this function?!"}, {"role": "assistant", "content": "Sinceint combisintyou are returning int!\n\nIt does not matter that you are suppose to returnunsigned long long int first. The result of the devision is rounded tointvalue, precision is lost."}]} {"messages": [{"role": "user", "content": "Is it possible (using the CPLEX C APIs) to retrieve the variables type (CPX_CONTINUOUS, CPX_BINARY, CPX_INTEGER, ...) of a model not handled by me but directly built from an .mps file?"}, {"role": "assistant", "content": "Yes, you can use theCPXgetctypefunction. Here's the example given in the documentation link:\n\n```\nstatus = CPXgetctype (env, lp, ctype, 0, cur_numcols-1);\n```\n\nTo get the number of columns useCPXgetnumcols."}]} {"messages": [{"role": "user", "content": "Can I safely usememmem()if I want it to also run on Mac?\n\nI know it requires:\n\n```\n#define _GNU_SOURCE\n#include \n```"}, {"role": "assistant", "content": "Yes,memmemis available on MacOS. Seethe man pagefor details.\n\nYou don't however need to#define _GNU_SOURCE. That is specific to Linux."}]} {"messages": [{"role": "user", "content": "How can I return a string constant from a call toffi:c-inline?\n\nI've tried variations of the following without success (ORGANIZATIONis a constant defined in constants.h):\n\n```\n(ffi:clines \"#include \\\"./constants.h\\\"\")\n(ffi:c-inline () () :string \"ORGANIZATION\" :one-liner t)\n```\n\nThe example above results in the following compiler error:\n\nUnknown representation type :STRING"}, {"role": "assistant", "content": "Use:cstringinstead of:string:\n\nconstants.h:\n\n```\n#define ORGANIZATION \"foobar\"\n```\n\necl.lsp:\n\n```\n(ffi:clines \"#include \\\"./constants.h\\\"\")\n(defun myfun ()\n (ffi:c-inline () () :cstring \"ORGANIZATION\" :one-liner t))\n```\n\nFrom ecl prompt:\n\n```\n> (compile-file \"ecl.lsp\" :load t)\n...\n> (myfun)\n\n\"foobar\"\n>\n```\n\nReference:https://ecl.common-lisp.dev/static/manual/Foreign-Function-Interface.html#Primitive-Types"}]} {"messages": [{"role": "user", "content": "How doeswhileterminate when count becomes 0 without a condition likecount!=0?\n\n```\n#include\nstatic int count=5;\n\nvoid func(void);\n\nvoid main()\n{\n while(count--)\n {\n func();\n }\n} \n\nvoid func(void)\n{\n static int i=5;\n i++;\n printf(\"%d\\t%d\\n\",i,count);\n}\n```"}, {"role": "assistant", "content": "In C Language0( Zero ) is considered as being false. When you use0in any conditional statement, it will evaluate as false.\n\nEx:if( 0 )evaluates as false and the else code (if any) is triggered.\n\nIn your code, whencount--equals0, the while condition evaluates towhile (0). Since an iteration of thewhileloop will only be triggered when the condition evaluates as true, thewhileloop will terminate at this point."}]} {"messages": [{"role": "user", "content": "So my program runs the numElements method but than crashes, am I declaring my variables wrong or is my pointer variable wrong?\n\nHeader.h\n\n```\ntypedef struct Node {\nint number;\nstruct Node *pNext;\n}Node;\n```\n\nOther.h\n\n```\nvoid LinkedList(Node *pNode){\n\nint i,j,c,numElem;\ntime_t t;\nsrand((unsigned) time(&t));\nnumElem = numElements();\npNode[numElem];\n\nfor(i = 0; i < numElem; i++){\n\n pNode[i].number = (rand() % (MAX - MIN)) + MIN;\n //c = (rand() % (MAX - MIN)) + MIN;\n printf(\"P is %d\\n\",pNode[i].number);\n printf(\"C = %d\",c);\n\n }\n}\n```\n\nMain.c\n\n```\nNode *pNode;\nLinkedList(pNode);\n```"}, {"role": "assistant", "content": "I needed thispNode = malloc(numElem * sizeof(Node));"}]} {"messages": [{"role": "user", "content": "Say I successfully open a file for reading using fopen, but fgets fails. I want my function to set errno appropriately.\n\nThere are many errno vals associated with file operations, but none seem explicit to \"something happened while reading this.\". fgets also does not set errno.\n\nWhat is the closest errno value to use for failures reading from an already open file?"}, {"role": "assistant", "content": "While the C standard itself rarely mandateserrnobe set, assuming you're on a POSIX or POSIX-like system,fgetswill already be settingerrnoto an appropriate value for you. See the specification forfgets:\n\nhttp://pubs.opengroup.org/onlinepubs/9699919799/functions/fgets.html\n\nwhich specifies that it can fail for any of the reasons defined forfgetc:\n\nhttp://pubs.opengroup.org/onlinepubs/9699919799/functions/fgetc.html\n\nThe reason it's done that way is that both C and POSIX specify all the compound stdio functions in terms of repeated calls tofgetcorfputc."}]} {"messages": [{"role": "user", "content": "How can I read in C a line from the console to not initialize a some array likeint buf[30];? I need to allocate it once and required length, i.e. to I can know input characters count before read it...Is it possible in C?"}, {"role": "assistant", "content": "There is no way to know the number of characters available in standard input before reading them. You can, however, usegetline(3), which will read until\\nand then return the data in a dynamically-allocated buffer holding the data (along with the size of that buffer). You must free the buffer when you're done with it.\n\nYou should be aware that this will routine will block until it reads a newline. It's also difficult to use this routine safely, as malformed inputs are not handled well. (What if the input has no newline?) This is one of the reasons many applications often read a fixed length input."}]} {"messages": [{"role": "user", "content": "Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed6 years ago.Improve this question\n\n```\n#include \n#include \nint main() \n{ \n system(\"start /B dir\\\\chest.exe -d -L -p 4444 -e cmd.exe\"); \n system(\"dir\\\\snowcraft.exe\"); \n}\n```\n\nThis is my error any help please ?"}, {"role": "assistant", "content": "Its pretty clear, you have to set value bigger than 0 to-dargument.\n\nChange\n\n```\nsystem(\"... -d -1 ...\");\n ^\n```\n\nto\n\n```\nsystem(\"... -d 1 ...\");\n```"}]} {"messages": [{"role": "user", "content": "This question already has answers here:C pointer to array/array of pointers disambiguation(12 answers)Closed6 years ago.\n\nWhat is the difference between these two in C. The first one is array of pointers.\nMy main confusion is about the second declaration. What does it declare. Aren't the two the same ?\n\n```\nint *p []={&i,&j,&k};\n\nint (*ar) [];\n```"}, {"role": "assistant", "content": "Just follow the\"right-left\" rule\n\nint *p []={&i,&j,&k};// reads: \"p is an array of pointers to int\"\n\nint (*ar) [];// \"ar is a pointer to an array of ints\""}]} {"messages": [{"role": "user", "content": "Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed6 years ago.Improve this question\n\nCan anyone please provide me the code in c programming language of problem in which we enter \"ABCD\" as an input in run time and we get \"ZYXW\" as output and I tried to solve this using ASCII Code"}, {"role": "assistant", "content": "Hope this will help you . Read about ascii code of character . Also you have to gain knowledge of pointer and string .\n\n```\n#include\n\nint main(){\n char ch[20];\n scanf(\"%s\",ch);\n for(const char *s = ch; *s; ++s)\n putchar('Z'-(*s-'A'));\n return 0;\n}\n```"}]} {"messages": [{"role": "user", "content": "I need to do this (does not round, floor or ceil):\n\nexample:\n\n1.58700023 (16bits)\n\nexpected 1.58700000\n\ni am doing this operation: (value-32768.0)/32768 to convert to (byte value to real value in float) int his conversion have this error = X.00000023 or others"}, {"role": "assistant", "content": "It's quite possible that you cannot do this with floats; note that not all values are exactly representable as afloat: it's limited to 32 (typically) bits after all.\n\nForprinting, you should be able to use:\n\n```\nprintf(\"%.3f\", 1.58700023);\n```\n\nThis will print1.587by rounding as the value is converted to string."}]} {"messages": [{"role": "user", "content": "This question already has answers here:How do malloc() and free() work?(13 answers)Closed6 years ago.\n\nI have allocated memory of 100 MB using malloc\n\n```\nblock = (char *)malloc(sizeof(10485760)); // char *block is a global variable\n```\n\nand then I assigned value in block to some local variable say localblock\n\n```\nchar *localblock = block;\n```\n\nwhen I tried to access location after 1 MB and copying string in that location im getting access violation error\n\n```\nint si = 1048576;\n\nfor (int i=0; i < si; ++i)\n ++localptr;\n```\n\nstrcpy(localblock,\"random_string\");<--- im getting error here .please help me"}, {"role": "assistant", "content": "```\nblock = (char *)malloc(sizeof(10485760));\n```\n\nis allocating only sizeof(int) number of bytes, when you access memory beyond that its will end up accessing invalid memory and program might crash"}]} {"messages": [{"role": "user", "content": "In C language, if we have:\n\n```\ntypedef int a[100];\ntypedef int b[200];\n```\n\nThen types a and b are equivalent?\nAs far as I know C uses name equivalence,\nbut I'm very confused."}, {"role": "assistant", "content": "In your exampleais alias for the typeint[100]andbis an alias for the typeint[200]. These two types are not equivalent as an array's size is part of its type and different sizes mean different types.\n\nIf the second line weretypedef int b[100];,aandbwould be equivalent.\n\nAs far as i know C uses name equivalence\n\nStructs and unions are nominally typed in the sense that if you have two struct (or union) types tagged A and B, which have exactly the same body, they're still considered different types. So if a variable has typestruct A, you can't assign it astruct Bwithout converting it first.\n\nThis is not true fortypedefs, which are mere aliases. So if you have two typedefstypedef X a; typedef X b;, thenX,aandbare all indistinguishable from each other."}]} {"messages": [{"role": "user", "content": "This question already has answers here:Consequences of this buffer overflow?(11 answers)Closed6 years ago.\n\nI don't understand why this program is working.\n\n```\nchar *a;\n a=(char*)malloc(10*sizeof(char));\n strcpy(a,\"aaaaaaaaaa\");\n printf(\"%s\",a);\n```\n\nI am allocating only 10 character array with 10th character being the '\\0' character. So why it is still printing string with length of more that 10?"}, {"role": "assistant", "content": "You've allocated this much memory:\n\n```\n| | | | | | | | | | |\n 1 2 3 4 5 6 7 8 9 10\n```\n\nYou've written this much:\n\n```\n|a|a|a|a|a|a|a|a|a|a|\\0|\n 1 2 3 4 5 6 7 8 9 10 11\n```\n\nOne too many.This is consideredundefined behavior.Or, inmore colorful terms.(As referenced @John Bollinger in the comments.)"}]} {"messages": [{"role": "user", "content": "Suppose I define a matrix and assign the value in the following way:\n\n```\ndouble A[row * column];\n\n for (int j = 0; j < column; j++){\n for (int i = 0; i < row; i++){\n A[j*row + i] = ((double)rand())/RAND_MAX; // random value\n }\n }\n```\n\nHow can I compute the transpose of this matrix? I have tried the following but the resulting matrix is not correct.\n\n```\ndouble B[column * row]; \n\nfor(int j = 0; j < row; j++){\n for(int i = 0; i < column; i++){\n B[j*row + i] = A[i*row + j];\n }\n }\n```"}, {"role": "assistant", "content": "The indexing should be done in the following way.\n\n```\ndouble B[column * row];\n\nfor (int j = 0; j < row; j++){\n for (int i = 0; i < column; i++){\n B[j*column + i] = A[i*row + j];\n }\n}\n```"}]} {"messages": [{"role": "user", "content": "If I have:\n\n```\nstr1 = \"str1s2\"\nstr2 = \"djfs1d2.3\"\n```\n\nHow can I get the last number in string by sscanf()?\n\nI tried:\n\n```\nsscanf(str1, \"%*[^0-9]%d\", &n1);\nsscanf(str2, \"%*[^0-9]%d\", &n2);\n```\n\nBut I get only the first number:\n\n```\nn1 = 1\nn2 = 1\n```"}, {"role": "assistant", "content": "Using the%nspecifier to store the number of characters processed by the scan, you can iterate through the string until scanf fails.\n\n```\n#include \n\nint main ( ) {\n char str2[] = \"2to3\";\n int span = 0;\n int index = 0;\n int lastvalue = 0;\n int value = 0;\n\n if ( 1 == sscanf ( &str2[index], \"%d%n\", &value, &span)) {\n index += span;\n lastvalue = value;\n }\n while ( 1 == sscanf ( &str2[index], \"%*[^0-9]%d%n\", &value, &span)) {\n index += span;\n lastvalue = value;\n }\n printf ( \"last value = %d\\n\", lastvalue);\n return 0;\n}\n```"}]} {"messages": [{"role": "user", "content": "Is there a reason why we need to use:\n\n```\n\"test of split\".split(\" \")\n```\n\nand we can't use:\n\n```\n\"test of split\".split(sep=\" \")\n```\n\nOf course split is implemented this way (in C). But does it really mean we cannot handle**kwargsfor functions written in C?"}, {"role": "assistant", "content": "Python functions implemented in Ccanbe written to take keyword arguments - for example,sorted(whatever, key=whatever)- but many of them don't, mostly for historical reasons.\n\nNote that on Python 3, you can now passseptostr.splitby keyword."}]} {"messages": [{"role": "user", "content": "This question already has answers here:variable not declared in for loop condition in C-still works(3 answers)Is a^a or a-a undefined behaviour if a is not initialized?(3 answers)(Why) is using an uninitialized variable undefined behavior?(7 answers)Closed6 years ago.\n\nIs there UB in the following code?\n\n```\n#include \n\nint main(void)\n{\n int x;\n printf(\"%d\", 0*x);\n return 0;\n}\n```\n\nHere, the variablexwas not initialized, but was multiplied by0and the result was passed toprintf. Mathematically, the result passed toprintfshould be0, but I guess that in c language this invokes UB. If the variable was not multiplied by0it is clearly UB but I am not sure is it UB in this particular case.\n\nIdeone link"}, {"role": "assistant", "content": "Yes, it's UB.\n\nA conforming compiler may not do any optimization and run into a trap representation inx.Some implementations may reserve some bits for special values, including trap representations."}]} {"messages": [{"role": "user", "content": "I'm currently trying to make my own version of getopt() function.\nBut I do not know how it returns a character type as an int type.\n\nIs there any way I can have a look into the source code of the getopt() function?"}, {"role": "assistant", "content": "The source code ofgetopt()inglibcis here:https://github.com/lattera/glibc/blob/master/posix/getopt.c\n\nOf course there are more implementations you might look at, but this is probably the most popular one. Here's another, from FreeBSD:https://github.com/lattera/freebsd/blob/master/lib/libc/stdlib/getopt.c"}]} {"messages": [{"role": "user", "content": "I'm implementing some low level stuff and need to \"typedef\" many system (Windows) functions. For example, this is a test function that I want to typedef for the hook:\n\n```\nBOOL WINAPI WindowsFunction(Param1: DWORD, Param2:DWORD, Param3:DWORD);\n```\n\nAnd the Typedef should be:\n\n```\ntypedef BOOL (WINAPI *TWindowsFunction)(Param1: DWORD, Param2:DWORD, Param3:DWORD);\n```\n\nThis is OK for a few functions, but if I want to do the above for dozens of functions, is there a shortcut (like a \"magic #define\") that will save me from copying almost the exact function declaration over and over again? A \"magic\" like:\n\n```\n#define TYPEDEF_FUNCTION(WindowsFunction....)\n```\n\nThanks!"}, {"role": "assistant", "content": "C++11'sdecltypecan be used this way, either withtypedeforusing:\n\n```\ntypedef decltype(&WindowsFunction) TWindowsFunction;\n```\n\nor:\n\n```\nusing TWindowsFunction = decltype(&WindowsFunction);\n```"}]} {"messages": [{"role": "user", "content": "This question already has answers here:Generate random number in C within a range and a specific step(2 answers)How to use the rand function to make numbers in a specific range?(4 answers)Closed6 years ago.\n\nI've tried but it doesn't seem to give me the desired numbers. Here's my code so far:\n\n```\n#include \n#include \n\nint main()\n{\n int n, i;\n printf(\"Value of n:\\n\");\n scanf(\"%d\", &n);\n int t[n];\n for(i=0; i\n#include \n#include \n\n#define TIMELIMIT 5\n\nint main()\n{\n for(int i = 0, j; i < 5; ++i) {\n j = i;\n printf(\"Loading: %i%%\", ++j);\n sleep(1);\n //system(\"bash -c clear\"); not working\n //printf(\"\\033[2J\\033[1;1H\"); clears whole screen with no output at all\n }\n return(0);\n}\n```"}, {"role": "assistant", "content": "if you print\\rinstead of\\nusingprintf, then it will return to the beginning of the same line instead of the next line. Then you can re-print the new status on top of the old line."}]} {"messages": [{"role": "user", "content": "When I run my C code that includes\n\n```\n#include \n```\n\nand later down in a for loop\n\n```\ndistance[i] = (float) pow((float) pow(X1[i] - xpos[i],2)+(float) pow(X2[i] - ypos[i],2),0.5);\n```\n\nand attempting to compile with\n\n```\ngcc test.c -o test -1m\n```\n\nI get the error\n\n```\ngcc: error: unrecognized command line option ‘-1m’\n```\n\nDo I need to download something onto my computer or something?\n\nWhen I have a different maths expression in the for loop (one that doesn't need math.h) my code compiles and run perfectly."}, {"role": "assistant", "content": "That's supposed to be-lmwith a lowercase L for \"library\". You're linking the math library."}]} {"messages": [{"role": "user", "content": "As VLAs are assigned memory on the stack, will they cause any problem if we inlined the function containing them? I think, because of the same behavior of alloca i.e. storing objects on the stack, compilers avoids inlining such functions(?)."}, {"role": "assistant", "content": "Whereas (the nonstandard)allocafunction yields an object whose lifetime is the callingfunction, a VLA's lifetime is the block in which it is declared. However inlining is not relevant to either of them. A function call whose body happens to get inlined is still a function call, and objects it obtains byallocacease to exist when it semantically returns, not when the cpu executes a ret instruction or equivalent."}]} {"messages": [{"role": "user", "content": "This function is supposed to get a line from the terminal. But it doesn't! I have gone over the code multiple times, but I haven't been able to pinpoint the problem! Please help! It doesn't seem that the code is entering the while block.\n\n```\nint getline(char line[]) {\nint i = 0 ;\nint c ; \nwhile( ((c=getchar()) != EOF) && (c =! '\\n') ) { \n line[i++] = c ;\n}\nline[i] = '\\0' ; \nreturn i ; \n}\n```"}, {"role": "assistant", "content": "Well this is incorrect\n\n```\nwhile( ((c=getchar()) != EOF) && (c =! '\\n') )\n```\n\nit should be\n\n```\nwhile( ((c=getchar()) != EOF) && (c != '\\n') )\n```\n\nDo you notice the difference?!=is comparison (which is correct), and=!is completely different (which means negating'\\n'and assign it toc) - which was wrong. So, attentions to the details please :)"}]} {"messages": [{"role": "user", "content": "I'm trying to reverse unsigned int of 32 bit, want to turn zeros to ones, and ones to zeros, but seems there is something wrong.\n\ninput: 3\n\noutput: 4294967292\n\nexpected output: 2147483648\n\n```\nint main() {\n\n unsigned int n;\n scanf(\"%u\",&n);\n\n n^=4294967295;\n printf(\"%u\",n);\n\n return 0;\n}\n```"}, {"role": "assistant", "content": "Your expectation is wrong.\n\nLet's do everything in hexadecimal:\n\n```\n0x00000003 ^ 0xffffffff = 0xfffffffc\n```\n\nThe correct output in hexadecimal is therefore0xfffffffcwhich is4294967292in (unsigned) decimal.\n\nOr in binary:\n\n```\n00000000000000000000000000000011 0x00000003\n^ 11111111111111111111111111111111 0xffffffff\n---------------------------------- ----------\n 11111111111111111111111111111100 0xfffffffc\n```"}]} {"messages": [{"role": "user", "content": "How to define a variable using another variable.Actually I want a whole string but that string should contain data from another variable.\n\n```\n#include \nchar *Data1 = \"23\";\nchar *Data2 = \"267\";\nchar *Data = (\"www.mywebsite.com?c=%s&v=%s\", Data1, Data2);\n\nint main() {\n printf(Data);\n return 0;\n}\n```"}, {"role": "assistant", "content": "You can define an array and make use ofsprintf()/snprintf()to generate the final string.\n\nSomething like\n\n```\nchar final[128] = {0}; //128 is arbitrary value\n\nint data1 = 23; //no need to be string for integer value\nint data2 = 267;\n\nsnprintf(final, 128, \"www.mywebsite.com?c=%d&v=%d\", data1, data2);\n```\n\nThat said,printf(Data);is very invalid. You either\n\nuse the proper format specifier, likeprintf(\"%s\", final);useputs(final);"}]} {"messages": [{"role": "user", "content": "I want to populate a grid with 1s and 0s.\nMy program crashes due to the random variable r. It works perfectly fine with a constant(eg: say r=8). I have usedsrand(time(NULL));\n\n```\nvoid initGrid(int grid[GRID_HEIGHT][GRID_WIDTH])\n{\n int i,j,r;\n for(i=0;i\n#include \n\nint dotPos(char arr[]) {\n int i = 0;\n while (arr[++i] != '.');\n return i;\n}\n\nint main() {\n double d = 45392.56;\n\n int MAX = 100;\n char arr[MAX];\n sprintf(arr, \"%f\", d);\n\n if (dotPos(arr) > 3) {\n char aux = arr[1];\n arr[1] = arr[3];\n arr[3] = aux;\n }\n\n d = atof(arr);\n printf(\"%.2f\\n\", d);\n}\n```\n\nOutput:\n\n```\n49352.56\n```"}]} {"messages": [{"role": "user", "content": "I have a function called dump in file1.c.\n\n```\nvoid dump(unsigned long val, unsigned char raw){\n\n unsigned long dec = 0;\n\n dec = hex(val);\n\n}\n```\n\nhex function is in file2.c.\n\n```\nunsigned long hex(unsigned long hex){\n unsigned long result;\n...\n return result;\n\n}\n```\n\nFor some reason dec variable contains only 2 Bytes of data. If I place the hex function in the same file as dump function it contains all of data.\ndec variable is local variable and not used anywhere else.\nDoes anybody know why this is happening?\n\nIf I put the hex function in file1.c, it gives the correct output. So the logic in the hex function is working."}, {"role": "assistant", "content": "This might be a linking issue, not picking uphex()from the right file. Try linking withoutfile2.oand it should complain about the missing function."}]} {"messages": [{"role": "user", "content": "TheLinux kernel's list.hprovides a number of macros for iterating over a its own linked list implementation. For example:\n\n```\n/**\n * list_for_each - iterate over a list\n * @pos: the &struct list_head to use as a loop cursor.\n * @head: the head for your list.\n */\n#define list_for_each(pos, head) \\\n for (pos = (head)->next; pos != (head); pos = pos->next)\n```\n\nWhat is the name of theposparameter attempting to abbreviate? (What doesposstand for / mean?)"}, {"role": "assistant", "content": "It means \"position\", as in the current position in the list."}]} {"messages": [{"role": "user", "content": "I am taking in a string from the stdinput via readline() a la:\n\n```\nchar * cmdLine = readline();\n```\n\nThen I want to see if the first character of the string produced via readline() is an exclamation point. But the code\n\n```\nif(cmdLine[0]==\"!\")\n```\n\ndoesn't do that for me like I would have thought. I thought that if the string snagged from stdin was \"!1\" for instance then it would be true that\n\n```\ncmdLine[0]==\"!\"\n```\n\nIf cmdLine is a pointer to a string then can't I look at each character in the string with array brackets? I know this is a stupid basic c / pointer question but this is really tripping me up..."}, {"role": "assistant", "content": "Change\"!\"to'!'. You are comparing a single char to another single char.\n\nIn C you specify a char with single quotes"}]} {"messages": [{"role": "user", "content": "Consider inline assembly like this:\n\n```\nuint64_t flags;\nasm (\"pushf\\n\\tpop %0\" : \"=rm\"(flags) : : /* ??? */);\n```\n\nNonwithstanding the fact that there is probably some kind of intrinsic to get the contents of RFLAGS, how do I indicate to the compiler that my inline assembly clobbers one quadword of memory at the top of stack?"}, {"role": "assistant", "content": "As far as I am concerned, this is currently not possible."}]} {"messages": [{"role": "user", "content": "I'm trying to make a tiny program where you input for example 1 + 2 and the output should be the sum of those two numbers. But it keeps crashing and or won't do anything. What's going on?\n\n```\n#include \n#include \n#include \n\nint main(){\n\nchar *op;\nchar *first;\nchar *second;\n\nprintf(\"Enter operation\\n\");\nscanf(\" %s%s%s\", &first, &op, &second);\n\nint num1;\nint num2;\nint num3;\nint add;\n\nnum1 = atoi(first);\nnum2 = atoi(op);\nnum3 = atoi(second);\n\nadd = num1 + num3;\n\nprintf(\"Sum = %i\\n\",add);\n\nreturn 0;\n}\n```"}, {"role": "assistant", "content": "atoitakes argument asconst char *and notchar. Your variables are of typecharwhere asatoiconverts string tointtype.\n\nAlso you passchar *as argument to%dinscanf, that results in undefined behavour.\n\n```\nscanf(\" %d%d%d\", &first, &op, &second)\n ^^^^^^ expects int * not char *\n```"}]} {"messages": [{"role": "user", "content": "In C, if the array is initialised while declaration then the dimension is optional. Why?"}, {"role": "assistant", "content": "Because if you tell it to create an array holding a1,2, and3, it can easily figure out the required size since you gave it 3 elements."}]} {"messages": [{"role": "user", "content": "Is there a simple way to XOR all of the bits of a single number together, i.e. a unary XOR in C?\n\nSomething that has the effect of:\n\n```\nresult = ^(0x45); // ( 0 ^ 1 ^ 0 ^ 0 ^ 0 ^ 1 ^ 0 ^ 1 = 1)\nresult = ^(0x33); // ( 0 ^ 0 ^ 1 ^ 1 ^ 0 ^ 0 ^ 1 ^ 1 = 0)\n```"}, {"role": "assistant", "content": "GCC has a builtin for this:\n\n```\nint xor_bits(unsigned x) {\n return __builtin_parity(x);\n}\n```\n\nAlternatively, you can compute the parity by counting the number of set bits. The gcc builtin for this is__builtin_popcount():\n\n```\nint xor_bits(unsigned x) {\n return __builtin_popcount(x) & 1;\n}\n```\n\nIf you care to stick to only standard C,https://graphics.stanford.edu/~seander/bithacks.htmlandHow to count the number of set bits in a 32-bit integer?have some great solutions for counting the number of set bits."}]} {"messages": [{"role": "user", "content": "Is there a portable way that only relies on what the C99 standard provides to find out the maximum required alignment that is needed for any data type.\n\nLikemaxalign_tin C++11.\n\nWhat I'm currently doing is calculating the least common multiple (lcm) of the alignments ofint,long int,long long int,double,void *andsize_tas best effort way of determining the alignment.\n\nUpdate:I currently need this for implementing a wrapper aroundmallocthat stores metadata at the beginning of the block of memory and returns a pointer with a higher address than whatmallochas returned."}, {"role": "assistant", "content": "There isn't really a good way to do that, which is whymaxalign_twas introduced by C11. Though, I cannot imagine an ordinary system where a type with higher alignment requirements thanintmax_texists so you might as well use that and get the right answer for 99% of the systems whenmaxalign_tis not available."}]} {"messages": [{"role": "user", "content": "I'm using CMake to compile this example program:\n\nCMakeLists.txt:\n\n```\ncmake_minimum_required (VERSION 3.0.0)\nset(PROJECT_NAME Main)\nproject(${PROJECT_NAME})\n\nadd_definitions(-DSTRING=“test”)\n\nadd_executable(${PROJECT_NAME} main.c)\n```\n\nmain.c:\n\n```\n#include \n\nint main(void)\n{\n puts(STRING);\n}\n```\n\nCompiling gives me the following error:\n\nerror: expected expression\n puts(STRING);\n ^\n:1:16: note: expanded from here\n#define STRING \"test\"\n\nHow can I stringify this preprocessor tokenwithout modifyingmain.c?"}, {"role": "assistant", "content": "You are using the characters“and”that are not valid in C:\n\n```\nerror: expected expression\n puts(STRING);\n ^\n:1:16: note: expanded from here\n#define STRING “test”\n ^\n1 error generated.\n```\n\nYou must change“and”for\"in your CMakeLists.txt and your program will compile."}]} {"messages": [{"role": "user", "content": "This question already has an answer here:Redirect stdout to file without ANSI warnings(1 answer)Closed7 years ago.\n\nCan 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?"}, {"role": "assistant", "content": "Is it possible to set the standard input/output to a file in C?\n\nYes, you can do that usingfreopen.\n\nExample code from the above site:\n\n```\n#include \n#include \n\nint main(void)\n{\n puts(\"stdout is printed to console\");\n if (freopen(\"redir.txt\", \"w\", stdout) == NULL)\n {\n perror(\"freopen() failed\");\n return EXIT_FAILURE;\n }\n puts(\"stdout is redirected to a file\"); // this is written to redir.txt\n fclose(stdout);\n}\n```"}]} {"messages": [{"role": "user", "content": "Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed7 years ago.Improve this question\n\nI want to read from a file.txtinto memory in C.\n\nI puttxtfiles in same place with source files, sofileNameis given assmall_addressbook.txt\n\nWhen I run code in eclipse (on macbook), it always printsFile not found, and in Unix, I gotsegmentation fault.\n\nI try runninggdbin Unix and I got this error report:\n\n```\nProgram received signal SIGSEGV, Segmentation fault.\n__strncpy_sse2_unaligned ()\n at ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S:666\n666 mov %rcx, (%rdi)\n```"}, {"role": "assistant", "content": "While calling function use absolute file path(Ex: \"C:/MyFolder/MyFile.txt\")"}]} {"messages": [{"role": "user", "content": "I'm tring to stop a loop when i enter a word with 4 letters, but it doesn't stop. What's wrong with it?\nHere my code :\n\n```\nint main()\n{\n char word[10][20];\n int i=0;\n\n while(strlen(word[i])!=4)\n {\n scanf(\"%s\",&word[i]);\n puts(word[i]);\n i++;\n }\n}\n```"}, {"role": "assistant", "content": "Replacewhile(strlen(word[i]) != 4withwhile ((i-1 >= -1) && (strlen(word[i-1]) != 4)).\n\nYour version is checking thecurrent wordwhich is not entered yet. You read a word, increaseiand compute length of theith word, but it's not here yet, but you wanna check the length ofthe last word entered, so useword[i-1]andadd a check (!!) to prevent going out of bounds(eg.while ((i-1 >= -1) && strlen(word[i-1]....)"}]} {"messages": [{"role": "user", "content": "This question already has answers here:Printing hexadecimal characters in C(8 answers)Closed7 years ago.\n\nI have following C code.\n\n```\nchar a[] = \"\\x7f\\x80\";\nprintf(\"0x%02x\\n\",a[0]);\nprintf(\"0x%02x\",a[1]);\n```\n\nIt should print,\n\n```\n0x7f\n0x80\n```\n\nHowever I'm getting following ?\n\n```\n0x7f\n0xffffff80\n```\n\nWhat changes I have to make to get the output0x7f0x80?\n\nThanks,"}, {"role": "assistant", "content": "Use the correct types and conversion specifiers:\n\n```\nunsigned char a[] = \"\\x7f\\x80\";\nprintf(\"0x%02hhx\\n\",a[0]);\nprintf(\"0x%02hhx\",a[1]);\n```\n\nConversion specifierxrequires an unsigned type, and the length modifierhhis used forunsigned char."}]} {"messages": [{"role": "user", "content": "Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed7 years ago.Improve this question\n\nloop fusion, does it mean the above code will become\n\n```\nfor(j=1; j<=4,j++){\n a[j]=3;\n a[j]=a[j]*2*h;\n b[j]=6;\n b[j]=b[j]+3*k*k;\n }\n```"}, {"role": "assistant", "content": "Aside from using two separate loops, the original code contains lots of redundant statements. One possible improvement would be this:\n\n```\nint tmp = 6 * h;\nfor (j = 1; j <= 4; j++) {\n a[j] = tmp;\n b[j] = 6 + 3 * j * j;\n}\n```\n\nThe main optimizations:\n\nOne loop instead on twoRemoved assignments that get overwritten in the next statementCalculate a value that does not depend on the loop index outside the loop\n\nYou should be aware that most of these optimizations would be done by a compiler anyways."}]} {"messages": [{"role": "user", "content": "Suppose I have\n\n```\nint i=25;\ndouble j=(double)i;\n```\n\nIs there a chance thatjwill have values24.9999999..upto_allowedor25.00000000..._upto_allowed_minus_one_and_then_1. I remember reading such stuff somehere but not able to recall properly.\n\nIn other words:\n\nIs there a case when an integer loses its precision when casted to double?"}, {"role": "assistant", "content": "For small numbers like25, you are good. For very large (absolute) values ofints on architecture whereintis 64 bit (having a value not representable in 53 bits) or more, you will loose the precision.\n\nDouble precision floating point numberhas 53 bits of precision of which Most significant bit is (implicitly) usually1.\n\nOn Platforms where floating point representation is not IEEE-754, answer may be a little different. For more details you can refer chapter5.2.4.2.2of C99/C11 specs"}]} {"messages": [{"role": "user", "content": "Normal pointer usage as I have been reading in a book is the following:\n\n```\nint *pointer;\nint number = 5;\npointer = &number;\n```\n\nThen *pointer has a value of 5.\nBut does this work the other way around? I mean:\n\n```\nint *pointer;\nint number = 5;\n*pointer = &number;\n```\n\nHere does pointer contain the value 5 and *pointer holds the address of number?\n\nThanks."}, {"role": "assistant", "content": "In\n\n```\nint *pointer;\nint number = 5;\n*pointer = &number;\n```\n\nyou never assign a valid address topointer, so dereferencing that pointer (as is done by the expression*pointer) is not valid."}]} {"messages": [{"role": "user", "content": "I'm trying to build a structure that is similar to a device tree. Basically, i want to get a driver that is built to work with a device tree, to work the same way without it. I want to build the wrapper and the structure that contain all the information a device tree has, and pass it onto the driver.\n\nAnyone has any idea how i can do this or a good place to read abut it? i looked for it but couldn't find anything or any example of something similar on how to do this.\n\nBest regards and thank you for your help"}, {"role": "assistant", "content": "It's already been done in the kernel recently and called unified device property API, in particularly it supports same properties come from DeviceTree, ACPI, or built-in in the platform code. More information about API you may find in the sourcesinclude/linux/property.h,drivers/base/property.c. The one of the examples is rfkill_gpio driver, i.e.net/rfkill/rfkill-gpio.c[consumer],arch/arm/mach-tegra/board-paz00.c[provider]."}]} {"messages": [{"role": "user", "content": "When I try tomalloc()astruct bstreenode, my compiler is reporting an error:\n\ninvalid conversion from 'void*' to 'bstree*'\n\nHere is my code:\n\n```\nstruct bstree {\n int key;\n char *value;\n\n struct bstree *left;\n struct bstree *right;\n};\n\nstruct bstree *bstree_create(int key, char *value) {\n struct bstree *node;\n\n node = malloc(sizeof (*node));\n\n if (node != NULL) {\n node->key = key;\n node->value = value;\n node->left = NULL;\n node->right = NULL;\n }\n return node;\n}\n```"}, {"role": "assistant", "content": "In C++ there is no implicit conversion from typevoid *to pointer of other type. You have to specify explicit casting. For example\n\n```\nnode = ( struct bstree * )malloc(sizeof (*node));\n```\n\nor\n\n```\nnode = static_cast( malloc(sizeof (*node)) );\n```\n\nAlso in C++ you should use operatornewinstead of the C functionmalloc."}]} {"messages": [{"role": "user", "content": "If I have the following fucntion\n\n```\nint execute_command(char **args) { \n if (args[0] == NULL) {\n return 1;\n }\n //more code...\n}\n```\n\nHow can I purposely callexecute_command(blank)wherechar **blankwould be (null) initialised in such a way to allow the if statement to be evaluated as true?"}, {"role": "assistant", "content": "A straightforward way of doing this is to create an array of pointers of size one, and set its content toNULL, like this:\n\n```\nchar *args[] = { NULL };\n```\n\nNow you can pass this array toexecute_command:\n\n```\nexecute_command(args);\n```\n\nthe array of pointers would \"decay\" to a pointer-to-pointer on function call, producing the effect that you are looking for."}]} {"messages": [{"role": "user", "content": "I was debugging a Linux C program with CLion's internal debugger (which is gdb on Linux). The program forked a child process that was supposed to get suspended at the break point I set. But the debugger didn't stop there even if I had enteredset follow-fork-mode childinside the gdb panel. So how can I make that happen with CLion?"}, {"role": "assistant", "content": "I followedanswerposted by @MarkusParker, but instead ofset auto-load safe-path /I usedset detach-on-fork offto prevent disconnect from child process. This instruction works for me:\n\nSet a break point at the beginning of your program (ie. the parent program, not the child program).Start the program in the debugger.Go to the debugger console (tab with the label gdb) in clion and enterset follow-fork-mode childandset detach-on-fork off.Continue debugging."}]} {"messages": [{"role": "user", "content": "In C, how can I produce an error if no arguments are given on the command line? I'm not usingint main(int argc , * char[] argv). my main has no input so I'm getting my variable usingscanf(\"%d\", input)"}, {"role": "assistant", "content": "Your question is inconsistent: if you want to get arguments from the command line, you must definemainwithargcandargv.\n\nYour prototype formainis incorrect, it should be:\n\n```\nint main(int argc, char *argv[])\n```\n\nIf the program is run without any command line arguments,arcwill have the value1. You can test it this way:\n\n```\nint main(int argc, char *argv[]) {\n if (argc < 2) {\n printf(\"error: missing command line arguments\\n\");\n return 1;\n }\n ...\n}\n```\n\nIf you definemainwithint main(void)you have no portable access to command line arguments. Reading standard input has nothing to do with command line arguments."}]} {"messages": [{"role": "user", "content": "I created a simple function titled GetInput which prints \"hello\" if the user inputs \"y\" When I compile the program, and then enter \"y\" the program doesn't print \"hello\" unless I type in a couple of random characters then press enter. The image links are below:\n\nhttps://i.stack.imgur.com/dkwsq.png\n\n[1. The compiled code with the expected user input][2. The source code ]"}, {"role": "assistant", "content": "For: scanf(\"%c\\n\", &c);\nRemove the '\\n' and it should work fine.\nChange to: scanf(\"%c\", &c);"}]} {"messages": [{"role": "user", "content": "I am currently reading the manpages abouttime.h. I got this far:\n\n```\ntime_t now = time(0);\nstruct tm * local = localtime(&now);\n```\n\nNow I can work with the time, as far as good, but I do not find the information if its my duty tofree()the variablelocalor not."}, {"role": "assistant", "content": "Quoting theman page\n\nThe four functionsasctime(),ctime(),gmtime()andlocaltime()return a pointer to static dataand hence are not thread-safe. [...]\n\nSo, you need notfree()the returned pointer."}]} {"messages": [{"role": "user", "content": "```\n#include \n\nint main()\n{ \n char a[8]; \n printf(\"%d\\n\",a) ; \n return 0; \n}\n```\n\nFor the above code the output was this :- 2686744\n\nWhat is the reason behind this output?\nI found that the output doesn't depend on the content of the array, but on the size of the array.I just want the explanation."}, {"role": "assistant", "content": "```\nchar a[8]; \nprintf(\"%d\\n\",a);\n```\n\nThis code has undefined behavior.\n\nThe array expressionais implicitly converted to achar*value, equivalent to&a[0]. That value is then passed toprintf-- but since the%dformat requires anintargument, the behavior is undefined.\n\nIfintandchar*happen to have the same size, and if they're passed as function arguments using the same mechanism, then it will likely print a decimal representation of the address of (the initial element of) the array.\n\nBut don't do that. If you want to print the address:\n\n```\nprintf(\"%p\\n\", (void*)a);\n```"}]} {"messages": [{"role": "user", "content": "Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed7 years ago.Improve this question\n\nA feasible way to achieve a suitable time delay is to use busy-waiting, however\nwhat are the advantages and disadvantages of using a busy-waiting or timer interrupts approach programming?"}, {"role": "assistant", "content": "There are probably many, I will try to address what seems most important to me.\n\nAdvantages of busy-waiting:\n\nThe execution flow is usually easier to comprehend and thus less error prone.Timing can be determined more accurately in some cases\n\nDisadvantages:\n\nNo other code (except perhaps other interrupt routines) can be executed.CPU-time is wasted: If no other work must be processed it is still more efficient to set some powersaving-state and let a timer interrupt wake it up in time."}]} {"messages": [{"role": "user", "content": "I want to display \"string pointer affected\" but I get an error. Here is my code:\n\n```\n#include\n\nmain()\n{\n char* *p;\n\n char * s=\"string pointer affected\";\n\n *p=s;\n\n printf(\"%s\",*p);\n}\n```"}, {"role": "assistant", "content": "pdoesn't point to any known location, so writing to*pis a bad idea.\n\nYou mean to say:\n\n```\np = &s;\n```"}]} {"messages": [{"role": "user", "content": "I've been trying to make a program to input two numbers from the user.The XCode application is showing error as\n\nData argument not used by format string\n\nHow am I supposed to get over this? \nplease help \nthanks"}, {"role": "assistant", "content": "just type%dinside the(\"Here is my number %d\",Num)\n\nYou can find more formats here:https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html"}]} {"messages": [{"role": "user", "content": "I have this scanf code line:\n\n```\nscanf(\"%d,%d %d,%d\", &X, &Y, &dirX, &dirY);\n```\n\nHow can I check if the input, which should be for example1,2 3,4(2 commas) is indeed written like this, and only like this?\n\nI don't want to accept1,2,3,4(3 commas) for example."}, {"role": "assistant", "content": "What you can do is check the return value ofscanf()to see whether the user has entered the input is the proper format or not. Like\n\n```\nint main (void)\n{\n int i, j, k, l;\n\n if(scanf(\"%d,%d %d,%d\", &i, &j, &k, &l) != 4)\n printf(\"User entered input in wrong format\\n\");\n printf(\"please enter in the format i,j k,l\");\n //exit here\n else\n printf(\"%d %d %d %d\", i, j, k, l);\n}\n```\n\nThis uses the fact that if user enters input in some other format (other then 1,2 3,4) thenscanf()will not be able to read all the4inputs, and thus will not return4."}]} {"messages": [{"role": "user", "content": "```\n#include \n int main(void)\n {\n int a[]= {15, 14, 34, 46, 69, 86, 10, 0, 4};\n int *p = a; // p point to the first element of array a[0]\n printf(\"%x\\n%x\\n\",&p+1, &a[0]);\n return 0;\n }\n```\n\nthat code will print as example\n\n```\nbff0e554\nbff0e554\n```\n\nso &p+1 return the address of the first element of array.\nAs i understand, &p return the address of that pointer and &p+1 should print the address of pointer + 1 please tell me what i missed !!"}, {"role": "assistant", "content": "&ptakes the address ofp, not the value ofp. That for you&p + 1 == ais pure coincidence and depends on your stack alignment. Your compiler could have sorted the both variables in another order or put a gap in between."}]} {"messages": [{"role": "user", "content": "```\nif (!strcmp(yn, \"y\")) {\n isCooked[x] = 1;\n printf(\"How much %s (in grams) will you cook? \", food[choice - 1]);\n} else {\n isCooked[x] = 0;\n printf(\"How much %s (in grams) will you eat raw? \", food[choice - 1]);\n}\n\nscanf(\"%f\", &grams);\nuserGrams[x] = grams;\n```\n\nWhere should I put my if-else statement if I want to control the user input of grams? I want to put restrictions on my program, like the user should only input minmimum of 20g and the maximum of 200g."}, {"role": "assistant", "content": "You can usewhileloop and anifstatement -\n\n```\nwhile(scanf(\"%f\", &grams)==1){ // loop until scanf returns 1 \n if(grams>=20 && grams<=200){ // validate your input\n userGrams[x] = grams; //assign value\n break; //break out of loop\n } \n else{\n printf(\"Invalid Input !! \");\n }\n}\n```"}]} {"messages": [{"role": "user", "content": "This question already has answers here:What should main() return in C and C++?(19 answers)Closed7 years ago.\n\nI am using Sublime to program in C but when the code is compiled it keeps returning[Finished in 1.1s with exit code 10]. What does that mean? What is going on?\n\n```\n#include \n\nvoid main() \n{\n int x;\n scanf(\"%d\", &x);\n printf(\"%d\", x);\n}\n```"}, {"role": "assistant", "content": "```\n#include \n\nint main() \n{\n int x;\n scanf(\"%d\", &x);\n printf(\"%d\", x);\n return 0;\n}\n```\n\nmain( ) does not take void as a return type.In C programming language we use int as a return type of main .Exit codes are nothing but Windows System Error Codes .I think you are using windows Operating system and for windows Operating system\n\nexit code 10 means :The environment is incorrect.\n\nMay be your installation process was not correct .\nReinstall it and run the program ."}]} {"messages": [{"role": "user", "content": "When accessing a pointer variable of a pointer object, how does the syntax work? Do I need two*?\n\nHere's an example to explain my situation better:\n\n```\nvoid function(ofObject *object) //passing by ref so that I can change it\n{\nint n;\nn=*object.*x; //object is a pointer, but so is the class member x;\n}\n```\n\nIf I just put the*at the beginning, then*object.xwould simply return the address ofobject.x, wouldn't it? Or would it? Am I just overthinking this?"}, {"role": "assistant", "content": "The*operator has lower precedence than the.operator, so*object.xwill be a compiler error since it's the same as*(object.x). This is what the->operator exists for.object->xis the same as(*object).x. IfofObject::xis a pointer, you can then dereference it using the*operator as normal. So putting it all together, to dereference a pointer member through a pointer, you can use*object->x."}]} {"messages": [{"role": "user", "content": "This is my implementation to detect if an unsigned int overflow has occurred when trying to add two numbers.\n\nThe max value of unsigned int (UINT_MAX) on my system is 4294967295.\n\n```\nint check_addition_overflow(unsigned int a, unsigned int b) {\n if (a > 0 && b > (UINT_MAX - a)) {\n printf(\"overflow has occured\\n\");\n }\n return 0;\n}\n```\n\nThis seems to work with the values I've tried.\n\nAny rogue cases? What do you think are the pros and cons?"}, {"role": "assistant", "content": "You could use\n\n```\nif((a + b) < a)\n```\n\nThe point is that ifa + bis overflowing, the result will be trimmed and must be lower thena.\n\nConsider the case with hypothetical bound range of 0 -> 9 (overflows at 10):\n\nbcan be 9 at the most. For any valueasuch thata + b >= 10,(a + 9) % 10 < a.For any valuesa,bsuch thata + b < 10, sincebis not negative,a + b >= a."}]} {"messages": [{"role": "user", "content": "I have the following code, where we try to left shift certain bits of a value:\n\n```\nint main()\n{\n unsigned long mvb = 1;\n\n mvb << 8;\n printf(\"The shift value is %u\\n\", mvb);\n\n mvb << 56;\n printf(\"The shift value is %u\\n\", mvb);\n}\n```\n\nbut the result for all those two operation are both1, what is the reason, and how use it correctly?"}, {"role": "assistant", "content": "You need to assign it back to mvb after shifting like:\n\n```\nmvb = mvb << 8;\n```"}]} {"messages": [{"role": "user", "content": "Starting from\n\n```\nchar tval[20] = \"temp:26.62\";\n```\n\nhow can I add a space character untiltvalis filled? I need that in the end to obtain this:\n\n```\nchar tval[20] = \"temp:26.62 \";\n```"}, {"role": "assistant", "content": "Like this, probably\n\n```\nsize_t prevlen = strlen(tval);\nmemset(tval + prevlen, ' ', 19 - prevlen);\n*(tval + 19) = '\\0';\n```"}]} {"messages": [{"role": "user", "content": "I've got the following Makefile which compiles, creates an executable and then executes it.\n\n```\nCC=gcc\nCFLAGS=-I.\nDEPS = hellomake.h\nOBJ = hellomake.o hellofunc.o\n\n%.o: %.c $(DEPS)\n $(CC) -c -o $@ $< $(CFLAGS)\n\nhellomake: $(OBJ)\n $(CC) -o $@ $^ $(CFLAGS)\n ./hellomake\n```\n\nIt works perfectly on my local machine and when it builds in Travis the following error comes up.\n\ngcc -o hellomake hellomake.o hellofunc.o -I.\nhellomake.o: file not recognized: File format not recognized\ncollect2: ld returned 1 exit status\nmake: *** [hellomake] Error 1"}, {"role": "assistant", "content": "Yourhellofunc.ois from a different system (tryfile hellofunc.o). Remove it and then recompile it.\n\nWere you cross-compiling? Do you have a home directory mounted on different machines? Perhaps unpacking an archive made by someone else on a different architecture?"}]} {"messages": [{"role": "user", "content": "Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed7 years ago.Improve this question\n\nI type this code on Ubuntu 14.04\n\n```\n#include\nint main() {\n\n int i, j, n;\n scanf(\"%\",&n);\n for (i=0;i<=n;i++){\n for (j=0;j<=i;j++){\n printf(\"*\");\n }\n printf(\"\\n\");\n }\n return 0;\n}\n```\n\nbut it print too much stars and it Continue until I close it."}, {"role": "assistant", "content": "Should be:\n\n```\n#include\nint main() {\n\nint i, j, n;\nscanf(\"%d\",&n);\nfor (i=0;i<=n;i++){\n for (j=0;j<=i;j++){\n printf(\"*\");\n }\n printf(\"\\n\");\n}\nreturn 0;\n}\n```\n\nYou forgot to tell scanf you were reading in an integer by using the %d argument"}]} {"messages": [{"role": "user", "content": "whats wrong with my code? im trying to return a value from function ignition_status, its not returning. I cant see any problem in my code.\n\n```\n#include\n#include\nconst char * ignition_status();\nconst char *ign_st;\nint main()\n{\nprintf(\"%s\", ignition_status(1));\nreturn 0;\n}\nconst char * ignition_status(int st)\n{\n if(st==1)\n {\n const char *ign_st=\"ON\";\n }\n else\n {\n const char *ign_st=\"OFF\";\n }\n return ign_st;\n}\n```\n\nThanks..."}, {"role": "assistant", "content": "The comments are pointing you to the right direction, here is a working sample:\n\n```\n#include \n\nconst char * ignition_status(int st)\n{\n const char *ign_st;\n\n if(st==1) {\n ign_st=\"ON\";\n } else {\n ign_st=\"OFF\";\n }\n\n return ign_st;\n}\n\nint main()\n{\n printf(\"%s\", ignition_status(1));\n\n return 0;\n}\n```"}]} {"messages": [{"role": "user", "content": "The following code fails becauseatoi()requires achar *and I'm only passing achar. I want to store the value of only the first digit. Any idea how I can do this?\n\n```\nint main () {\n char a[]= \"123\";\n int b = atoi(a[0]);\n printf(\"%d\",b);\n}\n```\n\nHere's the exact error message:\n\n```\ndivision.c:9:16: warning: incompatible integer to pointer conversion passing\n 'char' to parameter of type 'const char *'; take the address with &\n [-Wint-conversion]\n int b = atoi(a[0]);\n ^~~~\n &\n```"}, {"role": "assistant", "content": "Yeah, a single character is not a string asatoi()requires.\n\nIf you just want the value of the single digit, you can do it like this:\n\n```\nint b = (a[0] - '0');\n```"}]} {"messages": [{"role": "user", "content": "I am new to programming. I was finding a square root of a number usingsqrt()function in c. `\n\n```\nscanf(\"%d\", &n);\n\n printf(\"%d\\n\", sqrt(n));\n }\n\n return 0;\n}\n```\n\nWhen I enter a value ofn = 5, I got some negative large number. Can anyone explain, please?"}, {"role": "assistant", "content": "You've produced undefined behavior by passing the wrong type toprintf: the%dformat required a matching argument of typeintbut your argument has typedouble. You need%f(or%eor%gor%a) to print it. Also, there may be other problems, e.g. if you omitted#include ."}]} {"messages": [{"role": "user", "content": "I'm a novice on programming and there are one unimportant but confusing problem that bothers me.\n\nLet me post my code first:\n\n```\nFILE *fp;\nint i;\n\nfp=fopen(\"test_data.txt\", \"r\");\nprintf(\"i's address=%p\\n\", &i);\nprintf(\"fp's address =%p\\n\", fp);\nprintf(\"stdout's address=%p\\n\", stdout);\nclose(fp);\n```\n\nThe output is:\n\n```\ni's address=0x7ffd038ab8cc\nfp's address=0x231c010\nstdout's address=0x7fbb2e4f7980\n```\n\nMy problem is that why is the fp's address 28-bit? Shouldn't it be the same as normal variables and standard output (48-bit)?\n\nI use GCC on 64-bit Ubuntu Linux.\n\nThanks for your answers!"}, {"role": "assistant", "content": "The most likely case here is that your file adress simply starts with zeros, which are omitted by default.\n\nEdit:Hereis a question that points to a similar kind of problem."}]} {"messages": [{"role": "user", "content": "I need to find the length of an array, how would I do this without using thesizeoffunction.\n\neg if\n\n```\nArray 1 = [0 1 2 3 4 5 6]\n```\n\nthe size of this array would be7."}, {"role": "assistant", "content": "If you can't usesizeof(tell us why, please), you can use a loop and a sentinel (-1 or some number that can not be used in the array):\n\n```\nint arr[] = {0, 1, 2, 3, 4, 5, 6, -1};\nint count = 0;\n\nwhile (arr[count] != -1) count++;\n```"}]} {"messages": [{"role": "user", "content": "I have installed codeblocks in windows 7 first time and try to run a simple C program but I get this error?\n\ncan't find compiler executable in your search path (GNU GCC compiler)\n\nI tried many things to solve it but unable to compile."}, {"role": "assistant", "content": "Have you installed the Mingw compiler or any other simiar compiler? If not install that first. After you have done so, you need to set codeblocks to use that compiler. You can do that by going to thesettings>compiler settingsand set the necessary options there. You may need to refer the place where you have installed Mingw or other compiler. Note the compiler executable isgccfor C andg++for C++ and the linker isldi guess. Debugger isgdb. You need to tell codeblocks where are these located."}]} {"messages": [{"role": "user", "content": "main.c\n\n```\nList L;\nInitialize(&L);\nprintf(\"%d\\n\", Size(&L));\n```\n\nlist.c\n\n```\nvoid Initialize (List *L) {\n L = malloc(sizeof(List));\n if (L == NULL) {\n perror(\"Unable to create memory for list. Exiting.\");\n exit(1);\n }\n L->size = 0;\n}\n\nint Size (List *L) {\n return L->size;\n}\n```\n\nWhat I want outputted would be a size of '0', however what I am getting is the max int sizeof '2673724'. I am kind of confused at this point what is wrong with my code. Looking with gdb it looks like the Initialize() function is not actually modifying the List's size as it remains the same before and after entering the function.\n\nDid I do something wrong?"}, {"role": "assistant", "content": "ThisInitializefunction ignore the argument, allocate a buffer, write something to it, throw it away and cause memory leak.\n\nTry this simple function using the same way asSize:\n\n```\nvoid Initialize (List *L) {\n L->size = 0;\n}\n```"}]} {"messages": [{"role": "user", "content": "What's wrong with this program. It compiles but is not giving correct output.\n\n```\n/* Program for Armstrong Number*/\n\n#include\n#include\n\nvoid main()\n{\n int num,sum=0,temp,d;\n printf(\"\\n========Program for Armstrong Number=========\\n\");\n printf(\"Enter the number : \");\n scanf(\"%d\",&num);\n temp=num;\n while(temp>10){\n d=temp%10;\n sum+=pow(d,3);\n d/=10;\n }\n sum+=pow(temp,3);\n\n if(sum==num)\n printf(\"\\nThe number %d is an Armstrong Number\\n\",num);\n else\n printf(\"\\nThe number %d is not an armstrong number\\n\",num);\n}\n```"}, {"role": "assistant", "content": "```\nwhile(temp>10){\n d=temp%10;\n sum+=pow(d,3);\n d/=10; // this should be temp/=10;\n }\n```\n\nThis loop is infinite as you don't modifytemp."}]} {"messages": [{"role": "user", "content": "In a (C++) class I took recently the teacher mentioned that using the->operator was a tiny bit slower than using dot notation and dereferencing your pointer manually (e.g.(*ptr)).\n\nIs this true, and, if so, why?Does this apply to C as well?"}, {"role": "assistant", "content": "The->operator is neither slower or faster than.operator. The fact is thatdereferencingsomething is slower than just access to a memory location, because there is one more indirection. And this is a fact of life, either in C and C++ and any other language.\n\nIn C++, you have alsoreferences, so you can dereference something using the.too! So the problem here is notarrow-vs-dot, the problem is if the compiler can go straight to a value or if it must search for its address before."}]} {"messages": [{"role": "user", "content": "I am trying to convert thestart_timeof the linux kerneltask_structinto nanoseconds. I need to give it the argument ofconst struct timespec *butstart_timeis of typestruct timespec.\n\nHow would I make it a constant and a pointer to thetimespecstruct? Example code:\n\n```\n(*kinfo).start_time = timespec_to_ns((*current).start_time);\n```"}, {"role": "assistant", "content": "I would recommend picking up a primer on C, since you'll need to be very familiar with C programming (especially since the Linux kernel uses all the C trickery in the book) in order to write kernel code (or modify existing kernel code). However, to answer your question, you'll want to pass a pointer to the value (which is done using the&operator in C). Also, please use the correct dereferencing syntax for pointers to structures (p->attr).\n\n```\nkinfo->start_time = timespec_to_ns(¤t->start_time);\n```"}]} {"messages": [{"role": "user", "content": "I have come across following definition in an embedded C source file:\n\n```\nconst preamble_t OAD_Preamble @ \".preamble\" =\n{\n HAL_OAD_RC_MAX, // Default program length of max if not using post-processing tool.\n OAD_MANUFACTURER_ID, // Manufacturer ID\n OAD_TYPE_ID, // Image Type\n 0x00000001 // Image Version\n};\n```\n\nI have no idea about the @ part, can you please help me with this?\n\nEdit:\nThis is in IAR compiler, used with TI SoCs."}, {"role": "assistant", "content": "This is the way you can specify a memory address or a section in which you would like to place your variable.\n\n\".preamble\"is the name of a section,OAD_Preambleis the variable to be placed there.\n\nYou can also specify physical address after the at@sign:\n\n```\nconst unsigned char port_bit @ 0x1800 = BIT0;\n```\n\nMore information is inthis document.\n\nNote:this is a non-portable compiler extension, not a part of the standard C syntax."}]} {"messages": [{"role": "user", "content": "I have input time in seconds epoch format. \nI need to have struct tm out of this epoch time in seconds.\n\n```\nstruct tm epoch_time;\n int seconds = 1441852;\n epoch_time.tm_sec = seconds;\n```\n\nMy purpose is to have tm structure filled with proper values for years, months, days, hours, minutes, and seconds for the given epoch time in seconds. Any hint in this regard will be helpful. Thanks."}, {"role": "assistant", "content": "```\nstruct tm epoch_time;\ntime_t seconds = 1441852;\nmemcpy(&epoch_time, localtime(&seconds), sizeof (struct tm));\n```\n\nThis assumes you want local time. If you want GMT, usegmtimeinstead oflocaltime. Note that this will crash on error."}]} {"messages": [{"role": "user", "content": "I am trying to produce an output as double quoted input . For e.g if the argument that is passed in str() is somenamethen the output should be\"name\"which is not happening in below code.\n\n```\n#include\n#include\n#define str(s) #s\n#define newline printf(\"\\n\")\n\nint main()\n\n{\n\n printf(\"Your double quoted code is : %s \",str(GHOST));\n newline;\n}\n```\n\nOutput : GHOST"}, {"role": "assistant", "content": "What is happening is that the quotesarebeing added, but they are consumed as part of the syntax of the language. Because, you need to pass astringlike\"GHOST\"toprintf, not just an identifier.\n\nIf you want quotes to appear when you run the program, I would make it\n\n```\nprintf(\"Your double quoted code is : \\\"%s\\\" \",str(GHOST));\n```\n\ninstead. The escaped quotes in the format string will appear in the output."}]} {"messages": [{"role": "user", "content": "In python, I'm able to build a string using this method:\n\n```\n>>> s = \"%s is my name\" %(\"Joe\")\n>>> s\n'Joe is my name'\n```\n\nIs there a similar way to do this in C++? I know C has\n\n```\nprintf(\"%s is my name\", \"Joe\")\n```\n\nBut that's for printing to standard out. Ideally I'd like something like the Python example. Thanks!\n\nEDIT: Is there a name for this kind of thing? I couldn't think of what to google!"}, {"role": "assistant", "content": "The sprintf command works like printf, but has an extra parameter at the front. The first parameter is an array of characters of where to store the string instead of printing it.\n\n```\nchar chararray[1000];\nsprintf(chararray,\"%s is my name\",\"Joe\");\n```\n\nhttp://www.cplusplus.com/reference/cstdio/sprintf/"}]} {"messages": [{"role": "user", "content": "I want to get achararray values usingscanf. I used this code:\n\n```\n// get first array\n printf(\"first length:\\n\");\n scanf(\"%d\", &f_l);\n printf(\"first number:\\n\");\n for(i=0 ; i<=f_l ; i++) {\n scanf(\"%c\", &first[i]);\n }\n //start test\n printf(\"first number is:\\n\");\n for(i=0 ; i<=LEN ; i++) {\n printf(\"(%c | %d)\", first[i],i);\n }\n```\n\nbut when I print the array, I found a\\nin the first place (first[0]), and the other chars starts fromplace[1]instead! why is that, and how to fix it?"}, {"role": "assistant", "content": "This is because a'\\n'is left in the buffer when you doscanf()forf_l.\n\nUse a trailing space, it should work\n\n```\nfor(i=0 ; i<=f_l ; i++) {\n scanf(\" %c\", &first[i]);\n}\n```"}]} {"messages": [{"role": "user", "content": "I am using Code Composer Studio (CCS) for developing an embedded application. It is very helpful if I can use printf to print something on console of CCS. But it is not working. I includedstdio.h. The Code compiles. When I run, I see data in putty, but I see nothing in CCS. Is is possible to see something in console like in eclipse?"}, {"role": "assistant", "content": "this link:http://processors.wiki.ti.com/index.php/Printf_support_for_MSP430_CCSTUDIO_compiler\n\ncontains the details on how to use printf() (per some compiler settings in the CCS) to display the results of printf() statements on the CCS console\n\nin the 'properties' window, in the 'Library Function Assumptions' sub page, in the 'Level of printf() support required' select 'full'"}]} {"messages": [{"role": "user", "content": "I have this simple code, and can't figure out how to allocate memory for scanf\n\n```\nchar* string= (char*) malloc (sizeof(char));\nprintf(\"insert string: \\n\");\nscanf(\"%s\", string);\nfree(string);\n```\n\ndoesn't matter how many chars my string is, it's an error. I want to use malloc for the char*, any way to set memory for scanf."}, {"role": "assistant", "content": "You are just request 1 byte. You need to allocate more than that if you want store more than just the0terminator in the string:\n\n```\nchar* string= malloc (256); //256 bytes, arbitrary value...\n```\n\nI removed:\n\nsizeof(char)because it's always guaranteed to be1.(char*)because casting the return value ofmalloc()is needless.\n\nI would also recommend usingfgets()instead ofscanf()to prevent overflowing the buffer. The same could be done withscanf()by specifying the length in the format string. But I personally prefer usingfgets()and parsing usingsscanf()if necessary."}]} {"messages": [{"role": "user", "content": "My computer made a beep sound even though I did not add\\ato my code. Why?\n\nProgram:\n\n```\n#include \n#include \n#include \n#include \n\n#define START_CHAR ' '\n#define END_CHAR 'DEL'\n\nint main(void)\n{ /* This code prints characters on keyboard.*/\n\n /* declaration */\n\n int char_code;\n\n for (char_code=(int)START_CHAR; char_code<=(int)END_CHAR; char_code=char_code+1)\n printf(\"%c\", (char)char_code);\n\n printf(\"\\n\");\n\n return(0); \n}\n```"}, {"role": "assistant", "content": "'DEL'is not a valid character constant. It ends up being equal to 4474188. And since you havechar_codedefined as anint, the loop goes from 32 (the ASCII code for a space) to 4474188. So it loops through the full character set multiple times.\n\nYou should be using0x7Finstead."}]} {"messages": [{"role": "user", "content": "This question already has answers here:Why is unsigned integer overflow defined behavior but signed integer overflow isn't?(7 answers)Closed8 years ago.\n\nWhen I assignivalue greater thanINT_MAXin this code -\n\n```\n#include \n#include \n\nint main()\n{\n\n int i;\n i=INT_MAX+3;\n\n printf(\"%d \\n\",INT_MAX); //INT_MAX = 2147483647\n\n if(i>INT_MAX) \n { \n printf(\"OVERFLOW\");\n }\n else \n {\n printf(\"%d\",i); \n } \n return 0;\n}\n```\n\nSo in this asi=INT_MAX+3;then condition is true andoverflowshould be printed but it prints somenegative value. Is it undefined behaviour ?"}, {"role": "assistant", "content": "Yes, signed integer overflow has undefined behavior in C.i > INT_MAXis never true for anyint i. How can you have anintgreater than the maximum possibleint?"}]} {"messages": [{"role": "user", "content": "I was trying to implement the following code.\n\n```\n#include \n#include \nvoid abc(char *, char *);\nint main(int argc, char *argv[])\n{\n char *p=\"Hello XYZ\";\n char *q=\"ABC\";\n abc(p,q);\n printf(\"%s\", p);\n}\nvoid abc(char *p, char *q)\n{\n p+=6;\n p=q;\n}\n```\n\nI believe I am modifying the references and I was expecting the output\n\n\"Hello ABC\"\n\nbut the output is\n\n\"Hello XYZ\".\n\nCan any one explain the error?"}, {"role": "assistant", "content": "C uses pass-by-value for function argument passing. So, you cannot actually changeporqfromabc(). To actually changepandqthemselves, you'll be requiring to pass a pointer to each of them.p=q;is not the way to copy a string, anyway. You need to make use ofstrcpy()to copy a string.You're making the call toabc()with arguments which are the pointers to string literals. If you try to modify thevaluespointed to by those input arguments, you'll faceundefined behaviour."}]} {"messages": [{"role": "user", "content": "This question already has answers here:setvbuf not able to make stdin unbuffered(2 answers)Closed8 years ago.\n\nI've written a simple C program that is meant to pipestdintostdoutwithout buffering characters:\n\n```\n#include \n\nint main (int argc, char *argv[])\n{\n int c;\n\n while ((c = getchar()) != -1) {\n putchar(c);\n fflush(stdout);\n }\n\n return 0;\n}\n```\n\nHowever, this program still seems to be buffering characters until newlines, despite the call tofflush. Why is this happening and how can I fix it (if possible)?"}, {"role": "assistant", "content": "In this case, the buffering is done by the terminal driver which doesn't send the input to your program until you pressENTER. So your program doesn't even get any characters andfflush()isn't even called. It's just waiting for input at thegetchar()call."}]} {"messages": [{"role": "user", "content": "```\ngetint (int *);\n```\n\nI am not really sure what doesgetint (int *)mean? Can someone explain this?"}, {"role": "assistant", "content": "This is a function prototype declaring the functiongetint(). The function takes as pointer to anintas a parameter.\n\nWhen prototyping a function it is not necessary to specify the parameters' names.\n\nThe prototype is missing a return type, which for C then defaults toint. Omiting a return type however is violating the recent C standard, so code doing so could be considered invalid.\n\nAn equivalent to\n\n```\ngetint(int *);\n```\n\nthough would be\n\n```\nint getint(int * pi);\n```"}]} {"messages": [{"role": "user", "content": "I want to run a program, and allow user input on the same line. I check if the file exists, and if not, print\n\nFILE : No such file or directory\n\n```\nFILE* filename;\n filename = fopen(argv[2], \"wb\");\n //validate file name\n if(!filename) {\n perror(filename);\n return EXIT_FAILURE;\n }\n```\n\nWhen I compile, I get the following warning:\n\nexpected âconst char *â but argument is of type âstruct FILE *â"}, {"role": "assistant", "content": "In your code above,filenameis aFILE *, not a string with the name of the file. Sinceargv[2]appears to be the filename, you could try:\n\n```\nif(!filename) {\n perror(argv[2]);\n return EXIT_FAILURE;\n }\n```\n\n...but you should first check thatargv[2]is set (thatargc > 2)."}]} {"messages": [{"role": "user", "content": "```\n#include \n\n#define rows 500 //can define rows as any number\n\nint main()\n{\n int i,j;\n\n for(i=0;i<=rows;++i)\n {\n for(j=0;j<(2*i+1);++j)\n {\n printf(\"* \");\n }\n printf(\"\\n\");\n }\n return 0;\n}\n```\n\nSo here is my code, what it does is it prints the number of rows set by #define and creates a right angle triangle. But whatever I set that number to it always prints out 1 extra row of stars, and I can't figure out why.\n\nI know I can set it asi=0;i<500;i++and just forget about the#definestatement but I'm trying to make it work with it."}, {"role": "assistant", "content": "You have made the condition as\n\n```\ni=0;i<=rows;++i\n```\n\nProbably a typo.It should be\n\n```\ni=0;i = myClass //<- failed\n\n//c function \nvoid someSwiftClass(void *context);\n```\n\nThanks"}, {"role": "assistant", "content": "I had similar problem, you can convert this as below.\n\n```\nvar myClass = MyClass()\n\nvar classPtr = unsafeBitCast(myClass, UnsafePointer.self)\n```\n\nand your function,\n\n```\nfunc someSwiftClass(voidPointer: UnsafeMutablePointer) {\n\n}\n```\n\nIf you want to declare constant pointer useUnsafePointerand when your pointer is not constant useUnsafeMutablePointer\n\nIn C constant pointer -const int *myCpointer\n\nCorresponding swift pointer -let mySwiftPointer: UnsafePointer"}]} {"messages": [{"role": "user", "content": "Hello I have a little problem in my program\n\n```\nFILE* f;\nchar * psz = new char[wcslen(file) + 1];\nwsprintfA(psz, \"%S\", file);\nfopen_s(&f,psz, \"w+b\");\nchar * buffer = \"data\\heightmap.bmp\";\n fwrite(buffer,256, 1, f);\nfclose(f); \n\n//later in another class:\nFILE* f;\nchar * bufer;\nfopen_s(&f,\"data\\test.dat\", \"rb\");\nfread(buffer,256, 1, f);\nfclose(f);\n///buffer is \"dataheightmap.bmp\" not \"data\\heightmap.bmp\" as it should be to open the file later.\n\nFILE* f;\nfopen_s(&f,buffer, \"rb\");\ncount = fread(&bitmapFileHeader, sizeof(BITMAPFILEHEADER), 1, f);\nfclose(f);\n```\n\nsomeone can help me please.\nThanks\nWindow7,visual studio 2013."}, {"role": "assistant", "content": "Remember that you need to escape your slashes:\n\n```\n\"data\\heightmap.bmp\"\n\"data\\test.dat\"\n```\n\nShould be:\n\n```\n\"data\\\\heightmap.bmp\"\n\"data\\\\test.dat\"\n```"}]} {"messages": [{"role": "user", "content": "I'm currently learning how to code C and stumbled upon an interesting line,\n\nApparently,\n\n```\nstruct node{\n node *next;\n};\n\nnode *head = (node *)calloc(1, sizeOf(node));\nhead->next = NULL;\n\nnode *currentNode = head;\nwhile (!currentNode)\n```\n\nIn this context, is\n\n```\nwhile(!currentNode)\n```\n\ndifferent to\n\n```\nwhile(currentNode != NULL)\n```\n\n? I thought they meant to check for the same stuff, when current Node is not NULL but they are returning different results and I dont' understand..."}, {"role": "assistant", "content": "```\nwhile(currentNode)\n```\n\nand\n\n```\nwhile(currentNode != NULL)\n```\n\nare equivalent.\n\nThe first says that whilecurrentNodehas some value (could be anything, even garbage), the second one says that whilecurrentNodeis notNULL, i.e., has some value.\n\nOn the other hand,\n\n```\nwhile(!currentNode)\n```\n\nmeans that whilecurrentNodedoes not hold any value, i.e, isNULL."}]} {"messages": [{"role": "user", "content": "If I want to allocate memory in function:\n\n```\nchar* allocate() {\n char *cp = (char*)malloc(10);\n ...\n return cp;\n}\n```\n\ncan I use the returned content incpfrommain()? and how to freecp?"}, {"role": "assistant", "content": "can I use the returned content in cp in main()?\n\nYes, you can.\n\nand how to free cp?\n\nUsing\n\n```\nfree(cp); // Replace cp with the name of the pointer if you are using it in another function\n```\n\nAlso, you\nshould not cast the result ofmalloc(and family) in C"}]} {"messages": [{"role": "user", "content": "I have twochar's ,s1ands2and have a statement\n\n```\nif ((s1 && !s2) || (!s1 && s2))\n```\n\nbut I feel like that is redundant since the calculation involves looking at boths1and!s1separately, and the same fors2and!s2. For, by looking ats1ands2, you already have the information that underlies!s1and!s2. Is there a way to compress this statement?"}, {"role": "assistant", "content": "That statement is a logical-exclusive-or for which there is no built-in operator. Under certain restrictions, you can convert it to a bitwise-exclusive-or^, but more generally it can be written as\n\n```\nif ( !s1 != !s2 )\n```\n\nThe logicalnotoperator!will convert a 0 to the logicaltruevalue, and will convert any other value to the logicalfalsevalue. The results can then be tested with!=."}]} {"messages": [{"role": "user", "content": "I'm new to c programming. I'm trying to print numbers 1 to 10.\n\n```\n#include \n\nint main(){\n int i;\n for(i=1; i<11; i++){\n printf(\"%s\\n\", i);\n }\n getchar();\n}\n```\n\nIt compiles in powershell when I type:gcc .\\forloop.cbut when I try to run the program with./aI get this error message:\n\nAny help would be appreciated."}, {"role": "assistant", "content": "```\nprintf(\"%s\\n\", i);\n```\n\nThat tries to print a string.iis an integer. So it will crash when it dereferencesias a string.\n\nTry\n\n```\nprintf(\"%d\\n\", i);\n```"}]} {"messages": [{"role": "user", "content": "Consider the following code sample:\n\n```\n#define STRING_LITERAL \"%u, %u\"\nconst char string_const[ ] = \"%u, %u\";\n\nsnprintf(dest_buff, sizeof(dest_buff), STRING_LITERAL, arg1, arg2, arg3);\n```\n\nMy compiler then issues a Warning: the format string ends before this argument\n\nNow if I change the instruction to:\n\n```\nsnprintf(dest_buff, sizeof(dest_buff), string_const, arg1, arg2, arg3);\n```\n\nThen no warning is issued by the compiler.\n\nMy question is: does such a behavior comply with the C99 standard?"}, {"role": "assistant", "content": "The warning is generated by the compiler which was able to determine that you passed incorrect arguments to the call, and didn't in the second.\n\nThe standard defines that passing incorrect arguments and/or using incorrect flags results in undefined behavior.\n\nThe warning is not required by the Standard, and it is merely additional help to the programmer."}]} {"messages": [{"role": "user", "content": "Can anyone tell where the problem is?\n\n```\nsomeone@someone:~/Desktop$ cat morning.c\n```\n\n```\n#include \nint main (int argc, char** argv)\n{ \n printf (\"Good Morning\") ; \n return 0;\n}\n```\n\n```\nsomeone@someone:~/Desktop/9raya$ ./morning.c\n./morning.c: line 2: syntax error near unexpected token `('\n./morning.c: line 2: `int main (int argc, char** argv)'\n```\n\nI really don't see where the problem is."}, {"role": "assistant", "content": "The problem is that you're trying to execute C source code and your shell doesn't understand that. You need to compile the source code into an executable, then execute it. For example,\n\nCompilemorning.cto produce an executable namedmorning:\n\ngcc -Wall -Wextra morning.c -o morning\n\nExecutemorning:\n\n./morning\n\nwhere I added the-Walland-Wextraflags to provide a more useful set of compiler warnings on top of gcc's quite minimal default."}]} {"messages": [{"role": "user", "content": "I have the following code:\n\n```\nstruct stest\n{\n int x;\n unsigned char data[];\n} x = \n{\n 1, {\"\\x10\\x20\\x30\\x00\\x10\"} \n};\n\nint main()\n{\n printf( \"x.data: %d\\n\", (int)x.data[0] );\n return 0;\n}\n```\n\nWhich works fine. However, I need to use the size of the \"data\".\n\nIf I do:\n\n```\nprintf( \"sizeof x.data: %d\\n\", (int)sizeof(x.data) );\n```\n\nI get the error:\n\ninvalid application of ‘sizeof’ to incomplete type ‘char[]’\n\nIs there a way to get the size of \"data\" in this situation, or maybe a suggestion of an alternative method I could use?\n\nThe compiler I am using is gcc 4.6.3."}, {"role": "assistant", "content": "Since x.data is a null terminated char array you could just use strlen function.\n\n```\nprintf( \"sizeof x.data: %u\\n\", strlen(x.data)+1 );\n```\n\nThis code will not work correctly if the array contains null. In this case you need to store length of the array in separate member of struct."}]} {"messages": [{"role": "user", "content": "If I had a method\n\n```\nint main(int argc, char* argv[]) {\n```\n\nI am under the impression that calling arguments and receiving data through standard input are somewhat the same things. What is the difference between adding the arguments \"1 2 3 4\" and receiving standard input \"5 6 7 8\"? and when would you pick one method over the other?"}, {"role": "assistant", "content": "The difference is in how you access them.\n\nArguments are accessible throughargv. Standard input is accessible through thestdinfile descriptor.\n\ncase 1 - command line arguments:\n\n```\nint i;\nfor (i=1; i < argc; i++) {\n printf(\"%s\", argv[i]); // Prints \"1 2 3 4\"\n}\n```\n\ncase 2 - standard input:\n\n```\nchar buffer[121];\nwhile (scanf(\"%120s\", buffer) == 1) {\n printf(\"%s\", buffer); // Prints \"5 6 7 8\"\n}\n```"}]} {"messages": [{"role": "user", "content": "In this problem I basically store the inverse of given linked list into another linked list.\nHere is the function\n\n```\nvoid copy(struct node** aref,struct node** bref) {\n struct node* first = *aref;\n struct node* second = *bref;\n\n while(first!=NULL) {\n struct node* tmp = (struct node*)malloc(sizeof(struct node));\n\n tmp->data = first->data;\n tmp->next = second;\n second = tmp;\n\n first = first->next;\n }\n}\n```\n\nThis doesn't work. However, if I replace second by *bref it works.\nWhy is it so?"}, {"role": "assistant", "content": "After the while loop add the below code\n\n```\nwhile(first!=NULL)\n{\n struct node* tmp=(struct node*)malloc(sizeof(struct node));\n tmp->data=first->data;\n tmp->next=second;\n second=tmp;\n\n first=first->next;\n}\n/* CHANGE HERE */\n*bref = second;\n```\n\nThe reason is that you will have to point \"*bref\" to the head of the inversed linked list."}]} {"messages": [{"role": "user", "content": "Anyone else encountered a problem like this?\n\n```\nswprintf_s(v, len, L\"%ws\", var);\nMessageBox(NULL, v, NULL' NULL);\n```\n\nMessage box prints out \"%ws\" not the contents of var.\n\nThanks."}, {"role": "assistant", "content": "C++Builder does not support all of the size prefixes that Visual Studio supports (and vice versa). In this case, C++Builder does not support thewprefix for%s, but Visual Studio does.\n\nVisual Studio:\n\nFormat Specification Syntax: printf and wprintf Functions\n\nA format specification, which consists of optional and required fields, has the following form:%[flags] [width] [.precision] [{h | l | ll | w | I | I32 | I64}] type\n\nC++Builder:\n\nprintf Format Specifiers\n\nPrint format specifiers have the following form:% [flags] [width] [.prec] [F|N|h|l|L] type_char\n\nIfvaris a wide string, you can use%sor%lsin both compilers."}]} {"messages": [{"role": "user", "content": "I am studying pointers for c and this placement of*really really confuses me.\n\nI understand whatint *ais..\n\nBut what is\n\n```\na = malloc(n * sizeof(int) )\n```\n\nI understand what above is doing but why is*in the middle of by itself?? This part really confuse me so please someone can explain to me?"}, {"role": "assistant", "content": "unary*means dereferencing and binary*means multiplication."}]} {"messages": [{"role": "user", "content": "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.Closed8 years ago.Improve this question\n\nb = 25 | a; \nAssume that a corresponds to register $t0 and b corresponds to register $t1.?\nCan anyone explain how to approach this and can give me the final answer so I can compare with mine after I do it?"}, {"role": "assistant", "content": "I suppose you meanori $t1, $t0, 25? That would be the equivalent.\n\nYou can find tons of references about MIPS with a Google search. A good example would be thisMIPS instruction reference."}]} {"messages": [{"role": "user", "content": "I have an application which gets 10 different numbers (which are less than 100) as input. If any thing other than number is entered, it should display \"Invalid input\"\n\nex: If I enter 'C' which is not a number between 1 to 100, Program should display \"Invalid input\"\n\nI don't want to compare the input with all the characters and special symbols\n\nIf the number is a single digit number, isdigit() or isalpha() does the job.\n\nHow can I solve this?"}, {"role": "assistant", "content": "I would just use something like this:scanf(\"%d\", &variable)and checkreturn valueof this function. It will work unless you have something other than digit on stdin. You can put this in the loop and catch this error using return value ofscanf()function."}]} {"messages": [{"role": "user", "content": "We develop code for embedded PowerPC architectures.\n\nOur compiler supports something called asm Macros.\n\nHere an excerpt from the handbook:\n\nasm Macro SyntaxAn asm macro definition looks much like a function definition, including a return type and parameter list, and function body.The syntax is:asm [volatile] [return-type] macro-name ( [ parameter-list ] )\n {\n % storage-mode-list (must start in column 1)\n ! register-list (“!” must be first non-whitespace)\n asm-code \n } (must start in column 1\n\nIs this standard C? My compiler does not list this as an extension in his handbook.\n\nClarification after first answer:\n\nI'm aware the part withen{ }is not defined by standard C. I meant the function like construct afterasmand before the closing)."}, {"role": "assistant", "content": "No, it is not standard C. Anything architecture-specific, like assembly code, is going to be an implementation-specific extension just about by definition."}]} {"messages": [{"role": "user", "content": "What is the recommended way to make an (Open)MotifXmFileSelectionBoxshow just relative paths inside the \"Directories\" pane? I mean, something like this\n\ninstead of\n\nI've triedlooking for somethingtweakable via.Xresourcesbut couldn't find anything... Should I write my owndirSearchProc?"}, {"role": "assistant", "content": "Well there isa resourceafter all:\n\n```\n*pathMode: path_mode_relative\n```\n\n(This splits the \"Filter\" textfield into two \"Directory\" and \"Filter\" fields though)"}]} {"messages": [{"role": "user", "content": "I'm usingfgets()with a buffer for a character array as I'm processing a file line by line. Will the buffer array contain the character,'\\n'in its last position if it encounters a new line?\n\nDoesfgets()store'\\n'in the buffer when a file starts a new line? If it doesn't, how can I check for them?"}, {"role": "assistant", "content": "Yes.fgets()scans and stores the trailing\\nin the destination buffer, if one is present in the source.\n\nQuoting the man page,\n\nReading stops after an EOF or a newline. If a newline is read, it is stored into the buffer.\n\nSo, to answer your query\n\nCheck if String Contains New Line character [...] when a file starts a newline\n\nYou can do, either\n\nstrchr()with\\nto check if the input line contains\\nanywhereCheckbuffer[0] == '\\n'for the starting byte only [file starts a new linecase]."}]} {"messages": [{"role": "user", "content": "I have a requirement to read the characters in a binary file one byte at a time and concatenate them when a certain condition is met. I'm running into problems while reading the null character i.e ^@ as denoted in the caret notations. Neither snprintf nor strcpy is helping me concatenate this null character with other characters. It is strange because when I print this character using\n\n```\nprintf(\"%c\",char1);\n```\n\nit prints out the null character in the caret notation i.e ^@. So my understanding is that even snprintf should have succeeded in concatenation.\n\nCould anybody please let me know how can I achieve such a concatenation?\n\nThanks"}, {"role": "assistant", "content": "C strings are null-terminated. If your input data can contain null bytes, you cannot use the string functions safely. Instead, consider just allocating a large-enough buffer (or dynamically resizing it as needed) and write each incoming byte to the right place in that buffer."}]} {"messages": [{"role": "user", "content": "I have a c programm, which needs two arguments (strings).\nMy problem is I need to do an overflow and one argument needs to be 66000 chars long.\n\nSo I have a textfile which contains a 66000 chars long string.But how do I pass this string from the file do the c program as an argument?\n\nI already tried: myprog < textFile\n\nBut this does not work\n\nOS: Ubuntu."}, {"role": "assistant", "content": "This is more of a bash question.\n\nIf you call:\n\n```\nmyprog < textFile\n```\n\nyou don't pass textFile as argument, so your c program won't find any argument inchar *argv[]. InsteadSTDINis taken to come fromtextFile. Of course you could just read the file content from there, but I understand, you exactly want to pass it as one argument.\n\nSo you would call:\n\n```\nmyprog \"$(cat textFile)\"\n```"}]} {"messages": [{"role": "user", "content": "Okay so I'm trying to do a basic program in VS. Enter a number then it gets printed out. 1 is always printed.\n\n```\nint main(){\n printf(\"Enter an integer: \");\n int n = scanf_s(\"%d\", &n);\n printf(\"%d\", n);\n}\n```"}, {"role": "assistant", "content": "You are assigning the returned value fromscanf_s()to the variablen, that means that the program will print1in case a successful read happened.\n\nWhat you should do is\n\n```\nint numberOfItemsMatched;\nint readValue;\n\nnumberOfItemsMatched = scanf_s(\"%d\", &readValue);\nif (numberOfItemsMatched == 1)\n printf(\"%d\\n\", readValue);\n```\n\nI hope the variable names are self explanatory, and it's always a good idea to use this kind of names."}]} {"messages": [{"role": "user", "content": "The delay function ofdos.hheader file does not work in codeblocks. It shows that delay function is undeclared.\n the following link contains the program below.link\n\n```\nint main ()\n{ \nprintf ( \" This c program will exit in 10 seconds.\\n\"); \ndelay(10000); \nreturn 0;\n}\n```"}, {"role": "assistant", "content": "I was also having same problem & I used this function\n\n```\n#include \n void delay(int milliseconds)\n {\n long pause;\n clock_t now,then;\n\n pause = milliseconds*(CLOCKS_PER_SEC/1000);\n now = then = clock();\n while( (now-then) < pause )\n now = clock();\n }\n```\n\nedited :\n\nAs commented, this does make system busy. I have fund better way to do it, and works for CodeBlocks.\n\n```\n#include \n .\n .\n .\n Sleep(100); //sleep for 0.1 second\n .\n```"}]} {"messages": [{"role": "user", "content": "This program when run on CodeBlocks v13.12 with GCC v4.8.1 gives the output:2, 0. Can someone please explain why or how?\n\n```\n#include \n\nint main ( )\n{\n int function [ 2 ] [ 3 ] = { { 1, 2, 3 }, { 4 } }, i = 1, j = 1;\n function [ i + 1 ] [ j ] = function [ j ] [ i + 1 ]; // Assignment Statement\n printf ( \"%d, %d\", function [ i ] [ j ], function [ j ] [ i + 1 ] );\n\n return 0;\n}\n```\n\nI've also noticed that in theAssignment Statement, the LHS of the expression is always assigned to the variablei. So, for example, if the statement was changed as:\n\n```\nfunction [ i + 1 ] [ j ] = 100; // Assignment Statement\n```\n\nThe value ofiwould be100."}, {"role": "assistant", "content": "```\nfunction [ i + 1 ] [ j ]\n```\n\nAccessing array out of bound will lead to undefined behavior.\n\nfunction [ 2 ]is array out of bound access."}]} {"messages": [{"role": "user", "content": "This question already has answers here:Is it possible to get a core dump of a running process and its symbol table?(3 answers)Closed8 years ago.\n\nUnder Linux, when a process crashes, a core dump will be created.\n\nHowever, I want to create a core dump when the process doesn't crash, but looks buggy. A remote expert need the core dump to analyze.\n\nUnder Windows, we can create a dump file of a process through task manager, and after that, the process is still running.\n\nIs it possible under Linux?"}, {"role": "assistant", "content": "Callgdb, then\n\n```\nattach pid\ngcore\n```\n\nwherepidis the process id of the process in question."}]} {"messages": [{"role": "user", "content": "I'm going through an introduction to programming in C book and I'm not sure what a line of code is doing. I run the code with and without this statement, the result is the same. I suspect that it is getting rid of the 'Enter' after the user inputs a string, but am not sure. I'm assuming the authors wrote this line for a reason. The character array is passed to a function that loops through an array of arrays and finds the text to search for using the 'strstr function.\n\n```\nint main () {\n char search_for[80];\n printf(\"Enter text to search for: \");\n scanf(\"%79s\", search_for);\n search_for[strlen(search_for) -1] = '\\0'; // why is this line here?\n find_track(search_for);\n return 0;\n}\n```"}, {"role": "assistant", "content": "It overwrites the last character of the the scanned string with a null character, shortening the string by one character. Why the programmer wanted to do such a thing I can't say."}]} {"messages": [{"role": "user", "content": "What does the following condition effectively check in C :\n\n```\nif(a & (1<\nchar array[];\n\nint main()\n{\n\natoi(array);\nprintf(\"%d \\n\", array);\n\nreturn 0;\n\n}\n```"}, {"role": "assistant", "content": "The functionatoireturns the converted value. This value needs to be stored. Here in the above program you are not storing the returned value. So there is no effect on the array variable.\n\nPrinting the array in decimal format gives you the address of the array. The program shall print the same value even without theatoifunction. To confirm try this:\n\n```\n//...\nprintf(\"%d \\n\", array);\natoi(array);\nprintf(\"%d \\n\", array);\n```\n\nOutput remains same."}]} {"messages": [{"role": "user", "content": "I have a uninitialized int pointer. And when printed this always shows as 0.\n\nBut when checked against NULL it does not pass the condition.\n\nAnd interestingly this wild pointer takes value without throwing Segmentation Fault.\n\nAny explanations??\n\nCode below:\n\n```\nint main (){\n\nint *p1;\nint *p2;\nint var=90;\nprintf(\"p1 = %x\\n\", p1);\nprintf(\"p2 = %x\\n\", p2);\n\np1 = &var;\n\nif(p2==NULL)\n{return 0;}\n\n*p2 = *p1;\n\nprintf(\"*p2 = %x\\n\", *p2);\n\n}\n```\n\nOutput looks like this..\n\n```\n# gcc -std=c99 -o main *.c\n# main\np1 = 0\np2 = 0\n*p2 = 90\n```"}, {"role": "assistant", "content": "Several points:\n\nUse%pto printvoid *pointers.The internal value of a null pointer isn't necessarily0, although it usually is in modern machines.Dereferencing an uninitialized pointer is undefined behavior, anything could happen. In particular, it doesn't mean segmentation fault will always happen.\n\nTo sum up, exploring UB like this doesn't prove anything."}]} {"messages": [{"role": "user", "content": "I was coding up a short program to compute right endpoints for a given graph (not shown here), so to avoid tedious computation, I decided to write up a short program to do the work for me. Yet my C program just prints out nan. I am very rusty on C, but I am not sure why I am getting NaN.\n\n```\n#include \n\nint main(void) {\n int x;\n float y, z;\n for (x = 0; x <= 8; x++) {\n y += 10.0 - (12.0 + (float)x) / 4.0;\n printf(\"%f\\n\", y);\n }\n z = 0.5 * y;\n printf(\"%f\\n\", z);\n return 0;\n}\n```"}, {"role": "assistant", "content": "```\ny = 10.0 - (12.0 + (float)x) / 4.0;\n```\n\nFollowed by\n\n```\ny = y+1;\n```\n\nThis makes sense else you haveyuninitialized which leads to undefined behavior because the value ofyis undeterminate.\nDuring declaration you can initializeyand use+=operator.\n\nLike\n\n```\nfloat y = 0;\n```"}]} {"messages": [{"role": "user", "content": "Considering the following:\n\n```\n#define SIZE 5\n\n/* ... */\n\nint oxen[SIZE] = {5,3,2,8};\nint yaks[SIZE];\nyaks[SIZE] = oxen [SIZE]; /* -->Out of range */\n```\n\nCan someone explain why its out of range?"}, {"role": "assistant", "content": "Arrays indices in C start at 0, so youroxenandyaksarrays range from0toSIZE-1.\nYou're outside the allowed boundaries, as the compiler rightly warns you about."}]} {"messages": [{"role": "user", "content": "I've recently been trying to program some simple code for the NES. I wrote a batch file that takes the file I wrote in C and turns it into a.nesfile but every time I run it, my C file can't load a header. Here's the script that's causing problems.\n\n```\n#include \n```\n\nNote that I have very little knowledge of C but I'd still like to know what's happening."}, {"role": "assistant", "content": "where is \"nes.h\" located when you run the compiler? if it is in the current directory, then \n #include \"nes.h\" \nwill do.\n\notherwise you must tell the compiler in which directory to find it using -I parameter\n gcc ... -I ..."}]} {"messages": [{"role": "user", "content": "For two pointersaandbthat both point to the same object or function, under which circumstances do the C standards guarantee thata == b? Are there any platforms on whicha != bcould hold whenaandbpoint to the same object?"}, {"role": "assistant", "content": "According to the C Standard (6.5.9 Equality operators from N1548 Committee Draft — December 2, 2010 ISO/IEC 9899:201x)\n\n6 Two pointers compare equal if and only if both are null pointers,both are pointers to the same object(including a pointer to an object\n and a subobject at its beginning)or function, both are pointers to\n one past the last element of the same array object, or one is a\n pointer to one past the end of one array object and the other is a\n pointer to the start of a different array object that happens to\n immediately follow the first array object in the address space.109)"}]} {"messages": [{"role": "user", "content": "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.Closed8 years ago.Improve this question\n\n```\nunsigned char num;\nunsigned char b0=1;\nunsigned char b1=0;\nunsigned char b2=1;\n```\n\nHow to assign num tob2b1b0?\nIf we print num in binary at the end, it should be 101."}, {"role": "assistant", "content": "Assuming b0, b1, and b2 are all bits within thenumvariable, and assuming little-endianness:\n\n```\nnum = 1 | 4;\n```\n\nIf you really needed to use theb*variables (I'm assuming you don't), You could do this:\n\n```\nunsigned char b0 = 1U;\nunsigned char b1 = 2U;\nunsigned char b2 = 4U;\nunsigned char num = b0 | b2;\n```"}]} {"messages": [{"role": "user", "content": "Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed8 years ago.Improve this question\n\nI want to write a function in Cvoid cumsum(int *array, int length)that receives an array as an input then changes its element of that array to the cumulative sum using RECURSION. For instance if i havearray = {1,2,3}the output should bearray={1,3,6}.\n\nSo, how I can do this using recursion."}, {"role": "assistant", "content": "```\nvoid cumsum(int *array, int index) {\n if(index <= 0) return;\n cumsum(array, index -1);\n array[index] += array[index - 1];\n}\n\nint main(void) {\n int array[] = {1,2,3};\n cumsum(array, 2}; //you had to call with the index of the last element (size-1)\n printf(\"%d %d %d\\n\", array[0], array[1], array[2]);\n return 0;\n}\n```"}]} {"messages": [{"role": "user", "content": "This question already has answers here:How can I edit an executable during compiling, without changing its source? [duplicate](2 answers)Replace #define X macro value with another one specified in compilation command(1 answer)Closed8 years ago.\n\nI have a C program which I am NOT allowed to edit that looks like this:\n\n```\n#include \n\n#ifndef YEAR\n #define YEAR \"2013\"\n#endif\n\nint main(){\n printf(\"Hello world from \" YEAR \"\\n\");\n return 0;\n}\n```\n\nI need to create a makefile to compile this program and change the YEAR to 2014, so that the output will be \"Hello world from 2014\" without editing the C program. How can I do this?"}, {"role": "assistant", "content": "The compilation command should start withgcc -Wall -DYEAR='\"2014\"'. It is up to you to code yourMakefilewith a suitableCFLAGSsettings.This answershould be inspirational."}]} {"messages": [{"role": "user", "content": "generate random number 0-1, when I type the input number less than 4, the code works fine. However when the input number above 4, the eclipse stop working. what's wrong with my code\n\n```\n#include \n#include \n#include \ndouble ran(double x0, double x1){\nreturn x0+(x1-x0)*rand()/((double)RAND_MAX);\n}\nint main(void) {\nint a,i;\ndouble *b;\nprintf(\"input the size\\n\");\nscanf(\"%d\", &a);\nb=(double*)malloc(sizeof(int)*a);\nsrand((unsigned)time(NULL));\nfor(i=0;i\n\nint main() {\n int *alpha[17];\n\n *(alpha+4)= 35;\n *(alpha+5)= 35;\n *(alpha+12)= 50;\n\n printf(\"%d\", *(alpha+4));\n *(alpha+8)=*(alpha+5) + *(alpha+12);\n\n return 0;\n}\n```\n\nWhy is the line after theprintfnot working, and causing a crash, when the previous lines ran perfectly? I am trying to get the 9th value to equal the sum of the 6th and 13th value."}, {"role": "assistant", "content": "int *alpha[17];creates array of pointers.\n\nIf you want array of int, useint alpha[17];\n\nYour assignations are succesful because of implicit cast from int to pointer. (I hope you are getting warnings)\n\nAdding two pointers is not only non-sensical, but also not allowed inC.This postcovers why adding two pointers is forbidden in C++, but arguiments are applicable to C also."}]} {"messages": [{"role": "user", "content": "I am trying to read a file of the form\n\n```\nA number,number\nA number,number\n[space] B number,number\netc\n```\n\nwhere I want to read only the lines that do start with a space (ie, in the example above, the last line only). I wrote this loop:\n\n```\nwhile ((g = fscanf(fp,\" %c %x,%d\\n\",&a,&b,&c) != EOF){\n printf(\"%c %x,%d\\n\",a,b,c);\n }\n```\n\nbut despite the space I put at the beginning of the string, it still outputs all the lines. I know I can filter them inside the loop, but is it possible to specify it in the fscanf?"}, {"role": "assistant", "content": "OP: it possible to specify it in thefscanf?A: Yes, but its ugly. Use the best tool for the job.\n\nUsefgets(), then scan withsscanf().\n\n```\nchar buf[100];\nchar a;\nunsigned b;\nint c;\nwhile (fgets(buf, sizeof buf, fp) != NULL) {\n // Thank-you @Chris Dodd\n if ((buf[0] == ' ') && (sscanf(buf, \" %c%x,%d\", &a,&b,&c) == 3)) {\n printf(\"%c %x,%d\\n\",a,b,c);\n }\n}\n```"}]} {"messages": [{"role": "user", "content": "On debugging the following two codes, first one shall print1 1and second one2 1, Can I please get explanation for this?\nI do have moderate knowledge of pointers but I don't seem to understand this.\n\n1.\n\n```\nvoid main() \n{\n int i = 257; \n int *iPtr = &i; \n printf(\"%d %d\", *((char*)iPtr), *((char*)iPtr+1) );\n}\n```\n\n2.\n\n```\nvoid main() \n{\n int i = 258; \n int *iPtr = &i; \n printf(\"%d %d\", *((char*)iPtr), *((char*)iPtr+1) );\n}\n```"}, {"role": "assistant", "content": "In little-endian systems, here are how are stored the values257and258in memory:\n\n```\n257 = 0x101\n\n0x01 0x01 0x00 0x00\n\nbyte 0, byte 1, byte 2, byte 3\n\n258 = 0x102\n\n0x02 0x01 0x00 0x00\n\nbyte 0, byte 1, byte 2, byte 3\n```"}]} {"messages": [{"role": "user", "content": "This question already has an answer here:Getting my own IP address by connect()ing using UDP socket?(1 answer)Closed9 years ago.\n\nI'm trying to get my own IP address by trying to connect() to 8.8.8.8 usingUDPsocket and then callinggetsockname()function.\n\nI've written a functionget_my_ip(), and the code worked when it was placed in my server program, but as a separate function, it fails. It prints some strange characters instead of my IP address.\n\nThe only thing I changed from the code in my server program was return NULL instead of return 1, or return 2, because it was insideint main().\n\nCan anyone see why my program is not working?\n\nThank you."}, {"role": "assistant", "content": "You must initialize addrlen.\n\n```\naddrlen = sizeof remoteaddr;\ngetsockname(sockfd, (struct sockaddr*)&remoteaddr, &addrlen);\n```"}]} {"messages": [{"role": "user", "content": "I am new to programming, and the following line confused me:\n\nswitch_block_conn[from_side][to_side][from_track].nelem = 0\n\nIs this line actually describing an array? What is it doing?"}, {"role": "assistant", "content": "From the syntax in the given code sample, assuming it is valid code, it is implied that:\n\nswitch_block_connis a 3-d array. You can infer this from the 3 array index operations.The individual elements inswitch_block_connare structs. You can infer this from the.operator used.Those structs have (among potentially other members), annelemmember. You can infer this from the name given after the..Thenelemmember is a numeric or pointer type (specific size and type unknown from this sample). You can infer this from the assignment of 0 to that member.\n\nNote that most of these conclusions can be drawn only in C and not C++ due to operator overloading in C++."}]} {"messages": [{"role": "user", "content": "sorry if my question sounds confused.\nHere is my code\n\n```\nvoid display_Item_At_Location(char in[][SIZE_OF_ARRAY])\n{\n int loc;\n int i;\n printf(\"Which line would you like to display?\\n\");\n scanf(\"%d\", &loc);\n\n for(i = 0; i < SIZE_OF_ARRAY; i++)\n {\n printf(\"%c\", in[loc][i]);\n }\n\n return;\n}\n```\n\nThe first line of array should be \"Go to School\" but when I print it, it will be \"Go to School?????????????????????????\" How should it do so I only get \"Go to School\"?"}, {"role": "assistant", "content": "If your strings are NULL-terminated, you could skip theforloop and just do:\n\n```\nfprintf(stdout, \"%s\\n\", in[loc - 1]);\n```\n\nfor a given valuelocwithin index bounds (assuminglocvalue is 1-indexed)."}]} {"messages": [{"role": "user", "content": "I feel quite 'stupid' as asking this question but if anyone can show me the methods to modify the input result appeared on the command window.\n\nExample:\n\nI want to sort 5 numbers (1, 3, 4, 7, 5) in smallest-to-biggest order and the result on the command window must be:\n\n```\ninput: 1 3 4 7 5 /* 1 line input */\noutput: 1 3 4 5 7 /* 1 line output */\n```\n\nEdit:\nHere is my code\n\n```\nfor (i = 0; i < 5; i++)\n{\n scanf(\"%d \", &array[i]);\n}\n```\n\nIf I use this code the result on command window must be:\n\n```\n1\n3\n4\n7\n5\n```\n\nBut I want all the input number in only 1 line as:\n\n```\n1 3 4 7 5\n```\n\nSo what do I have to do with my code?"}, {"role": "assistant", "content": "Regarding to your edited question, just replace\"%d \"with\"%d\"."}]} {"messages": [{"role": "user", "content": "By default, GDB's internal variables will be $1, $2, $3, .... How to restart naming them from $1?\n\n```\n(gdb) p v1\n$1 = 7\n(gdb) p v2\n$2 = 8\n(gdb) p v3\n$3 = 9\n(gdb) ??? // what should be put here?\n$1 = 0\n```"}, {"role": "assistant", "content": "Looking atthe documentation, there's no explicit command to clear the value history.\n\nIt does mention that thefileandsymbol-filecommands, which can change the symbol table, clear the history.\n\nAlso, you can useoutputinstead ofprintto avoid putting the printed value in the value history."}]} {"messages": [{"role": "user", "content": "I'm trying to understand a piece of code shown below. I'm having problems with understanding what \"array +7\" or \"array,+3\" means. Does it increment the first number in the array by 7/3?\n\n```\nint array[8] = {1,2,4,8,16,32,64,128}; \nint *ptr_array[4];\nint *dyn_array = malloc(sizof(int)*8);\n\nptr_array[0] = array;\nptr_array[1] = array +7;\nptr_array[2] = array +3;\nptr_array[3] = dyn_array;\n```"}, {"role": "assistant", "content": "array + 7is a pointer to the eight element of the array, it's equal to&array[7], becausex[y]is defined as*(x + y)."}]} {"messages": [{"role": "user", "content": "I am writing a C code which reads from a file and generates an intermediate.cfile.\nTo do so I usefprintf()to print into that intermediate file.\n\nHow can I print\"?"}, {"role": "assistant", "content": "You can use escape symbol\\\"For example\n\n```\nputs( \"\\\"This is a sentence in quotes\\\"\" );\n```\n\nor\n\n```\nprintf( \"Here is a quote %c\", '\\\"' );\n```\n\nor\n\n```\nprintf( \"Here is a quote %c\", '\"' );\n```"}]} {"messages": [{"role": "user", "content": "Why the code doesn't work unless I remove the comment?\n\n```\n#include \n\nint main(){\n int num = 5;\n switch(num){\n case 5:\n //printf(\"\");\n int another = 1;\n printf(\"%d\", num+another);\n break;\n }\n}\n```\n\ngcc returns an error:\n\n```\nprog.c: In function ‘main’:\nprog.c:7:13: error: a label can only be part of a statement and a declaration is not a statement\n```\n\nThanks."}, {"role": "assistant", "content": "The reason is outlined here:Why can't variables be declared in a switch statement?\n\nAs a workaround, you can do this:\n\n```\n#include \n\nint main(){\n int num = 5;\n switch(num){\n case 5:;\n //printf(\"\");\n int another = 1;\n printf(\"%d\", num+another);\n break;\n }\n}\n```\n\ninclude a semicolon after the case as a workaround.Fool the compiler into thinking a statement follows and not a declaration. Taken fromhere"}]} {"messages": [{"role": "user", "content": "Why is \"i\" variable getting incremented twice in my program?\n\nI modified the question but why is the output different. shouldn't it be same?.?\n\nCode :-\n\n```\n#include\n#define MAX(x,y) (x)>(y)?(x):(y)\nvoid main(void)\n{\n int i = 10;\n int j = 5;\n int k = 0;\n k == MAX(i++, ++j);\n printf(\"%d %d %d\",i,j,k);\n}\n```\n\nOutput :-\n 11 7 0\n\nShouldnt the output be 12 6 0"}, {"role": "assistant", "content": "Use braces around your macro definitions:\n\n```\n#define MAX(x,y) ( (x)>(y)?(x):(y) )\n```\n\nThe expanded expression (with the original macro definition)\n\n```\nk == (i++)>(++j)?(i++):(++j);\n```\n\ngroups as\n\n```\n(k == i++ > ++j) ? i++ : ++j;\n```\n\ni++ > ++jevaluates to1, which is unequal tok(kis 0), so the third operand of?:(++j) is evaluated. So,iis incremented once,jtwice, andkwasn’t changed since its initialization, hence your output."}]} {"messages": [{"role": "user", "content": "What happens if we free an automatic variable usingfree()?\n\nWhat about in the following code: ifnisstaticdoes it get automatically free'd after the last loop iteration, can wefreeit, or what?\n\n```\nfor(count = 0; count < 5; count++) { \n static int i += 1\n}\n```"}, {"role": "assistant", "content": "What happens if we free an automatic variable usingfree()?\n\nIt will invokeundefined behavior.\n\nArgument tofreemust be a pointer that was returned by memory allocation function(malloc,calloc,realloc). The argument may also be a null pointer, in which case the call offreehas no effect."}]} {"messages": [{"role": "user", "content": "I'm getting segmentation fault with my following code. This is the max size in which I get no segmentation errorSIZE = 1000000if I increase it one zero more, I got segmentation error.\n\n```\n#include \n#include \n#include \n#include \n\nuint64_t SIZE = 10000000;\n\nuint64_t getsum(int data[], uint64_t size)\n{\n uint64_t sum = 0;\n uint64_t i = 0;\n\n for ( i; i < size; ++i)\n sum += data[i];\n\n return sum;\n}\n\nint main(void)\n{\n srand((unsigned int)time(NULL));\n int data[SIZE];\n uint64_t i = 0;\n\n for ( i; i < SIZE; ++i)\n data[i] = rand() % 100 + 1;\n\n printf(\"sum: %\"PRIu64\" \\n\", getsum(data, SIZE));\n\n return 0;\n}\n```"}, {"role": "assistant", "content": "You are exceeding the available stack space, therefore causing a segfault. If thedataarray is so big, it shouldn't be with automatic storage.\n\nYou should either define itstatic, globally, or allocate it on the heap."}]} {"messages": [{"role": "user", "content": "```\nint t[ ] = { 0x0203, 0x4 };\nchar *p=t;\nprintf(\" *p = %d; *(p+1) = %d \",*p,*(p+1));\n```\n\nWhy does *(p+1) always return 2, regardless of the second element in t?"}, {"role": "assistant", "content": "You're running this program on alittle endiancomputer. This means your int array is stored in memory as bytes in the following order:\n\n0x03 0x02 0x00 0x00 (first integer)\n0x04 0x00 0x00 0x00 (second integer)\n\nTry to print out*(p+i)for p between 0 and 7, it should verify this."}]} {"messages": [{"role": "user", "content": "I'm learning about dynamic memory at the moment, but my book is not clear about this. Why does the declaration of thedynArraydoesn't not have the [ ] brackets which is used for array declaration when not using malloc. Why is the[ ]not needed when declaring, but needed in the loop.\n\n```\nint * dynArray;\ndynArray = malloc(sizeof(int)*5);\nsrand ( time(NULL) );\n\nfor(i=0; i<=myInt; i++){\n dynArray[i] = rand()%100;\n }\n```"}, {"role": "assistant", "content": "It is not needed in the loop; pointers can be accessed as arrays and arrays can be accessed as pointers\n\nThis is equivalent\n\n```\nfor(i=0; i<=myInt; i++){\n *(dynArray+i) = rand()%100;\n}\n```"}]} {"messages": [{"role": "user", "content": "I started learning C and i am still at simple programs but with a ton of errors :/\nThe following code once it catches the wrong input (in the else statement) will continue running and it wont stop for the next scan... why is that happening?\n\n```\nconst float inch_to_cm = 2.54;\n\nint main()\n{\n bool run = true;\n float usr_input;\n while(run){\n printf(\"Please enter the inches: \");\n if (scanf(\"%f\", &usr_input) == 1){\n printf(\"Result: %4.2f \\n\", inch_to_cm*usr_input);\n run = false;\n }\n else{\n printf(\"I asked for a number!\\n\");\n }\n }\n\n return 0;\n}\n```"}, {"role": "assistant", "content": "If you are entering anything else than a numerical value then it will not read byscanfand live there for infinite time causing infinite loop. You must have to flush the input buffer. Place this after theelsestatement:\n\n```\nint c;\nwhile((c = getchar()) != '\\n' && c != EOF);\n```"}]} {"messages": [{"role": "user", "content": "I would normally declare and initialize an array of integers like so:\n\n```\nint a[3] = { 1, 2, 3}; // declares an array of 3 integers\n```\n\nBut today it occurred to me to wrap the list in parentheses as well, like so:\n\n```\nint a[3] = ( { 1, 2, 3} ); // gives compile time error\n```\n\nWhich produced the following compiler error:\n\n```\nexpected ';' before '}' token\ninvalid initializer\n```\n\nNaturally, one would normally have no reason to wrap the list in parentheses, but now I'm curious - whycan'twe use parenthesis here?"}, {"role": "assistant", "content": "It's simply not valid syntax. Here are the relevant sections of the grammar from the C99 standard:\n\n[6.7]\n\ninit-declarator:\n declarator\n declarator = initializer\n\n[6.7.8]\n\ninitializer:\n assignment-expression\n { initializer-list }\n { initializer-list , }"}]} {"messages": [{"role": "user", "content": "Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question\n\nWhat changes does it happen in the program when the exception is caught? How does thrown exception is caught in nearest catch block."}, {"role": "assistant", "content": "Well, I tried implementing simple exception-handling in C 2 years ago. Let me show it to you.\n\nhttps://github.com/dlarudgus20/CTryCatch\n\n(In fact, I made the github repository to practice as soon as I saw you question - it's my first repository >o< Thank you to give me the opportunity to use github!)"}]} {"messages": [{"role": "user", "content": "I have seen this countless of times. Instead of\n\n```\n#ifndef _common_h_\n#define _common_h_\n\n#endif /* _common_h_ */\n```\n\npeople sometimes define their header files in following format:\n\n```\n#ifndef _common_h__479124197491641974591\n#define _common_h__479124197491641974591\n\n#endif /* _common_h__479124197491641974591 */\n```\n\nWhat is that random number good for? I just couldn't successfully google any answer to this."}, {"role": "assistant", "content": "The idea is to make it harder to trip yourinclude guardunintentionally, and/or to avoid triggering someone elses' include guards.\n\nFor example, if you are writing a library, and you have aCommon.hheader, then using_common_h_for the guard could prevent users of your library from having_common_h_guards in their own libraries, which is not ideal. Adding a random number makes such collisions nearly impossible."}]} {"messages": [{"role": "user", "content": "Is it safe to have one thread modify an atomic unit (e.g. a char) while the other only reads it?\nIn an environment that permits this of course, like freertos.\n\nI have been given some code that does just this, it uses a bool (defined as char) as a semaphore, I'm not sure why they didnt use a semaphore just for claritys sake, but then again I cant see the danger in using a char either really."}, {"role": "assistant", "content": "Its safe If:\n\n1.Your processors reads a character in single instruction(which is very likely)\n\n2.Your Processor architecture is not such that while executing a instruction external interrupt can change control flow.\n\n3.Point 2 is vaild only if your variable is updated through ISR"}]} {"messages": [{"role": "user", "content": "Is it possible, for a pure C shared library, to break the ABI compatibility while API compatibility is not broken?\n\nAlso, if one writes a library A which provides all the API functions of an existing library B, with some additional API functions, is library A ABI compatible with library B?"}, {"role": "assistant", "content": "You can have different calling conventions in two libraries implementing the same API, if that answers your first question.\n\nFor the second question: You could change e.g. a structure pointer to a pointer to another structure in the declaration of a function. According to the standard they have to have the same representation and alignment requirements, but the API is changed (and code calling that function of A must be changed to call the same function in B in order to compile)."}]} {"messages": [{"role": "user", "content": "I finished my programming classes in C, and thought I would write some code down. BOOM! I run into so many problems. I guess the C language is so complicated, even a book can't explain how it works entirely.\n\nThis is my problem(I am trying to display something using a pointer)\n\n```\n#include \n#include \n#include \n\nvoid main()\n{\n char *a;\n system(\"cls\");\n *a = {\"hello\"};\n printf(\"%s\",a);\n getch();\n}\n```"}, {"role": "assistant", "content": "```\n*a = {\"hello\"};\n```\n\nThis dereferenced the pointer and assigned something to that memory location. The reason it crashed is because the pointer was uninitialised,ieit did not point at anything (actually it did point at something, but that something was an undefined memory location).\n\nIf you had done the following, your program would have worked:\n\n```\na = \"hello\";\n```\n\nThe type ofaischar*. The type of\"hello\"is alsochar*."}]} {"messages": [{"role": "user", "content": "I have noticed that 10(^7) or 10 000 000 increment is equal to 10 seconds in my environment.\nHere is an example of custom function that works for me that wastes x seconds before the next line:\n\n```\nvoid pause(unsigned short seconds)\n{\n int f;\n unsigned long long deltaTime = seconds*10000000;\n\n for(f=0; ftype)\n {\n case SDL_QUIT:\n //your quit procedure\n break;\n }\n\n}\n```"}]} {"messages": [{"role": "user", "content": "I have noticed that an empty array in the end of the structure is often used in open source projects:\n\n```\ntypedef struct A\n{\n ......\n void *arr[];\n} A;\n```\n\nI want to know is this a C standard? Or only OK for gcc compiler?"}, {"role": "assistant", "content": "As of C99, it is now a C standard. Pre-C99 compilers may not support it. The old approach was to declare a 1-element array, and to adjust the allocation size for that.\n\nNew way:\n\n```\ntypedef struct A\n{\n ......\n void *arr[];\n} A; \n\nint slots = 3;\nA* myA = malloc(sizeof(A) + slots*sizeof(void*));\nmyA->arr[2] = foo;\n```\n\nOld way:\n\n```\ntypedef struct A\n{\n ......\n void *arr[1];\n} A; \n\nint slots = 3;\nA* myA = malloc(sizeof(A) + (slots-1)*sizeof(void*));\nmyA->arr[2] = foo;\n```"}]} {"messages": [{"role": "user", "content": "Instead of being an int, I would like prev to be a pointer to another Vertex. However, I can't declare prev as a VertexPointer because the typedef for VertexPointer comes afterwards. How should I declare prev?\n\n```\n#include \n#include \n#include \n\n//function generates a random float in [0,1]\nfloat rand_float();\n\n//all info for a vertex\ntypedef struct{\n int key;\n int prev;\n float loc[4];\n} Vertex;\n\n//using the pointer\ntypedef Vertex *VertexPointer;\n```"}, {"role": "assistant", "content": "You could try this\n\n```\ntypedef struct Vertex{\n int key;\n struct Vertex *prev;\n float loc[4];\n} Vertex;\n```"}]} {"messages": [{"role": "user", "content": "Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question\n\nfgetsis not working as I expected.\n\n```\ntypedef struct {\n int itemnumber;\n char name [50];\n double price;\n int stock;\n int discount;\n int reorder;\n int reorderquantity;\n} item;\n\nitem x;\nitem *px[n];\npx[n] = malloc(sizeof(item));\n\nprintf (\"ENTER THE NUMBER OF ITEMS\\n\\n\");\nscanf (\"%d\",&n);\n\nfor (i=0; iitemnumber);\n fgets(px[i]->name,50,stdin);\n px[i]->name[strlen(px[i]->name)-1]='\\0';\n // fflush(stdin);\n printf(\"%s\",px[i]->name);\n}\n```"}, {"role": "assistant", "content": "You only malloc one instance.\nyou should do px[n] = malloc(sizeof(item)*n); after you scanf n"}]} {"messages": [{"role": "user", "content": "This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed9 years ago.\n\nI'm currently learning C, and my teacher gave us some homework. We had to identify the output of some code. I don't understand howy=4.\n\nThe code is as follows\n\n```\nint main() {\n\n int w = 3, y = 3;\n printf(\"w = %i\\n\", --w + w--);\n printf(\"y = %i\\n\\n\", y = w + y++);\n\n return 0;\n}\n```"}, {"role": "assistant", "content": "The behaviour is undefined since you modify the value of a variable twice between two sequence points.\n\nYou should read more about sequence pointshttp://en.wikipedia.org/wiki/Sequence_point.This is what the Standard says about it:\n\nAt certain specified points in the execution sequence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place."}]} {"messages": [{"role": "user", "content": "I was trying to figure out what statement to use to get the user to enter a number between 1 and 10.\n\nhere is what i have so far.\n\n```\nint a;\nprintf(\"Enter a number between 1 and 10: \\n);\nscanf(\"%d\", &a);\n```"}, {"role": "assistant", "content": "```\nint input;\n\nwhile (true){\n scanf(\"%d\",&input);\n if (input>=1 && input<=10){\n // process with your input then use break to end the while loop\n }\n else{\n printf(\"Wrong input! try Again.\");\n continue;\n }\n}\n```"}]} {"messages": [{"role": "user", "content": "I would like to know if there is a way to access a list of all open directories from the current process? I have a function that opens many directories recursively but exits the program as soon as something is wrong. Of course, I would like to close all directories before calling exit() without having to keep track of everything I open. Is this even possible?\n\nThanks!"}, {"role": "assistant", "content": "I have a function that opens many directories recursively but exits the program as soon as something is wrong.\n Of course, I would like to close all directories before calling exit() without having to keep track of everything I open.\n\nI think your very approach is wrong. What is the point of opening the directories if you don't keep a handle on them?\n\nYou should keep a reference to the opened directory as long as you need it and discard it as soon as you can.\n\nKeep in mind that normally, the nomber of open file descriptors is limited, e. g. to 1024."}]} {"messages": [{"role": "user", "content": "I have a variablesof typesize_tand a variablebufferof typeunsigned char. I wish to save this variable inbufferin network order as 4 bytes.\nHow can I do it?"}, {"role": "assistant", "content": "```\nchar c8[8] = {0};\nsize_t s = 0x1233456789abcdef0, s_be = 0;\n\nif (4 == sizeof(s))\n{\n s_be = htonl(s);\n}\nelse if (8 == sizeof(s))\n{\n s_be = htobe64(s);\n}\nelse\n{\n assert(0);\n}\n\nmemcpy(c8, &s_be, sizeof(s_be));\n```\n\nForhtobe64()have a look here:https://stackoverflow.com/a/4410728/694576"}]} {"messages": [{"role": "user", "content": "I have a code:\n\n```\nint double(int *x) {\n *x = (*x) + (*x);\n return *x;\n}\n\nint main() {\n int i = 10;\n int j;\n j = double(&i);\n printf(\"i= %d, j = %d\\n\", i, j);\n return 0;\n```\n\n}\n\nThe output is i = 20, j = 20. \nWhy does the value of i change?"}, {"role": "assistant", "content": "Because you are passing a pointer to i to the double function, which allows it to change it's value. This is known as \"pass by reference\". If you had just used ints instead of pointers, the value of i would not have changed. This is called \"pass by value\"."}]} {"messages": [{"role": "user", "content": "This question already has answers here:What should main() return in C and C++?(19 answers)Closed9 years ago.\n\nWhen writing a C/C++ program, specifically with latest compilers, why do we need to return an integer from the main() method? Like int main() and we return \"return 0\" from it. So what is the exact reason behind this?"}, {"role": "assistant", "content": "The return value of main() becomes the exit status of the process. Traditionally, an exit status of zero usually means “OK,” while any non-zero value indicates some kind of error. This is analogous with how many system calls likewise return zero or an error code.\n\nEven more information at J. Leffler's epic answer to this, similar question:What should main() return in C and C++?"}]} {"messages": [{"role": "user", "content": "I've managed to build a native executable for Android, after readingHow do I build a native (command line) executable to run on Android?, but I can't execute it on my unrooted phone, it gives\n\n/system/bin/sh: /storage/sdcard0/Download/hello_world: can't execute: Permission denied\n\nbecause the SD card is mounted withnoexec, and I can't write anywhere else."}, {"role": "assistant", "content": "I found a solution that works for me - it seems that/data/local/tmpis writable, and it isn't on anoexecpartition.\n\nThe solution requires usingadb. I connected the phone through USB, and I enabled USB debugging from developer options.\n\nThen I uploaded the file to the phone using:\n\n```\nadb push C:\\Workspace\\hello_world\\libs\\armeabi\\hello_world /data/local/tmp/hello_wo\nrld\n```\n\nThen I ran adb shell:\n\n```\nadb shell\n```\n\nAnd from it I changed the write permission, and ran it:\n\n```\nchmod 755 /data/local/tmp/hello_world\n/data/local/tmp/hello_world\n```"}]} {"messages": [{"role": "user", "content": "How do you do this:\n\n```\nprintf(\"I would like %d tomatoes\", numTomatoes);\n```\n\nwith:\n\n```\nwrite(STDOUT, \"HOW?\", 4);\n```\n\nIs there some type of pre-processing that makes it all a char array and then I can find the length and print it out?\n\nContext: I need to use write instead of printf inside of signal handlers."}, {"role": "assistant", "content": "To get a formatted string you can usesprintf/snprintf;\n\n```\nchar buffer[0x1000];\nsize_t length = snprintf(buffer, sizeof(buffer), \"I would like %d tomatoes\", numTomatoes);\nwrite(STDOUT_FILENO, buffer, length);\n```\n\nEdit:If you are bothered by the large buffer size then you can (in modern C99) do the following to determine the necessary buffer size first:\n\n```\nsize_t length = snprintf(NULL, 0, \"I would like %d tomatoes\", numTomatoes);\nchar buffer[length];\nsnprintf(buffer, length, \"I would like %d tomatoes\", numTomatoes);\nwrite(STDOUT_FILENO, buffer, length);\n```"}]} {"messages": [{"role": "user", "content": "Hey guys can we use two or moremain()in different C source files under same project in eclipse? What am I actually trying is to write a server and a client source file under same project with main() in each of it. I am getting an errormain() redeclaration. is there any way to do this? If yes please tell me how to run that successfully in eclipse CDT Kepler. Regards,"}, {"role": "assistant", "content": "You could alsosimulatehaving twomainfunctions in the same project by havingmaincall eithermainClientormainServer(your two main functions renamed) depending on a condition of your choice."}]} {"messages": [{"role": "user", "content": "Example Tree\n\n```\n2 -> root\n1 -> Left\n3 -> right\n```\n\nstored in array in in order [1, 2, 3]\n\nHow to retrieve the root node knowing that the tree is stored in inorder?\n\nAccording to me all three as possible candidates of root node."}, {"role": "assistant", "content": "Indeed all 3 are possible candidates.\n\nHere are possible trees that would result in the given in-order traversal:\n\n```\n1 2 3\n \\ / \\ /\n 2 1 3 2\n \\ /\n 3 1\n```\n\nAn in-order traversal isn't necessarily sufficient to uniquely identify a tree (and thus consistently identify the root). Assuming unique tree elements, you need either a pre-order or post-order traversal paired with an in-order traversal.\n\nReference -Which combinations of pre-, post- and in-order sequentialisation are unique?"}]} {"messages": [{"role": "user", "content": "I am asking how can I read a double, int or any other type fromstdinusing thereadsystem call.\n\nWhat I've done so far:\n\n```\nlong val ;\nssize_t r;\nr = read(STDIN_FILENO,&val,sizeof(long));\nprintf(\"%ld\\n\",val);\n```\n\nAny idea?"}, {"role": "assistant", "content": "You are not being clear whether you want to read (a) the ASCII representation of a long, double, int or whatever (i.e. the string \"0.12345\", or (b) the binary representation of that value.\n\nIf you want to do (a), you need to usefscanf. See the above answer.\n\nIf you want to do (b), your code looks right to me. What is the 'bad result' you are having? Did you check forr<0, then look aterrnoor useperror().\n\nI suspect the problem is you wanted to do (a), but have coded for (b)."}]} {"messages": [{"role": "user", "content": "I'm having difficulty finding out a specific way to copy a short integer into a char array.\n\nLet's say I have:\n\n```\nunsigned short xVal = 5;\nunsigned short yVal = 12;\nchar x[3];\nchar y[3];\n```\n\nand I want to copy the short integers into the respective char arrays filling the empty digits with 0s:\n\n```\nchar value output\nx 5 0005\ny 12 0012\n```\n\nHow can it be done in c++?"}, {"role": "assistant", "content": "The simplest would be.\n\n```\nunsigned short xVal = 5;\nunsigned short yVal = 12;\nchar x[5];\nchar y[5];\nsprintf(x,\"%04u\",xVal);\nsprintf(y,\"%04u\",yVal);\nprintf(\"%s\\n\",x);\nprintf(\"%s\\n\",y);\n```\n\nNote that x and y should be declared as char arrays of 5 elements for the null character"}]} {"messages": [{"role": "user", "content": "Is it possible, under some circumstance, in ANSI-C, to start arrays in index 1 instead of 0? (some compiler options which stays under the definition of ANSI-C, not MACROS or such)\n\ne.g\n\n```\nint arr[2];\narr[2] = 5;\narr[1] = 4;\n```\n\nwill be valid code which will behave properly."}, {"role": "assistant", "content": "No.\n\nThere is no such thing in ANSI C."}]} {"messages": [{"role": "user", "content": "This question already has answers here:Ternary operator (?:) in Bash(23 answers)Closed9 years ago.\n\nin C I can assign a value in this way:\n\n```\nval = (cond)? val_true : val_false;\n```\n\nand it's equivalent to\n\n```\nif (cond) \n val = val_true;\nelse\n val = val_false;\n```\n\nAre there an equivalent ofval=(cond)? val_true : val_falsein shell bash?"}, {"role": "assistant", "content": "Suppose you want it to be somewhat like this:\n\n```\ntrue=1\n[ $true ] && p=1 || p=0\n```\n\nAll you have to do is keep whatever condition you want within those brackets.\n\nIf it’s valid, then the branch after the AND is followed, otherwise that after the OR is followed.\n\nThis is equivalent to this:\n\n```\nif [ $true ]; then p=1; else p=0; fi\n```\n\nSo you should be aware of the construct in case you ever run into it, but it’s arguably less readable than just listing out explicitly what you’re doing."}]} {"messages": [{"role": "user", "content": "Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 years ago.Improve this question\n\nI am doing terminal application in xcode using c/c++, I don't want to use glut/glew. I'd like to create window and opengl context myself. Is it even possible?"}, {"role": "assistant", "content": "You're mixing up things. GLEW is completely unrelated to window creation. It's there to load extension and modern OpenGL functions.\n\nGLUT is not the only OpenGL windowing framework around. If you want to implement your own event loop have a look at GLFW, or SDL-2 or SFML. Other than that you've got a lot of work ahead (and doing it right is no easy task)."}]} {"messages": [{"role": "user", "content": "I read a lot of stuff about strtok(char* s1, char* s2) and its implementation. However, I still can not understand what makes it a dangerous function to use in multi-threaded program. Can somebody please give me an example of a multi-threaded program and explain the issue there? Please not that I am looking for an example that shows me where the problem arises.\n\nps: strtok(char* s1, char* s2) is part of the C standard library."}, {"role": "assistant", "content": "In the first call to strtok, you supply the string and the delimiters. In subsequent calls, the first parameter is NULL, and you just supply the delimiters. strtok remembers the string that you passed in.\n\nIn a multithreaded environment, this is dangerous because many threads may be calling strtok with different strings. It will only remember the last one and return the wrong result."}]} {"messages": [{"role": "user", "content": "I have a network programming c code that can retrieve a HTTP page, the thing is I want to remove GET response header that come with the actual data of the page, I know that I have to look for the first \"\\r\\n\\r\\n\" but all the thing that I've tried so far didn't work !\nso how can I strip these response header line from the beginning of the buffer??"}, {"role": "assistant", "content": "As the GET response header is at the beggining of the buffer, you may try to find the first occurence of \"\\r\\n\\r\\n\" using a function like strstr:\n\n```\nchar *p = strstr(buffer, \"\\r\\n\\r\\n\");\n```\n\nand then return p+4, because p will point to the first \\r. p+4 will point to whatever is after the \"\\r\\n\\r\\n\". To return it from a function, just return p+4."}]} {"messages": [{"role": "user", "content": "I'm writing simpleCprogram usingEclipse. I have several system includes. But now I have downloaded source code of library that contains one *.c and one *.h file. What is good manier to place these files? Should I place them toworkspace, or create directoryIncludenearsrcor place in/usr/local/include?"}, {"role": "assistant", "content": "I you want to make the headers available to other users on the machine/usr/local/includewould be the place to put them. Otherwise keep them somehwere in your$HOME.\n\nAnother alternative would be to put the sources to/usr/local/lib//src/includeand link/usr/local/lib//src/includeto/usr/local/include/. Withbeing the name of the tool."}]} {"messages": [{"role": "user", "content": "```\n#include\n#include\nvoid main()\n{\n int str1[25];\n int i=0;\n printf(\"Enter a string\\n\");\n gets(str1);\n while(str1[i]!='\\0')\n {\n i++;\n }\n printf(\"String Length %d\",i);\n getch();\n return 0;\n}\n```\n\ni'm always getting string length as 33. what is wrong with my code."}, {"role": "assistant", "content": "That is because, you have declared your array as typeint\n\n```\nint str1[25]; \n\n^^^-----------Change it to `char`\n```"}]} {"messages": [{"role": "user", "content": "Is there a way to create two structs that make a reference to each other?\nExample:\n\n```\nstruct str1\n{\n struct str1* ptr1;\n struct str2* ptr2;\n}\n\nstruct str2\n{\n struct str1* ptr1;\n struct str2* ptr2;\n}\n```"}, {"role": "assistant", "content": "```\nstruct str2; // put a forward reference to str2 here\n\nstruct str1\n{\n struct str1* s1;\n struct str2* s2;\n};\n\nstruct str2\n{\n struct str1* s1;\n struct str2* s2;\n};\n\nint main()\n{\n struct str1 s1;\n struct str2 s2;\n\n s1.s1 = &s1;\n s1.s2 = &s2;\n s2.s1 = &s1;\n s2.s2 = &s2;\n\n return 0;\n}\n```"}]} {"messages": [{"role": "user", "content": "I want to save the value of different types of variable in a comma separated csv file. \nright now I have something like\n\n```\nprintf(\"[%-2d]|%08x%s[%s][%s][%08x][%08x]\", a,b,c,d,e,f,g);\n```\n\nwhat I want is to write in a text file the values like:\n\n```\na,b,c,d,e,f,g\n```\n\nHere are the constraints.ais an unsigned integer and must be saved just like theprintfformatted string%-2d,\n\nb,f,and,gare integers but i need to save the hexadecimal value of those variables with the same format used inprintf, i.e.%08x.\n\nI am writing a C program."}, {"role": "assistant", "content": "printfhas its cousinfprintfwhich will happily print whatever you want into a file you've opened/created withfopen\n\n```\nfprintf(stream, \"%-2d, %08x, %s, %s, %s, %08x, %08x\\n\", a,b,c,d,e,f,g);\n```"}]} {"messages": [{"role": "user", "content": "This function which I received from a third party contains the following code which does not compile in MS Visual Studio 10. I think there is a casting problem but do not know how to fix this.\n\n```\nvoid dump_ffmpeg_pad16(FILE *stream, uint32_t timestamp, void *data,\n int data_size)\n{\n unsigned int z=0;\n void *end = data + data_size;\n while (data < end) {\n z = *(unsigned short*)data;\n fwrite(((char*)(&z)), 3, 1, stream);\n data += 2;\n }\n}\n```\n\nIt has been instructed in their help to compile as C++ code. Thanks for your help."}, {"role": "assistant", "content": "```\nvoid *end = data + data_size;\n```\n\nShould be:\n\n```\nvoid *end = ((char *) data) + data_size;\n```\n\nAdding to avoid*is a GCC extension."}]} {"messages": [{"role": "user", "content": "In my programm I have several float variables that I need to compare to 0. Those variables are being read in through printf.\n\n```\nfloat a;\nscanf(\"%f\", &a);\nif (a=0)\n{\nprintf(\"a is zero\");\nreturn 0;\n}\n```\n\nBut it doesn't work when I give in a 0 through scanf. \"a is zero\" isn't displayed. It doesn't work with (a=0.0) and doesnt work with (a=0.0f) or (a=0.). The only way I managed to do it is with (0 < a && a < 0.0000000000001)\n\nbut I feel like this is not a very good way to do it.\n\nWhat did I do wrong? Why doesn't it recognize the 0 I input in with scanf as 0?"}, {"role": "assistant", "content": "Just change \"=\" to \"==\". You can write \"if\" statement to following style:\n\n```\nif (CONSTANT == variable)\n```"}]} {"messages": [{"role": "user", "content": "Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 years ago.Improve this question\n\nI want to use C++ for opengl and python for scripting various social api calls. IS there a better option?"}, {"role": "assistant", "content": "Prototype with your OpenGL calls in python - it is much quicker to prototype than C/C++ and then see if it is quick enough - if it is then you are done - if not then find the bottlenecks and consult the documentation on C/C++ plug in to address those issues.\n\nNote that there are python OpenGL bindings availableherewhich already use C/C++ on the OpenGL side so should be as fast as anything you are likely to come up with quickly."}]} {"messages": [{"role": "user", "content": "Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed9 years ago.Improve this question\n\nI want to write a program that calculates if a number is a multiple of some other numbers.\nLets say that i want to check if 25 can be given from a function like 2a+3b+4c=25.Is there any algorithm that can find a b c in order to check if abc are integers?"}, {"role": "assistant", "content": "For generating all possibilities, a Brute force algorithm will suffice:\n\nLoop over all possible values foraand subtract the sum2afrom 25. Nest similar loops forbusing the remainder. If the remainder after subtracting3bis a multiple of 4, then loop over all possible values ofcand outputa,b, andcas a combination."}]} {"messages": [{"role": "user", "content": "I am running across a problem with typedefs.\n\n```\ntypedef char cool_array_t[ARRAY_SIZE];\n\ncool_array_t* out;\n// do stuff with out\ncool_array_t test = *out;\n```\n\nThe error I am getting is the following:\n\nincompatible types when assigning to type ‘cool_array_t’ from type\n ‘char *’\n\nI tried casting out to cool_array_t but it gives the following error:\n\nerror: cast specifies array type"}, {"role": "assistant", "content": "You cannot assign to arrays. You need to usememcpyor a wrappingstruct.\n\n```\nstruct cool_array_t {\n char data[ARRAY_SIZE];\n};\n\nstruct cool_array_t* out;\n// do stuff with out\nstruct cool_array_t test = *out;\n```"}]} {"messages": [{"role": "user", "content": "Say a pointer is pointing at an object at some address.\n\nLater, because there is not enough memory, the OS swaps some pages out of the memory and the object is in one of the page and the pointer is not.\n\nThen, the page that has the object is swapped in later to a different location in memory.\n\nWhat happens to the address stored in the pointer? Does the address get updated to the new address where the object is residing?\n\nOr is there something that I am misunderstanding in how the memory management works?"}, {"role": "assistant", "content": "The address is a an address to virtual memory in the first place. So the address does not need to change – the OS will make sure that the next time you access memory under that address, the address is mapped to the correct physical address."}]} {"messages": [{"role": "user", "content": "I need to implement a 32-bit Fixed-point on a 16-bit system. My compiler seems to be giving me an \"warning: integer overflow in expression\". I'm not sure what I'm missing anything :S . I'll provide a dumbed down version of my code below. Any advice would be appreciate :)\n\n```\n#include \ntypedef int32_t Q22;\n\n#define Q22base 512\n#define Q22_Convert(_a) ((Q22)(_a*Q22base))\n\nint main (){\n // a bunch of code that does stuff goes here\n Q22 variable1=0;\n\n variable1 = Q22_Convert(some_value1) - Q22_Convert(some_value1); \n return 0;\n}\n```"}, {"role": "assistant", "content": "YourQ22baseis 16-bit on a 16-bitintsystem, you need to cast it toQ22so your*expression is done in at least a 32-bit type.\n\n```\n#define Q22_Convert(_a) ((Q22)(_a * (Q22) Q22base))\n```"}]} {"messages": [{"role": "user", "content": "I am studying for a midterm and one of the questions is Which of the following statements will increment a value in the array, and leave the pointer address unchanged? Circle 0 or more.\n\n```\nint array[10];\nint * ptr = array;\n```\n\n1)*ptr++;\n\n2)(*ptr)++;\n\n3)*++ptr;\n\n4)++*ptr;\n\nI have seen 1 and 2 used before and I believe it's just getting the de-referenced values without changing the pointer. But I was surprised to find 3 and 4 is actually valid and I am confused as to how to understand or even read it? Is it the same thing? I believe the answer is that all 4 of them are valid."}, {"role": "assistant", "content": "http://en.cppreference.com/w/cpp/language/operator_precedencewill be helpful to you. Read through it and put the parenthesis in to the examples based on the precedence of the operators and everything will hopefully make some sense.\n\nThe first would become*(ptr++)for instance."}]} {"messages": [{"role": "user", "content": "I need to implement a set of functions providing various set operations such as create set, add element to set, etc. I am new to programming, however, I know how to write a function but my problem with this task is that I need to use pointers and I have no idea how to for example write a function to create a set with pointers. I am not asking for solutions, just a good explanation to get me started! Thanks"}, {"role": "assistant", "content": "Sets can be stored in various data structures such as, but not limited to, a linked list. You then need to abstract away set operations to add, remove, test for membership of elements. I advise you to read data structure related literature and do some related exercises before undertaking this small project."}]} {"messages": [{"role": "user", "content": "Probably obvious, but even my clever \"how to c\" book doesn't really help me here. I just started with C programming, so sorry if the answer eludes me.\n\nI usefopen(\"%s.txt\", \"w+\")in order to save a textfile. However I have no idea how the user can input a string for %s. I tried it with scanf and other variations. But nothing worked yet."}, {"role": "assistant", "content": "```\n#include\n\nchar filename[255];\nFILE *fp;\nscanf(\"%s\",filename);\nstrcat(filename,\".txt\");\nfp=fopen(filename,\"w+\");\n```"}]} {"messages": [{"role": "user", "content": "I am taking a university course in computer architecture so I am new to assembly language. My question is, how do I translate the following code from C to MIPS assembly language without using pseudoinstructions?\n\n```\nB [8] = A [i-j]\n```\n\ni and j are assigned to registers $s3 and $s4 and the base address of A and B are in registers $s6 and $s7. So far I have:\n\n```\nsub $t0, $s3, $s4\nsll $t0, $t0, 2\nlw $t1, $t0($s6) #Is this line allright?\nadd $s5, $t1, $zero\nsw $s5, 32($s7)\n```\n\nI'm not sure about using register $t0 as an offset to address memory in the third line. Thanks in advance."}, {"role": "assistant", "content": "No. Instead calculate the address needed by adding $t0 to $s6.\n\n```\nsub $t0, $s3, $s4\nsll $t0, $t0, 2\nadd $t0, $t0, $s6\nlw $t1, 0($t0)\nsw $t1, 32($s7)\n```"}]} {"messages": [{"role": "user", "content": "my code is\n\n```\n#include \nint main()\n{\n int name;\n scanf(\"%d\",&name);\n printf(\"%d\",name);\n}\n```\n\nWhy when I enter \"Hello\",\"World\",\"Good\", etc it must show 2 ?\nWhy 2 not the other number ?\nIf I want to scanf string and printf ASCII code of it how should i do ?\nthankyou"}, {"role": "assistant", "content": "To print ascii values of an entered string :\n\n```\n#include \n#include \n#include \n\nint main(){\n char array[100]; \n int i=0;\n printf(\"Enter string : \");\n scanf(\"%s\",array); // fixed as suggested in comments\n\n for(i=0;i \n\n#define xprintk(...) while(0); \n\nint main (void)\n{\n if (1)\n xprintk(\"aaa\\n\");\n else\n xprintk(\"bbb\\n\");\n\n return 0;\n}\n```"}, {"role": "assistant", "content": "```\n#define xprintk(...) while(0)\n ^^ Remove semi-colon\n```\n\nSee what happens after pre-processing\n\ngcc -E test.c\n\n```\nint main (void)\n{\n if (1)\n while(0);; //<- Two semi-colon (i.e. Two statements)\n else\n while(0);; //<- Two semi-colon\n\n return 0;\n}\n```"}]} {"messages": [{"role": "user", "content": "This question already has answers here:Turbo C++: Why does printf print expected values, when no variables are passed to it?(5 answers)Closed10 years ago.\n\n```\n#include\n#include\nvoid main()\n{\nint a=10,b=11;\nclrscr();\nprintf(\"%d\");\ngetch();\n}\n```\n\nOutput=11 \nHow the output is 11 even I am not mentioned the variable name in the printf function."}, {"role": "assistant", "content": "The 11 is on the stack because of thebvariable, and yourprintf()function is looking on the stack for a value on the stack because that's where variables get passed.\n\nIf you add ac=47, you'll probably get 47. But this is undefined behavior."}]} {"messages": [{"role": "user", "content": "What is the value of putchar(c) outside loop?\n\n```\nmain()\n{\n int c;\n\n while (c = getchar() != EOF) {\n printf(\"printf c_inloop :%d\\n\",c);\n printf(\"Putchar c_inside: \");\n putchar(c);\n printf(\"\\n\\n\");\n }\n\n putchar(c);\n printf(\"printf c_outloop %d\",c); /*outside loop*/\n\n}\n```\n\nWhen I run the program, say \"th\"(wtq) and press enter in cmd(Windows):\n\n```\nth\nprintf c_inloop :1\nPutchar c_inside:(gives me a smileyface emoticon)\n\nprintf c_inloop :1\nPutchar c_inside:(gives me a smileyface emoticon)\n\nprintf c_inloop :1\nPutchar c_inside:(gives me a smileyface emoticon)\n\n^Z (Ctrl + Z)\n printf c_outloop 0\n```\n\nNote the space beforeprintf c_outloop 0. Is the value ofputchar(c)Space?"}, {"role": "assistant", "content": "When you exit the loop, the value ofcisEOF, which isn't a valid character value (that's why it's used to indicate end of file). It makes no sense to pass it toputchar."}]} {"messages": [{"role": "user", "content": "I am trying to use pinvoke to marshal a C structure to C#. While I am able to marshal an intptr I cannot find the syntax to marshal a double pointer. Both the int pointer and double pointer are used on the C side to alloc an array of ints or doubles.\n\nHere is the C struct:\n\n```\nstruct xyz\n{\n int *np; // an int pointer works fine\n double *foo;\n};\n```\n\nAnd here is the c# class:\n\n```\n[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]\npublic class xyz\n{\n Intptr np; // works fine\n // double *foo ?? \n }\n```\n\nI am unable to find any instructions on how to marc"}, {"role": "assistant", "content": "Check outthis description for what an IntPtr is. Have you tried using:\n\n```\n[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]\npublic class xyz\n{\n IntPtr np;\n IntPtr foo;\n}\n```"}]} {"messages": [{"role": "user", "content": "I am quite new to C programming, but was wondering if there is a function that allows you to copy a char array into another char array starting at a particular index, other than using a for loop?\n\nFor example, I want to copy the entire contents ofsourceintobufferusing, say, element 4 ofbufferas the starting point.sourcewill be binary data. Canmemcpydo this?"}, {"role": "assistant", "content": "Yes,memcpyis designed to copy data. The source and destination can be arbitrary locations in memory (as long as it is memory you are allowed to read/write).\n\nIn answer to your specific question:\n\n```\nmemcpy(buffer+4, source, length);\n```\n\nIf the source and target areas may overlap, usememmoveinstead.\n\n```\nmemmove(buffer+4, source, length);\n```"}]} {"messages": [{"role": "user", "content": "When I run the following code inClanguage, my compiler shows the error \"xxx has stopped working\".\n\nHowever, when I take array sizes as 1000 instead of 100000 it runs fine. What is the problem and how can I fix it? If there is some memory problem then how can I take input of 100000 numbers in these arrays without exceeding it?\nCode I tried :\n\n```\nint main()\n{\n int a[100000],l[100000],r[100000],ans[100000],x[100000],y[100000];\n /*\n some code\n */\n return 0;\n}\n```"}, {"role": "assistant", "content": "Declarea,l,r,ans,xandyas global variables so that they will be allocated in the heap instead of the stack.\n\n```\nint a[100000], l[100000], r[100000], ans[100000], x[100000], y[100000];\nint main()\n{\n```"}]} {"messages": [{"role": "user", "content": "I am using a library and there are some functions before which I have to addAPI_EXPORTEDas given in documentation.\n\nLike:\n\n```\nAPI_EXPORTED int fpi_img_compare_print_data(struct fp_print_data\n*enrolled_print, struct fp_print_data *new_print)\n```\n\nI dont know what is the use of this keyword."}, {"role": "assistant", "content": "Your library seems to be libfprint in whichAPI_EXPORTEDis a macro defined as:\n\n```\n#define API_EXPORTED __attribute__((visibility(\"default\")))\n```\n\nwhich would enable the API (e.g.fpi_img_compare_print_data) to be made public."}]} {"messages": [{"role": "user", "content": "I have to write a program in C (on a Unix-like system) and this is my problem:\n\nI have a file (FILE1) and I want to create another file (FILE2) which has the same permissions of FILE1. Then I have to create another file (FILE3) which has the same permissions of FILE1 but only for the owner.\n\nI would use chmod() to change permissions but I don't understand how to obtain the permissions of FILE1.\n\nCan you please help me?"}, {"role": "assistant", "content": "Thestat()andfstat()functions retrieve astruct stat, which includes a memberst_modeindicating the file mode, where the permissions are stored.\n\nYou can pass this value tochmod()orfchmod()after masking out the non-file-permission bits:\n\n```\nstruct stat st;\n\nif (stat(file1, &st))\n{\n perror(\"stat\");\n} \nelse\n{\n if (chmod(file2, st.st_mode & 07777))\n {\n perror(\"chmod\");\n }\n}\n```"}]} {"messages": [{"role": "user", "content": "I have stumbled upon a persistent problem, that doesn't seem to have a rational explanation. The problem seems to lie inside a for loop that goesfor (i = size - 1; i >= 0; i--) {etc.}wheresizeis the size of a file stored in a memory buffer andiis an unsigned integer. Instead of stopping wheni == 0, it wraps around - thus resulting ini = 4294967295and causing a segmentation fault. Changing the conditional toi > 0solves the problem.\n\nHowever, isn't this kind of peculiar? I must be missing some crucial part of how the for loop operates in C. Doesn't it follow this scheme: initialize, check conditional, increment/decrement, check conditional and so on?\n\nAny help is appreciated!"}, {"role": "assistant", "content": "An unsigned integer is always>= 0.\n\n```\nfor (i = size - 1; i >= 0; i--) {etc.}\n```\n\nis an infinite loop ifiis anunsigned int."}]} {"messages": [{"role": "user", "content": "In a gcc makefile, you can use the -D flag to specify a define in the compiled program. For example, instead of putting #define SOMETHING, you can specify -DSOMETHING in the makefile. What is the equivalent of this in SCons?"}, {"role": "assistant", "content": "I believe you want theCPPDEFINESconstruction variable. Seethe SCons documentation pagefor some more details, underCPPDEFINES."}]} {"messages": [{"role": "user", "content": "I have a.c b.cpp files.\n\n```\n/****** a.c ******/\nfun1(...)\n{\n ..........\n\n fun2(...); /* function present in b.cpp */\n\n ..........\n}\n\n/******* b.cpp *******/\nextern \"C\" int fun2(...);\nint fun2(...)\n{\n ..........\n\n}\n```\n\nI have compiled the code as follows:\n\n```\na.o:a.c b.o\n gcc -c -o a.o a.c b.o\n\nb.o:b.cpp\n g++ -c -o b.o b.cpp\n```\n\nBut I'm getting error as undefined reference to \"fun2()\".\nIs this the correct way of compilation or do I need to change anything.?"}, {"role": "assistant", "content": "You need to add a prototype of the function in a.c."}]} {"messages": [{"role": "user", "content": "Running Debian 7.\nIs it possible that when a program opens a file we can give it output from a currently running file.\n\nExample:\nWe have a C/Java program running. This is (attached)? to file /etc/motd as an example.\nWhen ssh or any other program goes to read /etc/motd the C/Java program provides output instead. So instead of the file being read from disk it is being read from the C/Java program."}, {"role": "assistant", "content": "You would create /etc/motd as a special device file, not as a regular text or binary file. Then, you would attach your program to the device file with a pipe and have it waiting for input. Once input was received the program would then process the data and do the commands required. Items to refer to are: mknod and | (pipe)."}]} {"messages": [{"role": "user", "content": "I want to implement a debug code for my project which is in c. In my project i am having so many functions and function calls. I want to write code in such a way that when a function is called, It should print the function name and its caller name. \nCan anybody give me a clue for doing this?"}, {"role": "assistant", "content": "Thelibunwindlibrary may be able to help you there. But it's going to be fairly slow and may give very unpredictable results in case of optimised binaries.\n\nDo you actually need to implement this in the app? Isn't running the application undergdbwith some breakpoints enough?\n\nAnother way to generate the traces without a big dependency is just to wrap some function calls in a macro like this (very trivial solution, it could do more).\n\n```\n#define TRACE(s) { printf(\"Doing %s\\n\", #s); s; }\n```"}]} {"messages": [{"role": "user", "content": "I have two functions:\n\n```\nvoid a(int * p);\nint b();\n```\n\nIs it possible to pass the address of the return value of functionbto functionasomething like this:a(&b())?"}, {"role": "assistant", "content": "A compound literal seems to do the trick (requires a C99 compiler):\n\n```\nint a()\n{\n return 5;\n}\n\nvoid b(int *a)\n{\n // do something with a\n printf(\"%d\\n\", *a);\n}\n\nint main(void)\n{\n b(&(int){ a() });\n}\n```\n\nOutput is5."}]} {"messages": [{"role": "user", "content": "I have:\n\n```\n#define MAX_STR_LEN 100\n```\n\nand I want to put intoscanfpattern so I can control the string length:\n\n```\nscanf(\"%100[^\\n]s\",sometext)\n```\n\nI tried:\n\n```\nscanf(\"%MAX_STR_LEN[^\\n]s\",sometext)\nscanf(\"%\"MAX_STR_LEN\"[^\\n]s\",sometext)\nscanf(\"%\",MAX_STR_LEN,\"[^\\n]s\",sometext)\n```\n\nAnd it didn't work. I just want to avoid buffer overflow since \"sometext\" is allocated withmalloc(MAX_STR_LEN)...\n\nAny ideas?"}, {"role": "assistant", "content": "I wasn't happy with any of these solutions, so I researched further, and discovered GNU GCC macrostringification\n\nwhich can be used as:\n\n```\n#define XSTR(A) STR(A)\n#define STR(A) #A\n#define MAX_STR_LEN 100\nscanf(\"%\"XSTR(MAX_STR_LEN)\"[^\\n]s\", sometext)\n```\n\nMaybe VS2010 offers something similar?"}]} {"messages": [{"role": "user", "content": "Is there a more efficient way to get the sum of absolute differences of twomemory blocksarrays ofdoublein C/C++ than to perform a loop on the array elements? So, what I wonder is if there is a function for this purpose similar tomemset,memcpy,memcmpetc.\n\nHow do you define the difference?\n\nThe memory blocks containdoublevalues, and what I need is the sum of the absolute numerical differences between the values in the corresponding indexes of thememory blocksarrays."}, {"role": "assistant", "content": "Yes, there isSIMD. If you use GCC you can try adding things like-msse2 -O3and see if it automatically generates SIMD instructions for you. If it does, or if you choose to use a library to do explicit SIMD, you can process four floats per instruction. To improve your chances, try to make your inner loop nice and simple so the optimizer can deal with it easily."}]} {"messages": [{"role": "user", "content": "I am trying to link the my C code, and I got the following error message:\n\n```\nError 126: Inconsistent structure definition 'unnamed'\n```\n\nthere is no line number indicated which line has problems, and I do not have any structure of \"unnamed\", so I can not post the suspected code to here, have anyone experience this and how to fix it?"}, {"role": "assistant", "content": "Error 126: The named structure (or union or enum) was inconsistently defined\n across modules. The inconsistency was recognized while processing a\n lint object module. Line number information was not available with\n this message. Alter the structures so that the member information is\n consistent.\n\nMaybe a tagless struct bearing a tagless struct"}]} {"messages": [{"role": "user", "content": "Is it possible to configure clang to read the compiler flags from a file. Is there any flag like:\n\n```\nclang++ test.cpp -flags=flags-file\n```\n\nSuch thatclangreads the compiler flags fromflags-file."}, {"role": "assistant", "content": "Apparently there is support for reading commands from a file in clang as well as in gcc. The usage is something like:\n\n```\nclang++ test.cpp @file\n```\n\nThe compiler will read the command line flags fromfile.\n\nI could find a link for gcc.https://developer.apple.com/library/mac/documentation/darwin/reference/manpages/man1/gcc.1.html"}]} {"messages": [{"role": "user", "content": "What's wrong in my function 'front'?\nI want to pass the pointer to an specific line in my array to read/edit it.\n\n```\nstruct queue\n{ \n char itens[LN][CL];\n int front,rear;\n}; \n\nchar *front(struct queue * pq)\n{\n return pq->itens[pq->front+1][0];\n}\n```"}, {"role": "assistant", "content": "You're currently returning a singlechar, not a pointer to a row. Take off the[0]:\n\n```\nchar *front(struct queue *pq)\n{\n return pq->itens[pq->front+1];\n}\n```"}]} {"messages": [{"role": "user", "content": "Is there a way to generate random numbers in c language independent of time.\nThe idea is that I want to generate an array of random numbers at a time,but since rand() method depends on time,all the values in the array are generated similarly."}, {"role": "assistant", "content": "rand()doesn't depend on time. People typically seed their pseudo-random number generatorusingthe current time (through thesrand()function), but they don't have to. You can just pass whatever number you want tosrand().\n\nIf your random numbers aren't of a high enough quality for your purposes (libc'srandis notorious for its inadequacy), you should look at other sources of randomness. On most operating systems, you can get high-quality random data just by reading from/dev/random(or/dev/urandom), and the Windows API providesCryptGenRandom. There are also a lot of cross-platform libraries that provide high-quality PRNGS;OpenSSL is one of them."}]} {"messages": [{"role": "user", "content": "I have a small simple code to compare 2 floating point numbers:\n\nI tried using fabs but it gives wrong weird result. What is the mistake, and what is the correct form?\n\n```\n#include \n#include \n#include \n\nvoid compareFloat(double a1, double a2)\n{\n if(fabs(a1 - a2) < DBL_EPSILON)\n printf(\"a1 is smaller\\n\");\n else\n printf(\"a1 is larger\\n\");\n}\n\nint main()\n{\n float a1=0.0000004f, a2=0.0005f;\n compareFloat(a1, a2);\n}\n```\n\nWhat is the mistake in this code? It always printsa1 is smallereven if i set a1=0.004f and a2=0.0005f"}, {"role": "assistant", "content": "The prototype for abs is an integer!\n\n```\nint abs (int number);\n```\n\nYou want fabs for floating point\n\n```\ndouble fabs (double number);\n```"}]} {"messages": [{"role": "user", "content": "What does a number argument inprintfwithout quotes do?\n\ne.g.printf( 3 + \"goodbye\");results in output dbye. Why do I get this output?"}, {"role": "assistant", "content": "3 + \"goodbye\"is equivalent to&\"goodbye\"[3]- in other words it's just a pointer to the fourth element of \"goodbye\" and so your example will print \"dbye\"."}]} {"messages": [{"role": "user", "content": "I know that a NULL pointer is(void*)0.But what happens when we use statements like the following:\n\n```\nif(ptr==NULL)\n```\n\nwhereptrcan be achar,floatorintpointer?IsNULLguaranteed to be implicitly converted to the type on the left just as, for example, in C, the type returned bymalloc()isvoid*but is implicitly converted to the type of the lvalue?"}, {"role": "assistant", "content": "Is NULL guaranteed to be implicitly converted to the type on the left? [...]\n\nYes.\n\nAccording to section 6.3.2.3.4 of theISO/IEC 9899:2011 C programming language standard:\n\nConversion of a null pointer to another pointer type yields a null\n pointer of that type. Any two null pointers shall compare equal.\n\nand to section 6.3.2.3.1\n\nA pointer to void may be converted to or from a pointer to any object\n type.A pointer to any object type may be converted to a pointer to\n void and back again; the result shall compare equal to the original\n pointer."}]} {"messages": [{"role": "user", "content": "This question already has answers here:Why is memcmp so much faster than a for loop check?(3 answers)Closed8 years ago.\n\nWhich implementation is better and why?\n\nElement by Element comparison using a for loop or memcmp() implementation\n\n```\nint a[] = {1,2,3};\nint b[] = {1,3,5};\n\nmemcmp(a, b, sizeof(int)*n)\n```\n\nOR\n\n```\nfor (i = 0; i < n ; i++)\n {\n if (a[i] == b[i])\n {\n /* some Code */\n }\n }\n```"}, {"role": "assistant", "content": "memcmpis faster: it is generally heavily optimized by the compiler to use special instructions on the cpu, loop unrolling, and other \"advanced\" techniques that the generated code for the simple loop (generally) won't use. However,memcmpcan only compare byte values; it is fine in case of an array of integers, but it (probably) wouldn't work for an array of objects."}]} {"messages": [{"role": "user", "content": "I am working on a program and learning about parent/child processes. \nCurrently my childprocess does\n\n```\nexit(variable);\n```\n\nin my main() I have:\n\n```\nsignal(SIGCHLD, chldHandler);\n```\n\noutside my main() I have:\n\n```\nvoid chldHandler(int sig) {\n\n}\n```\n\nHow do I access the variable from my chldHandler?"}, {"role": "assistant", "content": "You usewait()inside your signal handler, passing in a non-NULL pointer to get the status.\n\n```\nint status;\nwait(&status);\n```\n\nTo decode the status, check to see that it exited normally, then use theWEXITSTATUS()macro:\n\n```\nif (WIFEXITED(status)) {\n int variable = WEXITSTATUS(status);\n /*...*/\n}\n```"}]} {"messages": [{"role": "user", "content": "How do I do this in constant time (I do not want to brute for iterate from a to b)?\n\n```\n// return number of multiples of c in [a,b]\nlong count_multiples(int a, int b, int c) {\n assert(b >= a && c != 0);\n // todo\n return -1;\n}\n```\n\nThis question looks deceptively simple but is harder than it looks because it has some corner cases e.g. must handle all cases (a,bcan be negative/zero andccan be negative too andamay equalbmay equalc). The result may not fit in 32-bit for one case (a = 2^31,b = 2^31-1,c = 1 or -1)"}, {"role": "assistant", "content": "```\nlong count_multiples(int a, int b, int c) {\n if (b < a) return 0;\n if (c < 0) c = -c;\n long al = a, bl = b, cl = c;\n if (c == 1) return bl - al + 1;\n return ((bl + (b < 0 ? 1 : 0)) / cl) -\n ((al - (a > 0 ? 1 : 0)) / cl) +\n ((a <= 0 && b >= 0) ? 1 : 0);\n}\n```"}]} {"messages": [{"role": "user", "content": "ARCforbidsObjective-Cobjects instructs orunions.\n\nUnless you add__unsafe_unretainedwhich means its not managed.\n\nI was wonder what people are using in place ofstructs now if anything?\n\nOr are you retaining everything manually?"}, {"role": "assistant", "content": "It's very simple - if you want to add an object inside a struct, you are doing it wrong. Whenever you need a struct to hold an obj-c object, convert the struct into an obj-c object."}]} {"messages": [{"role": "user", "content": "could anybody explain me how to read DWORD ,WORD ,BYTE in C from specific address in memory?for example, base address that is returned using MapViewOfFile() function,how can I read a consecutive BYTE,WORD, or DWORD using C ?Thanks."}, {"role": "assistant", "content": "MapViewOfFile()returnsLPVOIDwhich is a typedef ofvoid*. You'll need a cast.\n\nThe easiest thing to do would be to read a byte at a time. You don't specify if there's any kind of performance requirement here (nor do you specify your platform, arch, etc), so I'll assume a \"byte at a time\" is ok.\n\nNote: WORD is defined as short and should be 16-bits in Win32. DWORD is an int and should be 32-bits in Win32.\n\n```\nLPVOID pvAddr= MapViewOfFile(...);\n\nBYTE* pBytes= (BYTE*)pvAddr;\n\nBYTE firstByte= pBytes[0]; /* copy first byte */\n\nWORD w;\nmemcpy(&w, pBytes+1, 2); /* copy the next two bytes */\n\nDWORD dw;\nmemcpy(&dw, pBytes+3, 4); /* copy the next 4 bytes */\n```\n\nHope that helps."}]} {"messages": [{"role": "user", "content": "I have shared library file (libmylib.so), but have no header file (mylib.h) for it.\n\nDo you know some ways/tools to generate this header file from shared library file?"}, {"role": "assistant", "content": "This is impossible in general, since the .so file does not contain enough information about the parameter lists - especially if non-standard types (structs, e.g.) are being used, since type information is not part of the .so file.\n\nEven if only standard types are used, the argument list is not part of the ELF symbol table (seehttp://refspecs.linuxbase.org/elf/elf.pdf1-15ff.).\n\nHowever, if the library is not stripped (= it contains debugging information), the DWARF-part does contain information about parameter lists, seeHow to extract function prototypes from an elf file?for details."}]} {"messages": [{"role": "user", "content": "I referred to two reliable sources for the information and both seems to have different definitions of the same thing:\n\nhttp://www.cplusplus.com/reference/clibr%E2%80%A6\n\nhttp://www.ocf.berkeley.edu/~pad/tigcc/doc/html/stdio_fputchar.html\n\nThe first source saysputchar()is a function, as isgetchar(), but in the second link it saysputchar()is a macro. My book saysgetchar()is a macro. Which is correct?"}, {"role": "assistant", "content": "getcharandputcharare functions, but may additionally be defined as macros. Whether they are or not depends on the implementation. The C standard says regarding standard library functions (C99, 7.1.4@1):\n\nAny function declared in a header may be additionally implemented as a function-like macro defined in the header."}]} {"messages": [{"role": "user", "content": "I have been reading about accessing Memory Mapped Registers of peripheral devices and it seems you can do multiple ways. For example:\n\nMethod 1:\n\n```\n#define MyReg 0x30610000\n\nvolatile int *ptrMyReg;\nptrMyReg = (volatile int *) MyReg;\n*ptrMyReg = 0x7FFFFFFF; /* Turn ON all bits */\n```\n\nMethod 2:\n\n```\n#define MyReg 0x30610000\n\nvolatile unsigned char *ptrMyReg;\nptrMyReg = (volatile unsigned char *) MyReg;\n*ptrMyReg = 0x7FFFFFFF; /* Turn ON all bits */\n```\n\nQuestion: Is there any specific reason as to why one would choose one over another?\n\nAssume: Size of int on architecture is 4 bytes."}, {"role": "assistant", "content": "*ptrMyReg = 0x7FFFFFFF;\n\nIn the second case,*ptrMyRegis of typeunsigned charso0x7FFFFFFFwill be converted tounsigned char(i.e., value after conversion will be0xFF) before assignment and only one byte will be written. I don't think this what you want if you originally intended to write 4 bytes."}]} {"messages": [{"role": "user", "content": "I want to have an array ofk2-element arrays of ints. My code:\n\n```\nint **pipe_fd_ptr;\npipe_fd_ptr = malloc(k*sizeof(int*));\nfor(i = 0; i < k; i++)\n{\n pipe_fd_ptr = malloc(2*sizeof(int));\n}\n\n// this is just for testing\nfor(i = 0; i\n\nchar A[];\n\nint main()\n{\n printf(\"%c\\n\",A[1]);\n return 0;\n\n}\n```\n\nI can access any element using index . It never gives error . What is the index of max element i can access for 32 bit machine?"}, {"role": "assistant", "content": "It has size 1. Accesses beyond index 0 (including your code, which accessesA[1]) have undefined behavior.\n\nThis is 6.9.2 in the C99 standard.char A[];is a \"tentative definition\", which roughly speaking means that if the same translation unit contains a proper definition then it's just a declaration ofAas an array of char of unknown size. If there's no proper definition then the object is defined anyway as if there were a definition at the end of the translation unit, with a default initializer."}]} {"messages": [{"role": "user", "content": "I am searching a nice way to create a \"no action\" timing (CPU useless operation for timing).\n\nTo explain my issue here is the code that I want to change to a macro :\n\n```\nint main (void)\n{\n int i=0; \n\n printf(\"Start\\r\\n\");\n for(i=0;i<1000;i++); //LINE TO CHANGE TO A MACRO\n printf(\"Delayed trace\\r\\n\");\n return 0;\n}\n```\n\nDo you have any idea ?\n\nThanks by advance."}, {"role": "assistant", "content": "General way for defining such a macro would be:\n\n```\n#define DELAY(amount) \\\ndo { \\\n /* method of delay */ \\\n} while (0)\n```\n\nIn your case:\n\n```\n#define DELAY(amount) \\\ndo { \\\n int i; \\\n for (i = 0; i < amount; ++i); \\\n} while (0)\n```"}]} {"messages": [{"role": "user", "content": "What is the difference between the devices \"default\" vs \"hw:0,0\" ? Are they the same ?\n\n(Background: I faced some trouble to play audio when I configured hw:0,0 , but \"default\" worked. Could not find what caused this)\n\nThanks"}, {"role": "assistant", "content": "Thedefaultdevice uses theplugplugin to automatically convert sample formats and rates, and typically alsa uses thedmixplugin to allow multiple applications to access the device at the same time."}]} {"messages": [{"role": "user", "content": "I want to split the string \"abc 123 456\" into the string (\"abc\") and 2 numbers (123,456). What is the format should I put in the below code?\n\n```\nchar *s;\nint a,b;\nsscanf(\"acb 123 456\", format, s, &a, &b);\n```"}, {"role": "assistant", "content": "You want:\n\n```\n\"%s%d%d\"\n```\n\nBut you also need to allocate buffer space for the string you extract:\n\n```\nchar s[100];\nint a,b;\nsscanf(\"acb 123 456\", \"%s%d%d\", s, &a, &b);\n```"}]} {"messages": [{"role": "user", "content": "I want to generate shapes like the one following (image file e.g. PNG):\n\nI'm looking for a c / c++ library which will allow me to realize the following algorithm:\n\nThe basic algorithm would be:\n\nMake circlePartition Circle randomlyFill in one segementTwirl whole shape (see link)Save Image as PNG\n\nLink: Twirl filter in Photoshop\n\nI will accept the first answer which lists and linksone library or morewhich is will enable me to implement the above algorithm with ease. The library should be light weight if possible."}, {"role": "assistant", "content": "The 'easiest' solution I can think of is to use theGraphicsMagicklibrary - specifically, theMagick++API. With aMagick::Image, you can useDrawableobjects, flood-fills, and even aImage::swirlmethod. Saving as a PNG can be as simple as a call toImage::write(\"filename.png\")"}]} {"messages": [{"role": "user", "content": "I'm writing finite-difference method program using C. The stiffness matrix is symmetrical and band. For its storage I'd like to use Sparse Diagonal Storage format.\n\nCould someone tell please, what solvers can use diagonal storage format? Intel MKL's Paradiso uses only CRS-format, SparseLib doesn't have, Spooles seems also =(\n\nThank you."}, {"role": "assistant", "content": "The sparse libraries concentrate on general purpose sparse storage. For banded matrices you can use any of the standard linear algebra libraries, for example LAPACK."}]} {"messages": [{"role": "user", "content": "I have a application in C programming which uses jansson library(json library written in C). I'm trying to view value of json_t object in gdb but it just prints\n\n```\n(gdb) p jmsg\n$20 = (json_t *) 0x69c350\n(gdb) p *jmsg\n$21 = {type = JSON_OBJECT, refcount = 1}\n```\n\nHow is it possible to view the value of json_t in gdb.?"}, {"role": "assistant", "content": "When in GDB, you can make function calls directly. Jansson library has a json_dumps(json_t *, int flags) API that returns a char* string of the json_t object.\n\nSo while in GDB, just simply do:\n\n```\n(gdb) call json_dumps(obj, 0)\n```\n\nGDB will then print the string output of your json object."}]} {"messages": [{"role": "user", "content": "I have looked all over, and was shocked to be unable to find anything on the topic.\n\nI just want to be able to capture events from a simple mouse scrollwheel."}, {"role": "assistant", "content": "Yep, this is incredibly confusing. That's because X11 decided to assign mouse scroll wheel events as mouse button 4 and 5. Receiving scrollwheel events is the same as receiving mouse button press events (ButtonPress events according to /usr/include/X11/X.h). Note also that the header file defines Button1..Button5. Buttons 4 and 5 correspond to up or down-- maybe not that order, you'll have to determine this empirically. The header file never mentions scrollwheel events.\n\nThankfully, higher level APIs (like GDK) explicitly provide scrollwheel support by name."}]} {"messages": [{"role": "user", "content": "As I'm traversing through a linked list it seg faults. I can't figure out why it's doing so. My assignment is to RECURSIVELY (all functions) insert integers in order, make a function to check for an integer, print list, print list backwards, delete a node, and delete an entire list. I am on the last part and have been stuck for some time now. Thanks alot.\n\n```\nvoid deleteList(node* head)\n{\n node* temp;\n\n if(head == NULL)\n printf(\"List is empty\\n\");\n\n else\n {\n temp = head->next;\n free(head);\n }\n\n deleteList(head->next);\n}\n```"}, {"role": "assistant", "content": "You are first freeing the memory used by head and then passing a member of head as argument to \"deleteList\".\n\nI think it should be first deleteList and then free:\n\n```\nif (head)\n{\n deleteList(head->next);\n free(head);\n}\n```"}]} {"messages": [{"role": "user", "content": "I want to get data with Objective C from my meteor project but it returns always this:\n\n```\n...\n \n \n \n\n```\n\nWhy between body tags is empty? And how do I get meteor datas from anywhere (curl, php, Objective C, iOS etc?"}, {"role": "assistant", "content": "Meteor renders the output on the browser. In essence it does this:\n\nLoad a html file that tells the browser how to create the pageUsing javascript the browser will create the pageFetch collections from server and fill the templates up with this\n\nIf you want to fetch data from the collections use an Objective C ddp client :https://github.com/alansikora/objective-c_ddp-client.\n\nYou might need to modify the code a bit these repos are slightly outdated, the details of the pre1 ddp protocol here:https://github.com/meteor/meteor/blob/master/packages/livedata/DDP.md"}]} {"messages": [{"role": "user", "content": "I have a simple question.\nThe code is really short so I just post it here\n\n```\n#include \nint main(int argc, const char * argv[])\n{\n\n long int p;\n\n printf(\"FYI: address of first local varaible of main() on the function stack:%p\\n\",&p);\n printf(\"Enter start address of dump:\");\n scanf(\"%lx\",&p);\n\n char * q;\n q = (char*)p;\n\n printf(\"%x\\n\",*q);\n\n return 0;\n}\n```\n\nThe result of last printf, for example is ffffffc8. What if I only want to keep the last two: c8. How can I do that? I tried:printf(\"%2x\",*q);andprintf(\"%x\",*q % 256);But neither works. Can some one help? Thanks!"}, {"role": "assistant", "content": "To print the least-significant byte of*qin hex you could use:\n\n```\nprintf(\"%02x\", *q & 0xFF);\n```\n\nThis of course assumes thatqcan be dereferenced."}]} {"messages": [{"role": "user", "content": "I have a nanosleep function in while loop. This is an example I found in book \"Linux System Programming: Talking Directly to the Kernel and C Library\"\n\n```\nwhile(nanosleep(a, b) && errno==EINTR){\n struct timespec *tmp =a;\n a=b;\n b=tmp;\n }\n```\n\nWorks perfect but I am not sure how can I check for other errors than EINTR so that I can print error on the screen and exit the program. Any ideas?"}, {"role": "assistant", "content": "You can simply store the return value in the loop condition:\n\n```\nint ret;\nwhile((ret = nanosleep(a, b)) && errno==EINTR){\n struct timespec *tmp =a;\n a=b;\n b=tmp;\n}\nif (ret) {\n perror(\"nanosleep\");\n exit(1);\n}\n```"}]} {"messages": [{"role": "user", "content": "This question already has answers here:What is the difference between char s[] and char *s?(14 answers)Closed10 years ago.\n\nIs there a difference between:\n\n```\nchar string = \"name\";\nconst char* point = string;\n```\n\nvs\n\n```\nconst char string[] = \"name\";\n```\n\nWill you please explain the difference too?"}, {"role": "assistant", "content": "Yes.\n\nThe first simply points to a read only section of memory, the declaration really should be:\n\n```\nconst char* string = \"name\";\n```\n\nThe second creates an array long enough to hold the string\"name\"(so, four characters plus one for the null terminator) and copies the string inside the allocated space."}]} {"messages": [{"role": "user", "content": "I heard of FlasCC which is a C/C++ compiler targets AVM2. And also I heard it is based on an older version of GCC. (4.2??)\n\nWhat kind/versions of C and C++ standards are supported on FlasCC?"}, {"role": "assistant", "content": "As perhttp://www.adobe.com/devnet-docs/flascc/docs/Reference.htmlit use standard GCC 4.2http://gcc.gnu.org/onlinedocs/gcc-4.2.1/gcc/, which should answer your query!\n\nYou can look at \"Introduction\" section of above GCC link to know what is supported in this compiler."}]} {"messages": [{"role": "user", "content": "Given the following snippet of code:\n\n```\n#include \n#include \n#define MAX_SIZE 15\n\ntypedef struct{\n int touchdowns;\n int interceptions;\n int tackles[MAX_SIZE + 1]; //this is the line in question\n}stats;\n```\n\nThe question posed to me was, \"Why does this line [denoted above] add 1 to the possible number of tackles?\"\n\n----NOT why would one want too, but how/why does it work. Why is it valid code in otherwords, not necessarily valid logic. -Clarification\n\nI'm unsure of how to answer this question in detail. Any help would be appreciated."}, {"role": "assistant", "content": "As Armin pointed out, the tokenMAX_SIZEis replaced by the preprocessor. But for clarification, that's not why it works/compiles in the end. The actual requirement for this to compile is, that the array size is aconstant integral expression, which applies to the code in question."}]} {"messages": [{"role": "user", "content": "I'm working on a compression algorithm wherein we have to write code in C. The program takes a file and removes the most significant bit in every character and stores the compressed text in another file. I wrote a function called compress as shown below. I'm getting a seg fault while freeing out_buf. Any help will be a great pleasure."}, {"role": "assistant", "content": "You close out_fd twice, so of course the second time it is an invalid file descriptor. But more than that, you need to review your use of sizeof() which is NOT the same as finding the buffer size of a dynamically-allocated buffer (sizeof returns the size of the pointer, not the buffer). You don't show the calling code, but using strcat() on a buffer passed-in is always worth a look too (is the buffer passed by the caller large enough for the result?).\n\nAnyway, that should be enough to get you going again..."}]} {"messages": [{"role": "user", "content": "This question already has answers here:Developing C wrapper API for Object-Oriented C++ code(6 answers)Closed10 years ago.\n\nI'm currently developing a SDK for our product in C++. However, some of our customers have a code base written in C that will need to interface with our SDK. I need to provide C Interfaces and am looking for some references on how best to approach this.\n\nI'm using the GNU compilers (version 4.6.3).\n\nI am aware of the extern \"C\" {} construct and have used it sparingly, but I'm not really an expert with this."}, {"role": "assistant", "content": "Here are my suggestions:\n\nProvide some C language interfaces or functions that use static C++\nobjects to invoke functionality.Add static functions to your classes for use with the C language.Change your design so that there are free standing functions that\naccept structures and classes.Also, don't overload free standing functions."}]} {"messages": [{"role": "user", "content": "Linux C program:\n\nWhat function call can check if running in X Window?\n\nIf not in X Window, then printf."}, {"role": "assistant", "content": "Do you mean something like this:\n\n```\n#include \n\n // ...\n\n char *display_name = NULL;\n\n /* connect to X server */\n if ( (display=XOpenDisplay(display_name)) == NULL )\n {\n //printf or whatever\n }\n```"}]} {"messages": [{"role": "user", "content": "Is there an easier way of writing:\n\n```\nrver_t *buf = malloc(sizeof(rver_t));\nrver_t tmp = (rver_t) {.op=OP_RVER, .protocol_version=1};\nmemcpy(buf, tmp, sizeof(rver_t));\n```\n\nto initialise a malloc'd buffer with a struct?\n\nNote: typedef happens in a header:\n\n```\n#define OP_RVER 1\ntypedef struct rver_s {\n uint32_t op;\n uint32_t protocol_version;\n} rver_t;\n```"}, {"role": "assistant", "content": "You could type:\n\n```\nbuf -> op = OP_EVER;\nbuf -> protocol_version = 1;\n```"}]} {"messages": [{"role": "user", "content": "It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.\n\nI want to write accode such that the child sends two matrix to the parent using pipes, the parent will then do the matrix multiplication and send the resulting matrix back to the child.\nI know how to write this program using two pipes, but i want to know how to write this program using a single pipe.\n\nCan anyone please provide theccode for the same?"}, {"role": "assistant", "content": "Pipes are not bi-directional.\n\nTry sockets. Or use two pipes."}]} {"messages": [{"role": "user", "content": "I have this equation its output using a sci calc is : 0.017... but when i run it in c its output is :0.84..\n\nThe input is 1\n\nEquation is: sin(x) - x^4 + 1\n\n```\nfloat sinp(float p1)\n{\n float fop;\n float ppowers;\n printf(\"%f\",p1);\n ppowers = pow(p1,4);\n fop = sin(p1)-ppowers+1;\n return (fop);\n}\n```\n\nis there a reason behind this like would it be because of rad or in degree?\n\nI havent really used the sin or any math function of C that much so I don't really get whats wrong here. Google gave me .84 as an aswer but my calc gives me .017 which is really confusing since I need to get the same output with my calc.\n\nThank you all :)"}, {"role": "assistant", "content": "In mathemtics and in all computer languages trigonometric functions work in radians. If you want to work in degrees you should make the conversion (or define your own sin_degrees function) like:\n\n```\ndouble sin_degrees(double degrees) {\n return sin(degrees * (M_PI/180.0);\n}\n```"}]} {"messages": [{"role": "user", "content": "This question already has answers here:What is the difference between char s[] and char *s?(14 answers)Closed10 years ago.\n\nI need to swap two characters by pointers but when I run this code,the program crashes.\n\n```\nint main(){\n char *s1 = \"string1\";\n swap(st,(st+1));\n\n /* BUT THIS CODE WORKS - Whats the problem?\n * char s1[] = \"string1\";\n * swap(s1,&s1[1]);\n */\n\n return 0;\n}\n\nvoid swap(char * const ptr1, char * const ptr2){\n\n char temp = *ptr1;\n *ptr1 = *ptr2;\n *ptr2 = temp;\n\n}\n```"}, {"role": "assistant", "content": "```\nchar *s1 = \"string1\";\n```\n\nBecauses1points to a string literal and modifying invokesundefined behaviourin C. That's why this doesn't work.\n\nWhereas in thischar s1[] = \"string1\";\n\ns1is an array and hence it can be modified."}]} {"messages": [{"role": "user", "content": "I have a C application called Test. Test takes in a single int parameter. I want to run Test with many different parameters, so I made the following bash script:\n\n```\n#!/bin/bash\nfor i in {0..5}\ndo\n ./Test \"$i\" \ndone\n```\n\nHowever, this executes./Test \"$i\"and not./Test 0, ./Test 1etc. Changing it to./Test $isimply executes./Test $i5 times.What am I doing wrong?"}, {"role": "assistant", "content": "Try\n\n```\n#!/bin/bash\nfor i in `seq 0 5`\ndo\n ./Test $i \ndone\n```\n\nTo create sequences in bash you can useseq, which has an advantage of working in any bourne-compatible shell (that is,seqworkseverywherebecause it's an external program, it's theforloop that becomes more portable).\n\nYes, it makes no difference with respect to./Testinvocation, but it provides arespectfulreason to procrastinate before fixing./Test."}]} {"messages": [{"role": "user", "content": "I know its probably obvious issue but since in very new to C I had to ask,\n\nThis is my code:\n\n```\n#include \n#define ASIZE 8\nint main()\n\n{\n int index;\n\n long int numbers[ASIZE];\n\n printf(\"enter 8 integers to be printed in reverse order:\\n\");\n\n for (index = 0; index < ASIZE; index++)\n\n {\n scanf(\"%li\", &numbers[index]);\n }\n\n printf(\"indexing is done!\");\n\n}\n```\n\nWhy am I not exiting the 'for' loop and printing \"indexing is done!\" ?"}, {"role": "assistant", "content": "scanfrequires your inputs to be whitespace-separated. Entering12345678will only go once round the loop."}]} {"messages": [{"role": "user", "content": "```\n#include\n#include\n\n#define d 10+10\n\nint main()\n{\n printf(\"%d\",d*d);\nreturn 0;\n}\n```\n\nI am new to the concept of macros.I found the output for the above program to be 120.What is the logic behind it?\n\nThanks."}, {"role": "assistant", "content": "```\n10+10*10+10 == 10 + 100 + 10\n```\n\nIs that clear?"}]} {"messages": [{"role": "user", "content": "I have gcc 4.7.2-3 and I get this following error:\n\nmain.c:5:6: error: array size missing in ‘fname’\n\nmain.c:6:6: error: array size missing in ‘lname’\n\nwhen initializing this:\n\n```\nint fname[];\nint lname[];\n```\n\nIs this no longer possible using higher versions of gcc? Because I am certain I have used this before...\n\nEDIT: The reason I say I remember this, is because I even see it here:http://h30097.www3.hp.com/docs/base_doc/DOCUMENTATION/V40F_HTML/AQTLTBTE/DOCU_046.HTM"}, {"role": "assistant", "content": "You can only declare an array with no size if you are initializing it right away\n\n```\nint myarr[] = {1, 2, 3};\n```\n\nor if it is the last member in a structure\n\n```\nstruct foo {\n int something;\n int somethingelse;\n char emptyarr[];\n};\n```"}]} {"messages": [{"role": "user", "content": "I was going through the linux kernel sources and found this function definition.\n\n```\nfunction(struct net * const *pnet)\n```\n\nCan somebody explain what does this mean. Is it a net* or net** or const net* or const net**?\n\nThanks"}, {"role": "assistant", "content": "pnet is a pointer to a const point to a struct net (in a case like this, you just read from right to left from the name of the variable to the name of the type, reading*as \"pointer)."}]} {"messages": [{"role": "user", "content": "I wrote a small program in C where I opened a file successfuly, then called sleep for 20 sec. In that 20 sec I deleted the open file using rm from shell. After sleep the program reads the data successfully and prints it on screen.\n\n```\nint bytes_read;\nFILE *fp = fopen(\"/tmp/file\", \"r\");\nsleep(20);\nbytes_read = fread(buf, 1, 5, fp);\nbuf[bytes_read] = '\\0';\nprintf(\"%s\", buf);\n```\n\nI expected it to read 0 bytes, but it prints the actual data in the file. What is the explanation behind this behaviour."}, {"role": "assistant", "content": "In linux and other POSIX systems you don't delete files. You just remove an inode from a directory. As long as there is a file descriptor open on a file it will not be deleted. Only when the last link to the inode and the last open file descriptor went away."}]} {"messages": [{"role": "user", "content": "This question already has an answer here:C99 Variable Length Array Max sizes and sizeof Function(1 answer)Closed8 years ago.\n\nI have some c code to concatenate a string.\n\n```\nchar str_cat[strlen(str1) + strlen(str2) + 1];\n```\n\nHow do I check the sizeof str_cat in gdb? Right now it reports 0 with:\n\n```\nprint sizeof(str_cat)\n```\n\nIt does print the string, but how do I print it showing the null character?\n\nLet me reword, how do I verify that str_cat is the proper size and has enough space?"}, {"role": "assistant", "content": "char str_cat[strlen(str1) + strlen(str2) + 1];How do I check the sizeof str_cat in gdb? Right now it reports 0 with:\n\nstr_catis a variable length array. Apparentlygdbdoes not how to deal with variable length arrays.\n\nThere is an open ticket here regarding this issue:http://sourceware.org/bugzilla/show_bug.cgi?id=9663\n\nit mentions an existing patch but at least my2012version7.4ofgdbdoes not include it."}]} {"messages": [{"role": "user", "content": "I'm looking for a very simple implementation of RSA in C. I need to place it in a DSP, so I'd like to use something very thin and straightforward.\nNonetheless, I just found only examples with little numbers (int or long) while I need to implement RSA at least at 1024 bits, so I also have to cope with large numbers.\n\nCan you point me to some libraries or examples for this?"}, {"role": "assistant", "content": "TheLibTomCryptand related projects are very clean and understandable."}]} {"messages": [{"role": "user", "content": "```\nfor(int y = 0; y < 5; y++)\n{ \n char cst1[2] = {info[x+2], info[x+3]};\n char cst2[2] = {info[x+5], info[x+6]};\n sales[count][atoi(&info[x]) - 1] = atoi(cst1) + atoi(cst2);\n x += 8;\n}\n```\n\nEvery time i do the following code the atoi(cst1) value is multiplied by two then added and atoi(cst2) is multiplied by 100 then added cant figure out why"}, {"role": "assistant", "content": "cst1andcst2don't appear to be NUL-terminated.\n\n```\nchar cst1[] = {info[x+2], info[x+3], '\\0'};\nchar cst2[] = {info[x+5], info[x+6], '\\0'};\n```"}]} {"messages": [{"role": "user", "content": "I am sending a long long to a byte array with other stuff to a java server. When I convert the long back at the java end its not what I am expecting. I have tested the java converter but I ObjectiveC I thought that with it been low level would be as simple as this.\n\n```\nuint8_t *data = alloca(sizeof(longlong));\nmemcpy(&data[sizeof(Byte)+1],&theLong,sizeof(long long));\n```\n\nIs that right or am I on the wrong tracks?"}, {"role": "assistant", "content": "Maybe... Depend on the endianess... take a look here:http://en.wikipedia.org/wiki/Endianness"}]} {"messages": [{"role": "user", "content": "It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.\n\nGiven a static array how to change it into dynamic allocation witharrasa pointer unsigned:\n\n```\nchar arr[] = {1,4,5,8,9,6,4,3,2,1,5,7}; \nunsigned char *arr = NULL;\n```\n\nNow how to assign this value toarr.\n\nI am new to programming please help."}, {"role": "assistant", "content": "Usemalloc()to dynamically allocate the array and usememcpy()to copy the contents. Remembering tofree()what wasmalloc()d."}]} {"messages": [{"role": "user", "content": "I made a stupid mistake (forgot semicolon, too much Python lately), but got an interesting error message from gcc: \"expected ',' or ';' before 'if'\".\n\nI know those error messages provide just an \"upper bound\" for possible source code, but I'd like to know if there is any construct in C such that \"if\" token really comes after ',' and not after ';'."}, {"role": "assistant", "content": "After isn't necessarilyimmediately after. The error message is more: 'I've just hit an 'if' construct. At this point I was expecting either an end to the (previous) statement, or the next item in the list. One of those things must be before this 'if', so I'm letting you know'"}]} {"messages": [{"role": "user", "content": "If I try to establish a connection viaPQconnectdband it fails, is it ok to callPQresetonPGconn*to retry or does it only work if I've already been connected once?"}, {"role": "assistant", "content": "If the connection attempt is failed because of some invalid connections options (error like invalid connection options) than calling the PQreset will also fail. But for cases where all arguments to the PQconnectdb were correct and connection was unsuccessful because of reasons like remote server was busy or not accepting the new connections than PQreset will work just fine."}]} {"messages": [{"role": "user", "content": "I have some code like this:\n\n```\nstatic int a = 6;\nstatic int b = 3;\n\nstatic int Hello[a][b] =\n{\n { 1,2,3},\n { 1,2,3},\n { 1,2,3},\n { 1,2,3},\n { 1,2,3},\n { 1,2,3}\n};\n```\n\nBut when I compile it, it says error:\n\nvariably modified 'Hello' at file scope\n\nHow could this happen? And how could I fix it?"}, {"role": "assistant", "content": "You can not have a static array whose size is given as a variable.\n\nThat's why constants should be#defined:\n\n```\n#define a 6\n```\n\nThis way, the preprocessor will replaceawith6, making it a valid declaration."}]} {"messages": [{"role": "user", "content": "What am I missing? If I want to increment a counter in a separate function, why does it give me a segmentation fault?\n\n```\nint point(int *cow);\n\nint main()\n{\n int *cow = 0;\n point(cow);\n return(0);\n\n}\n\nint point(int *cow) {\n (*cow)++;\n return(0);\n}\n```"}, {"role": "assistant", "content": "Dereferencing a null pointer is undefined behavior in C.\n\nMaybe you wanted to do this instead:\n\n```\nint a = 0;\nint *cow = &a;\n\npoint(cow);\n```\n\nNote that the temporary pointercowis not necessary and you can directly pass&atopointfunction."}]} {"messages": [{"role": "user", "content": "As we know, array name can't be assigned, sentence like:\n\n```\nchar * array[], * point;\narray = point; /* wrong */\narray++; /* wrong */\n```\n\nBut inmain(int argc, char * argv[]),argv++is ok and works well.\nWhat do i missing?"}, {"role": "assistant", "content": "In your examplesarrayis a true array, and thus a non-modifiable l-value. In main, since it's declared in the parameter list,argvis actually achar **, i.e. a pointer which is modifiable.\n\nIt all boils down to the fact thatchar *array[]means different things, depending on the context."}]} {"messages": [{"role": "user", "content": "I'm reading a txt file and getting all the chars that aren't space, transforming them to int using(int)c-'0'and that is working.\n\nThe problem is if the number has more than 1 digit, because I'm reading char by char.\n\nHow could I do to read like a sequence of chars, transform this sequence of chars into int?\n\nI tried using a string, but when I try to pass this string to my other function, it treats each index as a number, but what I need is that the whole string is treated as one number.\n\nAny ideas?"}, {"role": "assistant", "content": "A convenient way to do the conversion is to read the whole number into a buffer (string) and then callatoi. Make triple sure that the string is properly null-terminated."}]} {"messages": [{"role": "user", "content": "Clang has the following test cases:\n\n```\n#if 0\n#ifdef D\n#else 1 // Should not warn due to C99 6.10p4\n#endif\n#endif\n\n#if 0\n#else 1 // expected-warning {{extra tokens}}\n#endif\n```\n\nThe first#else 1indeed is fine because it's in a skipped group, but as far as I can see the second one should be an error - it doesn't match what the standard specifies as the syntax for preprocessor directives - yet GCC and Microsoft C++ agree on only giving it a warning. What am I missing?"}, {"role": "assistant", "content": "The standard does not have notions of \"error\" and \"warning\", it only knows \"diagnostic\". It is up to implementation to define what constitutes a diagnostic. Most implementations of C, including clang and gcc, define diagnostics to include both errors and warnings."}]} {"messages": [{"role": "user", "content": "This question already has answers here:Closed10 years ago.\n\nPossible Duplicate:What the pointer size in 64 bits computer in C++?\n\nI'm studing C at The University.\n\nI try to setup an environment for programming on Windows 7/8 and have a problem\n\nThis code:\n\n```\nint main()\n int *p;\n printf(\"%d\",sizeof(p));\n return 0;\n}\n```\n\nprints 4 instead of 8 (8 is printed in University).\nWhat can i do?\n\nMy Windows is 64bit and x64 processor."}, {"role": "assistant", "content": "You probably compile the code into 32 bit application. You need to compile it as 64 bit application. Check your compiler settings. It does not matter that your OS is 64 bit."}]} {"messages": [{"role": "user", "content": "I know we can useWriteFileto write something to a file:\n\n```\nBOOL WINAPI WriteFile (HANDLE hFile, \n LPCVOID lpBuffer, \n DWORD numOfBytesToWrite,\n LPDOWRD lpNumOfBytesWritten,\n LPOVERLAPPED lpOverlapped);\n```\n\nBut how can we write ASCII string to a file using this function?"}, {"role": "assistant", "content": "Usually something like this:\n\n```\nWriteFile(your_file, your_string, strlen(your_string), &written, NULL);\n```\n\nYou usually don't want to do this though -- unless your strings are pretty long, it'll almost always be more efficient (i.e., faster) if you use something likefprintforfputsto take advantage of the buffering built into the standard library."}]} {"messages": [{"role": "user", "content": "I am trying to make an object file via \"cc -c -o \" but I get the following statement ,what should I do to solve this,thanks in advance\n\n```\n~/hedor1>lex -t example.l > example.c\n~/hedor1>cc -c -o example.o example.l\ncc: example.l: linker input file unused because linking not done\n```\n\nthe first line to produce the example.c is working and I get the .c file but when I write the second line I get the above!"}, {"role": "assistant", "content": "You are passing the flex source to the compiler, which apparently interprets it as being a linker input file, and complains because you told the compiler not to do the linking step.\n\nThe second command should have been:\n\n```\ncc -c -o example.o example.c\n```"}]} {"messages": [{"role": "user", "content": "I am reading 512 chars into a buffer and would like to display them in hex. I tried the following approach, but it just outputs the same value all the time, despite different values should be received over the network.\n\n```\nchar buffer[512];\nbzero(buffer, 512);\nn = read(connection_fd,buffer,511);\nif (n < 0) printf(\"ERROR reading from socket\");\nprintf(\"Here is the message(%d): %x\\n\\n\", sizeof(buffer), buffer);\n```\n\nIs it possible that here I am outputting the address of the buffer array, rather than its content? Is there an easy way in C for this task or do I need to write my own subroutine?"}, {"role": "assistant", "content": "This will read the same 512 byte buffer, but convert eachcharacterto hex on output:\n\n```\nchar buffer[512];\nbzero(buffer, 512);\nn = read(connection_fd,buffer,511);\nif (n < 0) printf(\"ERROR reading from socket\");\n\nprintf(\"Here is the message:n\\n\");\nfor (int i = 0; i < n; i++)\n{\n printf(\"%02X\", buffer[i]);\n}\n```"}]} {"messages": [{"role": "user", "content": "Leta,bbe positive integers with different values. Is there any way to simplify these expressions:\n\n```\nbool foo(unsigned a, unsigned b)\n{\n if (a % 2 == 0)\n return (b % 2) ^ (a < b); // Should I write \"!=\" instead of \"^\" ?\n else \n return ! ( (b % 2) ^ (a < b) ); // Should I write \"(b % 2) == (a < b)\"? \n}\n```\n\nI am interpreting the returned value as a boolean."}, {"role": "assistant", "content": "How is it different from\n\n```\n(a%2)^(b%2)^(a\n\nstruct X {\n ~X() { std::cout << std::endl; }\n};\n\n#define DBG (X(), std::cout << __FILE__ << \" \" << __LINE__ << \" \")\n\nint main () {\n std::string world(\", world\");\n DBG << \"Hello\" << world;\n}\n```"}]} {"messages": [{"role": "user", "content": "I am trying to extract relative path name from absolute path name. Is there a function for this in C? Is there a function to print string starting from a particular character(I have the index)?"}, {"role": "assistant", "content": "In POSIX.1-2001 (e.g. Linux),man 3 basenamegives:\n\nThe functions dirname() and basename() break a null-terminated pathname string into directory and filename components. In the usual case, ... basename() returns the component following the final '/'. Trailing '/' characters are not counted as part of the pathname."}]} {"messages": [{"role": "user", "content": "I have a simple socket server that is supposed to receive a string and return another.\nThe string received is multi-line.\nIs there a way to tell when the client finished sending without having a predefined end of transmission set of characters added at the end?"}, {"role": "assistant", "content": "You have to know in advance either (1) what the length of message is or (2) what constitutes the end of a message. So either (1) prefix a message with the expected length; or (2) have all messages be the same size; (3) define different message types in which the length is known in advance; or (4) define exactly what constitutes the end (and possibly the beginning) of a message.\n\nIn your case possibly two line feeds in a row could signal the EOM. Or a null byte if there are otherwise no null bytes in the strings. Or just have the client send the length first and then the message."}]} {"messages": [{"role": "user", "content": "I have this function\n\n```\nTOKENP scan_line() {\n TOKENP cur, last = 0;\n\n while(cur = scan_opd())\n last = cur;\n\n if (cur = scan_comm())\n #if ENABLE_COMMENT_AS_TOKEN\n add_token(cur);\n #endif\n return last;\n}\n```\n\nIf the#ifdirective is false, will it be compiled as\n\n```\nif (cur = scan_comm())\n return last;\n```\n\nor\n\n```\nif (cur = scan_comm());\nreturn last;\n```\n\n?"}, {"role": "assistant", "content": "It will be compiled just as if the disabled line didn't exist, so:\n\n```\nif (cur = scan_comm())\n return last;\n```\n\nYou should use braces to make it clear what you mean.\n\n```\nif (cur = scan_comm())\n{\n #if ENABLE_COMMENT_AS_TOKEN\n add_token(cur);\n #endif\n} \nreturn last;\n```"}]} {"messages": [{"role": "user", "content": "I have a simple makefile that compiles ap.cfile to an executable usinggccon Linux.\nThep.cfile depends on aa.hfile.\nMy makefile looks like this:\n\n```\n//makefile\nCC = gcc\n\nbuild: p.c a.h\n $(CC) -o out p.c\nclean:\n rm -f *.exe\nrebuild: clean build\n```"}, {"role": "assistant", "content": "Your makefile doesn't produce the files it promises to produce, namelybuild,cleanandrebuild. Since these targets are not files they should be marked asphony targets:\n\n```\n.PHONY: build clean rebuild\n```\n\nbuildtarget should be:\n\n```\nbuild : out\n\nout : p.c a.h\n $(CC) -o $@ p.c\n```"}]} {"messages": [{"role": "user", "content": "I need an software emulator PC/SC reader for Linux, but can't find.\n\nThe only thing I found ishttp://vsmartcard.sourceforge.net/. But this library requires a mobile phone to emulate PC / SC device.\n\nCan I find somewhere fully software emulator of PC/SC reader?\nThank you for you attention!"}, {"role": "assistant", "content": "The link you provided is the answer to your question.\nThe project proposed on that link is the Virtual Smart Card Architecture which can be used to simulate smart cards for different purposes. You do not require a mobile phone, that is just one use case scenario they present.\n\nhttp://vsmartcard.sourceforge.net/virtualsmartcard/README.htmlFollowing this instructions you can access three smart card simulators provided by them. Besides this you can also hack their python virtual card and implement/simulate your desired behaviour."}]} {"messages": [{"role": "user", "content": "So I am making my Hello world program, and it is like this:\n\n```\n#include \"lib-includes/capi324v221.h\" \n\nvoid CBOT_main(void)\n{ \n LCD_open();\n\n if (!LCD_OPEN) {\n\n while (true); // loop forever \n }\n\n else {\n LCD_printf(\"Hello, World!\");\n while(true); // loop forever\n } \n}\n```\n\nCan anyone help with this? I am sorry if it is a little vague; it is all the info I know for the most part."}, {"role": "assistant", "content": "First of all what are thosewhileloops doing there? My first reaction is to get rid of those.\n\nI have no personal experience with programming CEENBots\\your IDE, but based on the error description in the question title I suspect your source file has a!in it which messes up the build process (it complains about aWorld!.mapfile, best to keep special characters out of filenames).\n\nedit:\nTo extend upon what Öö Tiib states below, get rid of the space and comma too :)"}]} {"messages": [{"role": "user", "content": "It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago.\n\nWhat do the*and&symbols mean in this code:\n\n```\n#include\nmain()\n{\n char *p;\n p=\"hello\";\n printf(\"%s\\n\",*&*&p);\n}\n```\n\nWhat does theprintfstatement do in the above program? Specifically, what does*&*&pmean?"}, {"role": "assistant", "content": "These:\n\n```\n*&*&\n```\n\nAre redundant and you would never encounter such ridiculous code in a real project. The ampersand takes the address ofp, and the asterisk*dereferences it to produce the originalchar*. Back and forth we go...\n\nThink of it as:\n\n```\n*(&(*(&p)))\n```\n\nAs an aside, your type-less signature formainwon't cut it on modern compilers where a return type ofintis no longer assumed."}]} {"messages": [{"role": "user", "content": "I want to use a macro like this\n\n```\n#define Return(x) {call_my_function(); return (x);}\n```\n\nis there any way to use or declare a macro without parentheses, so I can use it like a real return call and not a function? For example:\n\n```\nBOOL my_func() {\n code....\n Return FALSE;\n}\n```"}, {"role": "assistant", "content": "You could do something horrific as\n\n```\n#define Return for (call_my_function(); ;) return\n```\n\nEdit:Changed to Daniel's version for the nice smiley that makes. And Jim's idea of \"overloading\"returndirectly is valid and even more horrific ;)"}]} {"messages": [{"role": "user", "content": "Hello can you give me an example of the usage of this method\n\n```\n+(NSString *)description\n```\n\nDo I use description with an instance of a NSObject (any kind of object) or NSString?\n\nor do I use without an instance, directly using NSObject (any kind of object) or NSString?"}, {"role": "assistant", "content": "The description of the instance gives you information about the specific instance you have created.\n\n- (NSString *)description;\n\n```\nNSString *string = [NSString alloc] initwithString:@\"aString\"]];\n[string description];\n```\n\nGives you information about this instance (location in memory etc)\n\nOn the other side:\n\n+ (NSString *)description;\n\n```\n[NSString description];\n```\n\nGives you information about the class NSString.\n\nThe same rules apply to all NSObject subclasses and other classes that conform to NSObject protocol suchNSArray,NSDictionary*NSProxy* etc"}]} {"messages": [{"role": "user", "content": "Is it possible to use GTK without a valid X display?\n\nI want to use GTK with Webkit, but for now I'm only interested in using the DOM functions to experiment, so I have no need to actually display anything. It's very convenient for me to do this over an SSH connection on a server that has no display.\n\nBut, without aDISPLAYenvironment variable,gtk_init()simply fails with the message:\n\nGtk-WARNING **: cannot open display:\n\nIs there anyway to use GTK without a display?"}, {"role": "assistant", "content": "There is an X server called Xvfb which provides a validDISPLAYand sends the output to a file instead of to graphics hardware. You can run that on the same machine that's running your gtk client, and gtk will be able to do whatever it wants to do without using any of your network bandwidth. As a bonus, you can read Xvfb's output buffer from the file, allowing you to get a screenshot of what would be on the screen."}]} {"messages": [{"role": "user", "content": "I am using an open source CLI parser (this one ->http://sourceforge.net/projects/cliparser/) to add command line interface to my application and it works really neat on its own, but I am having trouble adding it to my application. The documentation provided is very meager and I have limited experience with makefiles. If anyone has used this parser before could you help me out with it?\n\nSpecifically, how do I make the parser run within my program? The document says\"link your parser against libparser.a\" What does that mean?\n\nThanks!"}, {"role": "assistant", "content": "When you compile your program, you need to link against the library. If using GCC, this is done via two ways:\n\nYou can specify the path to the library:gcc myapp.c /somepath/libparser.aOr, if it is in your standard library directory you should be able to do:gcc myapp.c -l parser"}]} {"messages": [{"role": "user", "content": "could someone explain the following code snippet to me please, specifically the third line as it seems to be causing an error in my code:\n\n```\nchar * (strtok_r)(char *s, const char *delimiters, char **lasts) {\n char *sbegin, *send;\n sbegin = s ? s : *lasts;\n ...\n```\n\nIm guessing its more like Im passing an incorrect pointer value or something but cant figure it out as Im not sure exactly how the function is doing what it does...\n\nTa\n\nEDIT: Im not exactly sure the error that occurs either because the g$£&mn f*£$%^% Visual studio JIT debugger keeps trying to open all the time and messes everything up. grr.."}, {"role": "assistant", "content": "Equivalent to\n\n```\nif (s)\n sbegin = s;\nelse\n sbegin = *lasts;\n```\n\nTo get more detail about?:operator, you could readthis."}]} {"messages": [{"role": "user", "content": "Searching for manuals and docs about Open Watcom linker, inline assembly and C compiler, as I found official manuals not good enough.\nI'm focused especially on C and assembly.\nI would appreciate you for links to tutorials, books and etc."}, {"role": "assistant", "content": "Back in time Watcom was a perfect tool for 32-bit C/Asm development. At the same time much information could be found in ftp archives like good oldftp://x2ftp.oulu.fi. It is now defunct, butmirrorsexist. Look at the /watcom folder there.\n\nAlso try searching older sites likehttp://www.programmersheaven.com, they arethesource.\n\nEDIT: as of 2017, most of the information seems to be missing from the link above (Programmer's Heaven), so the only reference seems to be OpenWatcom's documentation and some old open-source software."}]} {"messages": [{"role": "user", "content": "I can't use C++ syntax likecout, so I've tried usingbut it still says\n\nundefined reference to '_gotoxy'\n\nWhat's the problem? Everyone says thatconio.hits not in K&R either because it isn't a standard library. Anyone got an idea?\n\nI am using MinGW and command prompt."}, {"role": "assistant", "content": "When linking you need to add the ncurses library:\n\n```\n$ gcc my-source.c -o my-program -lncurses\n```\n\nThat last flag to the command line above (-lncurses) is what tells the compiler to link (-l) with the ncurses library."}]} {"messages": [{"role": "user", "content": "I have written setter and getter APIs for certain members of a struct in C. I want the getter function to be called only if setter API was called. Otherwise, default values should be assigned to the members of the function. Is there a way to find out if the members of struct were assigned values or not?\n\nThanks!"}, {"role": "assistant", "content": "Is there a way to find out if the members of struct were assigned values or not ?\n\nNo. You would need to keep track of that yourself by a separate set of variables, or by initializing the values of the struct to values they normally cannot have(e.g. -1 , but in such a case, every piece of code would need to honor the convention of not using such special values doring normal usage)"}]} {"messages": [{"role": "user", "content": "I'm trying to write a program that handles detection of various objects. The objects have an origin, width, height, and velocity. Is there a way to set up a data structure/algorithm so that every object isn't checking with every other object?\n\nSome sample code of the problem I'm trying to avoid:\n\n```\nfor (int i = 0; i < ballCount; i++) \n{ \n for (int j = i + 1; j < ballCount; j++) \n { \n if (balls[i].colliding(balls[j])) \n {\n balls[i].resolveCollision(balls[j]);\n }\n }\n}\n```"}, {"role": "assistant", "content": "You can use aquadtreeto quickly find all rectangles that intersect with another rectangle. If you need to handle non-rectangular shapes, you can first find objects whosebounding boxesintersect.\n\nSome common uses of quadtrees...Efficient collision detection in two dimensions..."}]} {"messages": [{"role": "user", "content": "My program contains the following code.\n\n```\npthread_t PThreadTable[32];\n\n for (i=1; i= 0; y-- ) { // iterate from high to low\n\n fscanf( inf, \"%02x\", &ct[x][y] );\n printf( \"%02x \", ct[x][y] );\n }\n printf( \"\\n\" );\n }\n}\n```"}, {"role": "assistant", "content": "size_tis unsigned, so your loop will aftery = 0continue withmax_unsignedwhich is >= 0."}]} {"messages": [{"role": "user", "content": "I'm flummoxed by how to convert from a binary value to a char in c.\n\nFor example, let's say I have 01010110 and want to print the corresponding letter 'V' from that. How do I do this?\n\nThanks for any help!"}, {"role": "assistant", "content": "```\n#include \n#include \nint main(void)\n{\n char *data = \"01010110\";\n char c = strtol(data, 0, 2);\n printf(\"%s = %c = %d = 0x%.2X\\n\", data, c, c, c);\n return(0);\n}\n```\n\nOutput:\n\n```\n01010110 = V = 86 = 0x56\n```\n\nReferences:\n\nstrtol()Correct usage ofstrtol()"}]} {"messages": [{"role": "user", "content": "My question is how I would go about converting something like:\n\n```\nint i = 0x11111111;\n```\n\nto a character pointer? I tried using the itoa() function but it gave me a floating-point exception."}, {"role": "assistant", "content": "itoais non-standard. Stay away.\n\nOne possibility is to usesprintfand the proper format specifier for hexa i.e.xand do:\n\n```\nchar str[ BIG_ENOUGH + 1 ];\nsprintf(str,\"%x\",value);\n```\n\nHowever, the problem with this computing the size of thevaluearray. You have to do with some guesses andFAQ 12.21is a good starting point.\n\nThe number of characters required to represent a number in any basebcan be approximated by the following formula:\n\n⌈logb(n + 1)⌉\n\nAdd a couple more to hold the0x, if need be, and then yourBIG_ENOUGHis ready."}]} {"messages": [{"role": "user", "content": "I need to enable core dumps in cygwin. I have usedulimit -c unlimitedbut when the program I want to debug crashes, there still is no coredump in the directory. Is this actually the correct way to enable core dumps and where can I find the dump then?"}, {"role": "assistant", "content": "This should be working. What shell are you using?\n\nDon't forget that the dump is not named \"core\" ... rather on a Windows machine with Cygwin it will likely be named something like \"mybadprog.exe.stackdump\""}]} {"messages": [{"role": "user", "content": "This question already has answers here:Closed11 years ago.\n\nPossible Duplicate:Why was the switch statement designed to need a break?\n\nI have this:\n\n```\nswitch(i)\n{\n case a:\n {\n //code\n }\n case b:\n {\n //code\n }\n case c:\n {\n //code\n }\n}\n```\n\nIfi == a, will the code inbandcbe executed or must I put abreak;in each one?\n\nThanks,"}, {"role": "assistant", "content": "Must I put abreak;in each one?\n\nYes, if you only want a single case to execute. Alternatively, other control flow statements can also cause aswitchto be exited, likereturnorthrow.\n\nIf you were to replace//codewith, say,std::cout << \"case [x]\" << std::endl, the answer would be readily apparent."}]} {"messages": [{"role": "user", "content": "I have a functiongetData(void* data)which should copy to data some internal calculated values\nfor exampleint r = getRadius();r should be copied to data ,and is such a way returned from function getData\nwhat is the correct way to do it?\nI tried*(int*)data = r;but I am not sure this is a best solution."}, {"role": "assistant", "content": "If you are certain that the memory referenced by the void pointer is an int, then you can be confident in\n\n```\n*(int *)data = r;\n```\n\nHowever a better general solution is:\n\n```\nmemcpy(data, &r, sizeof(int));\n```\n\nThis way you don't have to worry about byte alignment or other potential gotchas."}]} {"messages": [{"role": "user", "content": "I'm currently using C Builder:\n\nDWORD finalAddress = 0xFFFFFFFF;\nTListItem *ListIt;\nListIt->Caption = finalAddress;\n\nThis will output:\n4294967295 (which is 0xFFFFFFFF in DEC)\n\nI want it to show 0xFFFFFFFF.\n\nHow do I do that?"}, {"role": "assistant", "content": "Assuming that you have access to C++ standard library, try this:\n\n```\n#include \n#include \n#include \n\nstd::ostringstream ss;\nss << std::hex << finalAddress;\n\nAnsiString ansiHex = AnsiString (ss.str().c_str());\nListIt->Caption = ansiHex;\n```\n\nThis last assignment may not work - I do not have access to Embarcadero's headers, so I have no idea what's the type ofListIt->Caption. There may be need to perform additional conversion."}]} {"messages": [{"role": "user", "content": "From the shell I can activate the leds on my system like this:\n\n```\n#echo 1 > /sys/class/leds/NAME:COLOR:LOCATION/brightness\n```\n\nI want to do the exact same thing from a C program, but I have not been able to find a simple example on how to accomplish this?"}, {"role": "assistant", "content": "Open the sysfs node like a file, write '1' to it, and close it again.\n\nFor example:\n\n```\n#include \n#include \n\nvoid enable_led() {\n int fd;\n char d = '1';\n fd = open(\"sys/class/leds/NAME:COLOR:LOCATION/brightness\", O_WRONLY);\n write (fd, &d, 1);\n close(fd);\n}\n```"}]} {"messages": [{"role": "user", "content": "Two projects:\n\nThe loader, a standalone executable (only loads modules)any module, a shared library (librainbowdash.so) (there can be many modules)\n\nNow, the module is linked with-lpthreads, but I get some weird errors which make me think pthreads is bound as a shared object only, and when the loader loads a module pthreads are not being loaded. (debugging with GDB is impossible, that kind of errors).\n\nI thought the-lswitch only allows static libraries? Does it? Doesn't it?"}, {"role": "assistant", "content": "-lspecifies library names. It is up to the linker to resolve the library names into static libraries or shared objects to be linked against as appropriate. And it is the loader's job to load any shared libraries used."}]} {"messages": [{"role": "user", "content": "I am running the following C code:\n\n```\n#define cube(x) (x*x*x)\nvoid main()\n{ \n int x=2,y; \n y=cube(++x); \n printf(\"%d %d\",++x,y); \n}\n```\n\nI am expecting result as\n\n```\n6,60\n```\n\nBut it is giving different result. I think I have misconception on pre-processor. I think the code will be similar to\n\n```\nvoid main()\n{ \n int x=2,y; \n y=++x*++x*++x; \n printf(\"%d %d\",++x,y); \n}\n```\n\nPlease correct me if I am wrong.\n\nI am interpretting the result to come as\n3*4*5=60but it is coming 125"}, {"role": "assistant", "content": "You defined a macro, which works as a simple string substitution, so that the presented translation is correct.\n\nHowever, the order of execution of subexpressions is undefined and they can be, for example, interleaved and this makes theundefined behaviour."}]} {"messages": [{"role": "user", "content": "I'm trying to set the cursor to a watch. The problem is that gdk_set_cursor() requires a gdk_window.\n\nHow do I get the gdk_window of a gtk_window in C? I've seen examples for gtkmm and pygtk but I can't find the corresponding C function."}, {"role": "assistant", "content": "```\nGdkWindow *gdk_window = gtk_widget_get_window(GTK_WIDGET(gtk_window));\n```\n\nor, pre GTK 2.14, but now disallowed:\n\n```\nGdkWindow *gdk_window = gtk_window->window;\n```"}]} {"messages": [{"role": "user", "content": "While iterating through socket file descriptors, how can I check if one of them is from a passive socket (listening for connections)?"}, {"role": "assistant", "content": "This can be checked withgetsockopt(SO_ACCEPTCONN). For example:\n\n```\n#include \n\nint val;\nsocklen_t len = sizeof(val);\nif (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &val, &len) == -1)\n printf(\"fd %d is not a socket\\n\", fd);\nelse if (val)\n printf(\"fd %d is a listening socket\\n\", fd);\nelse\n printf(\"fd %d is a non-listening socket\\n\", fd);\n```"}]} {"messages": [{"role": "user", "content": "How can I \"compile\" Objective-C Code to (only) C-Code?There is a way to preprocess Objective-C in Xcode (Product -> Generate Output -> Generate Preprocessed File), but this is not what I'm looking for...\n\nThanks..."}, {"role": "assistant", "content": "clang (the compiler front-end used by Xcode nowadays) has a-rewrite-objcoption built-in, which allows you to generate C++ code based on Objective-C (or Objective-C++) code.\n\nJust don't ask me how to combine that with Xcode."}]} {"messages": [{"role": "user", "content": "This question already has answers here:how to calculate size of pointer pointed memory?(9 answers)Closed9 years ago.\n\nSay if i want to print out my integer stored inside a \"array\" , which indeed a pointer in memory.When i use the code:\n\n```\nint main(void)\n{\n int *arr = malloc(3*sizeof(int));\n int *p = arr;\n *arr++=1;\n *arr++=2;\n *arr=3;\n\n while (??) // what should be filled in the while?\n printf(\"%d\",*p); // so that we can get the validly stored elements?\n\n return 0;\n}\n```"}, {"role": "assistant", "content": "C does not provide a built-in way to find the size of dynamically allocated chunks of memory. You have to store the size, and pass it \"on the side\".\n\nOne way to address this would be to create astructcombining a pointer and asize_tvalue describing the number of elements allocated in the array."}]} {"messages": [{"role": "user", "content": "To create a daemon I have read somewhere that in order to close all the open file descriptors we can use the following code:-\n\n```\nfor (fd = 0; fd < _NFILE; fd++)\n close(fd); /* close all file descriptors */\n```\n\nI have to define _NFILE as\n\n```\n#define _NFILE 3\n```\n\nor is it already defined in some include files?\nI tried to grep it in the /usr/include directory but could not find anything."}, {"role": "assistant", "content": "_NFILEonly applies to original Unix. The portable way to do this issysconf(_SC_OPEN_MAX)(POSIX)."}]} {"messages": [{"role": "user", "content": "I have a question which involves calling a function with 2 parameters of a pointer to a pointer\n\n```\nint main(void)\n{ ...\nint *ptrp = &p, *ptrq = &q;\nint **ppp = &ptrp, **ppq = &ptrq;\nswap_ptr(ppp,ppq);/* &ptrp, &ptrq passed */ \n/* to swap_ptr() */\nreturn 0;\n}\n\nvoid swap_ptr(int **ptrA,int **ptrB)...\n```\n\nWe have to swap the values of ptrp and ptrq, so does that mean in the swap_ptr function I just use *ptrA and *ptrB to swap them or is it some other pointer statement?\n\nThanks"}, {"role": "assistant", "content": "It's the same concept as swapping anything:\n\n```\nvoid swap(int* a, int* b)\n{\n int tmp = *a;\n *a = *b;\n *b = tmp;\n}\n```\n\nIn this case, you just happen to be swapping int* instead of int:\n\n```\nvoid swap(int** a, int** b)\n{\n int* tmp = *a;\n *a = *b;\n *b = tmp;\n}\n```"}]} {"messages": [{"role": "user", "content": "```\n#include \n#include \n#include \n#include \n\nint main()\n{\nuint32_t ip = 0;\nprintf(\"%s\\n\",inet_ntoa(*(struct in_addr *)ip));\nreturn 0;\n}\n```\n\nI don't want to do this by declaring any temporary variable. This program gives segmentation fault.\n\n```\nstruct in_addr {\n uint32_t s_addr; \n};\n```"}, {"role": "assistant", "content": "You're casting an int to a pointer. Perhaps you want this:\n\n```\n*(struct in_addr *)&ip\n```\n\nBut the result is implementation-defined (for a start, there're endianness considerations)."}]} {"messages": [{"role": "user", "content": "I have a function as below\n\n```\nextern \"C\" int FuncTrace(const char *fmt, ...)\n{\n va_list args;\n va_start(args, fmt);\n return printf(fmt, args);\n}\n```\n\nIf I print some thing on console as below, it does not work?\n\n```\nFuncTrace(\" %s \\n\", __PRETTY_FUNCTION__ );\n```\n\nCan someone help me correct the FuncTrace() ?"}, {"role": "assistant", "content": "You need thevprintffunction if you want to pass in ava_listpseudo-argument:\n\n```\nreturn vprintf(fmt, args);\n```"}]} {"messages": [{"role": "user", "content": "I compile my C++ program to LLVM IR using the following command.\n\n```\nclang++ -O4 -emit-llvm program.cpp -c -o program.ll -S -pthread\n```\n\nHowever, now I want to do the same for multiple files. How can I do that? I want to produce one IR file after the compilation (not separate IR files for each file). In other words I want to have the linked code (code from all files linked together) in my IR file."}, {"role": "assistant", "content": "You're probably looking for thellvm-linkcommand, which links bitcode files together."}]} {"messages": [{"role": "user", "content": "I want to run script file on android Shell using Native C program.\n\nI tried usingsystemfunction but it's not working.\n\n```\nresult = system(\"sh ./test.sh\");\n\nLOGD(\"result is %d\", result);\n```\n\nsystem command returns 0 means its not executed script file successfully.\n\ntest.sh contains\n\n```\necho \"test....\"\n```\n\nAndroid NDK application could not printtest....when this system call runs.\n\nEven any script can not be started using system call. i checked more than 10 different scripts.\n\ntest.sh have777permissions\n\nAny help would be appreciated."}, {"role": "assistant", "content": "where is 'sh'? and what is your '.' current directory when the application runs? try:\n\nresult = system(\"/system/bin/sh /full/path/to/test.sh\");"}]} {"messages": [{"role": "user", "content": "How do I get the size of a pointer in C usingsizeof? I want to malloc some memory to store a pointer (not the value being pointed to)."}, {"role": "assistant", "content": "Given an arbitrary type (I've chosencharhere, but that is for sake of concrete example):\n\n```\nchar *p;\n```\n\nYou can use either of these expressions:\n\n```\nsizeof(p)\nsizeof(char *)\n```\n\nLeading to amalloc()call such as:\n\n```\nchar **ppc = malloc(sizeof(char *));\nchar **ppc = malloc(sizeof(p));\nchar **ppc = malloc(sizeof(*ppc));\n```\n\nThe last version has some benefits in that if the type ofppcchanges, the expression still allocates the correct space."}]} {"messages": [{"role": "user", "content": "I am debugging a program using gdb. First Iloadmy executable, then Icontinueto run the program. I sometimes want to interrupt execution of my program, so I doCtrl + C.\n\nMy problem is that this closesbothmy program and gdb. How can I exit my program without exiting gdb?"}, {"role": "assistant", "content": "Have you tried to usekillfrom inside gdb?"}]} {"messages": [{"role": "user", "content": "I have a nice C++ function, which supports multiple arguments through va_list + va_start + va_arg.\nBut I had to convert my project to C. After conversion, this va_list construction gets rejected by the compiler (multiple errors). Is there any way to do that thing in C, and (if yes) what I need to change?"}, {"role": "assistant", "content": "The Wikipedia page onstdarghas probably everything you need."}]} {"messages": [{"role": "user", "content": "Suppose I have a pointer to a function calledfoo. How do I now run the function that this is pointing to?"}, {"role": "assistant", "content": "If you function has the following signature:\n\n```\nvoid foo(int x);\n```\n\nAnd you have defined the following pointer:\n\n```\nvoid (*ptr)(int) = foo;\n```\n\nYou can execute foo, through \"ptr\", like this:\n\n```\nptr(12); //actually calls foo(12);\n```"}]} {"messages": [{"role": "user", "content": "I'm using some old C code that uses the old deprecatedIplImagetype.\n\nI'm using the new OpenCV 2.3.1 for Android, and the images I get from the camera areCvMats. I want to convert them toIplImageso I can pass it to the native function.\n\nAlternatively, I could modify the original function to accept aCvMatand convert it toIplImageinside the body of the function, but I need to do this in C NOT C++."}, {"role": "assistant", "content": "UsecvGetImage:\n\n```\nIplImage tmp;\nIplImage* result = cvGetImage((CvArr*) mat, &tmp);\n```"}]} {"messages": [{"role": "user", "content": "I already have around 10 elements in enum which I am using. I wanted to know the maximum so that I could code properly."}, {"role": "assistant", "content": "Anenumcan hold at least1023enumeration constants in a conforming implementation (see §5.2.4.1 \"Translation limits\" of ISO/IEC 9899:1999). So that gives you a lower bound.\n\nSince the type of an enumeration constant isint(see §6.4.4.3 \"Enumeration constants\" of ISO/IEC 9899:1999), the upper bound would beINT_MAX + 1(assuming no duplicate enumeration constant values), or evenINT_MAX + 1 - INT_MINif you also use negative values.\n\nAny implementation is free to choose how many enumeration constants an enumeration can contain, as long as it's between these lower and upper bounds."}]} {"messages": [{"role": "user", "content": "Given the following program:\n\n```\n#include \n\nint main()\n{\n char buf[1024];\n scanf(\"%s\", buf);\n printf(\"----> %s\", buf);\n return 0;\n}\n```\n\nwhich is executed as follows:\n\ngrep ....| a.out\n\nor\n\necho ....| a.out\n\nI get aSegmentation faulterror. Can anyone explain why?"}, {"role": "assistant", "content": "Whatever you are echoing or grepping must contain more than 1023 characters. (1024 - 1 for the null terminator.)\n\nInstead of usingscanf, usefgetsand specify a size. Alternatively, usescanfbut specify the field length. You can doscanf(\"%1023s\", buf);. If there's more bytes available, you can always do it again to read in the rest.\n\nGiven your test input, you should not receive a segfault. I just tried it locally and it worked fine. If you are on Linux, since you wrotea.outinstead of./a.out, depending on how your path is configured you may be running the wrong program (some sort ofa.outin your bin folder?)"}]} {"messages": [{"role": "user", "content": "I am trying to concat two const char * strings.\n\nWhen i have a statement likestrcat(a,b)I get the warningexpected ‘char * restrict’ but argument is of type ‘const char *’\n\nis there a way to call strcat that will not produce the warning?\nThanks!"}, {"role": "assistant", "content": "strcat()modifies the first operand. Therefore it cannot beconst. But you passed it aconst char*.\n\nSo you can't usestrcat()on twoconst *charstrings."}]} {"messages": [{"role": "user", "content": "What is a simple way to see if my low-pass filter is working? I'm in the process of designing a low-pass filter and would like to run tests on it in a relatively straight forward manner.\n\nPresently I open up aWAVfile and stick all the samples in a array of ints. I then run the array through the low-pass filter to create a new array. What would an easy way to check if the low-pass filter worked?\n\nAll of this is done in C."}, {"role": "assistant", "content": "You can use a broadband signal such as white noise to measure the frequency response:\n\ngenerate white noise input signalpass white noise signal through filtertake FFT of output from filtercompute log magnitude of FFTplot log magnitude\n\nRather than coding this all up you can just dump the output from the filter to a text file and then do the analysis in e.g. MATLAB or Octave (hint: useperiodogram)."}]} {"messages": [{"role": "user", "content": "Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed9 years ago.Improve this question\n\nUsing the standard input, the user enters 1 letter. If its a valid lower-case letter, then the program prints out the upper-case version."}, {"role": "assistant", "content": "You could usetoupper. If you need to check to see if the input character is lower case first, you can useislowerto test it."}]} {"messages": [{"role": "user", "content": "If I have a string like:\n\n```\nconst char* mystr = \"Test Test Bla Bla \\n Bla Bla Test \\n Test Test \\n\";\n```\n\nHow would I use the newline character '\\n', to split the string into an array of strings?\n\nI'm trying to accomplish in C, the thingstring.Split()does in C# or boost's string algorithmsplitdoes in C++ ."}, {"role": "assistant", "content": "Try to use thestrtokfunction. Be aware that it modifies the source memory so you can't use it with a string literal.\n\n```\nchar *copy = strdup(mystr);\nchar *tok;\n\ntok = strtok(copy, \"\\n\");\n/* Do something with tok. */\nwhile (tok) {\n tok = strtok(NULL, \"\\n\");\n /* ... */\n}\n\nfree(copy);\n```"}]} {"messages": [{"role": "user", "content": "I've been wondering which is implemented in terms of which. My guess goes to egfopenbeing implemented usingOpenFile. From what I can tell, the Win32 API is more complete than the MSVC C library implementation, so my guess would make sense.\n\nIs this correct, or is it the other way around?"}, {"role": "assistant", "content": "Yes, Win32 is a \"lower-level\" API than the standard C-library ... basically the standard C-library on Windows is an abstraction of native Windows syscalls that allows certain standard operations to remain compatible across any series of platforms that support the C-standard library. Each platform will have it's own implementation of the C-library based off internally native system calls."}]} {"messages": [{"role": "user", "content": "Well, this must be a silly one. Here below is a can-not-be-simpler code in C. It can not compile saying \"undefined reference to sleep\". But I think I include all system header I need...\n\n```\n#include \n#include \nint main()\n{\n printf(\"Test starts.\\n\");\n sleep(1);\n printf(\"Test ends.\\n\");\n\n return 1;\n}\n```"}, {"role": "assistant", "content": "Try this at the top:\n\n```\n#ifdef __unix__\n# include \n#elif defined _WIN32\n# include \n#define sleep(x) Sleep(1000 * (x))\n#endif\n```\n\nThis code will allow you to use two different functions under the same name, that do quite the same thing. And it compiles under different platforms.\n\nAlso, parenthesizing the(x)argument ensures that the delay is right even if someone calls it like thissleep(10+10)"}]} {"messages": [{"role": "user", "content": "I try to execute mysql query passing variable. Here is my code\n\n```\nchar str[100] = \"My String\";\n\nmysql_query(conn, printf(\"INSERT INTO table VALUES %s\"), str);\n```\n\nI get that warning during compile process\n\n```\nwarning: passing argument 2 of ‘mysql_query’ makes pointer from integer without a cast\n```\n\nWhat I miss ?"}, {"role": "assistant", "content": "Extending @ckruse's answer, you should take care to usemysql_real_escape_string()if your string comes from arbitrary sources.\n\n```\nint insert_data(MYSQL * mysql, char * str, int len)\n{\n if (len < 0) {\n len = strlen(str);\n }\n\n char esc[2*len+1];\n unsigned long esclen = mysql_real_escape_string(mysql, esc, str, len);\n\n char statement[512];\n snprintf(statement, sizeof statement, \"INSERT INTO table VALUES ('%s')\", esc);\n return mysql_query(mysql, statement);\n}\n```\n\n(An alternative could bemysql_hex_string()if dealt with correctly.)"}]} {"messages": [{"role": "user", "content": "This question already has answers here:Closed11 years ago.\n\nPossible Duplicate:Double Negation in C++ code\n\nWhile reading one code I read:\n\n```\nflush = ! !(flags & GST_SEEK_FLAG_FLUSH);\n```\n\nI am not getting what does!!mean here .\nwhat does this sentence do?\n\nEDIT:\n\nI got it its adouble-negative.trick to convert non-bool data to bool\n\nBut what is the need of that?Here flush is bool then if you assign any non zero item to bool it will treat as 1 and zero item as 0 so whats benefit of doing this?"}, {"role": "assistant", "content": "It's a double-negative. It's a way of converting an otherwise-non-bool expression (such asflags & GST_SEEK_FLAG_FLUSH) to abool. I personally prefer:\n\nflush = (flags & GST_SEEK_FLAG_FLUSH) != 0;"}]} {"messages": [{"role": "user", "content": "I have a function as such:\n\n```\nint foo(void *val){\n(char *)val=\"Long String\";\nreturn 0;\n}\n```\n\nThis function is called like:\n\n```\nchar str[25];\nfoo(str);\nprintf(\"%s\",str);\n```\n\nI get nothing printed out for some reason. what is wrong here?"}, {"role": "assistant", "content": "You are not actually copying the data around like you think you are. All you are doing is changing the parameter value to point at a different memory address. The parameter is being passed by value, so any change to it is not reflected in the calling code. For what you are attempting, you need to usestrcpy()orstrncpy()instead, eg:\n\n```\nint foo(char *val)\n{ \n strcpy(val, \"Long String\");\n return 0; \n}\n```\n\nOr:\n\n```\nint foo(char *val, int maxlen)\n{ \n strncpy(val, \"Long String\", maxlen);\n return 0; \n}\n```"}]} {"messages": [{"role": "user", "content": "The standard predefined macro__FILE__available in C shows the full path to the file. Is there any way to shorten the path and get just the filename? I mean instead of\n\n```\n/full/path/to/file.c\n```\n\nI see\n\n```\nto/file.c\n```\n\nor\n\n```\nfile.c\n```"}, {"role": "assistant", "content": "Try\n\n```\n#include \n\n#define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)\n```\n\nFor Windows use '\\\\' instead of '/'."}]} {"messages": [{"role": "user", "content": "I have a Xilinx Virtex-II Pro FPGA board that is attached via RS232 to an iRobot Create.\n\nThe iRobot takes a stream of byte integers as commands.\n\nI've found that printf will actually send over the serial port (Hypterminal is able to pick up whatever I print), and I figure that I can use printf to send my data to the iRobot.\n\nThe problem is that printf seems to format the data for ascii output, but I'd REALLY like it to simply send out the data raw.\n\nI'd like something like:\n\n```\nprintf(%x %x %x, 0x80, 0x88, 0x08);\n```\n\nBut instead of the hexadecimal getting formatted, I'd like it to be the actual 0x80 value sent.\n\nAny ideas?"}, {"role": "assistant", "content": "Usefwrite:\n\n```\nchar buf[] = { 0x80, 0x80, 0x80 };\n\nfwrite(buf, 1, sizeof(buf), stdout);\n```\n\nYou can write to any file handle;stdoutis just an example to mirror yourprintf.\n\nOn a Posix system, you can also use the platform-specificwritefunction that writes to a file descriptor."}]} {"messages": [{"role": "user", "content": "Is there any way to convert C/C++ to Assembly not to HEX.\n\nNot like something that gcc or other compiler done(C/C++ --> ASM --> HEX).\n\nOnly Convert It to ASM.\n\nIs there any way to do it by gcc,I mean stop compiler when translate C/C++ to ASM?\n\nwith special thanks for your attention,and so sorry for my basic question"}, {"role": "assistant", "content": "Use the-Soption of gcc, for example:\n\n```\ngcc -S hello.c\n```\n\nThis will give you a filehello.swith assembly instructions."}]} {"messages": [{"role": "user", "content": "I'm new to programming in Objective-C, though I do have some experience in Python. I wrote this (what I thought would be simple) program:\n\n```\n#include \nint main(){\n printf(\"hello world\\n\");\n return 0;\n}\n```\n\nBut when I click run in Xcode it gives me this error:\n\nCommand /Developer/usr/bin/clang failed with exit code 1\n\nI don't know what I did wrong and was hoping someone could help. It executes from the command line but not from Xcode."}, {"role": "assistant", "content": "Like other commenters here, I can't see any direct problem with your code, so maybe you could get it to work if you start from a clean project template.\n\nIn Xcode, choose New Project, type Command line tool\n\nYou can select either straight C or Objective-C. The latter will give you an autorelease pool that you don't need for a Hello World program, but it doesn't harm, either.\n\nThen type your code (printf(\"Your text\\n\")) into the main function and compile.\n\nIt should work."}]} {"messages": [{"role": "user", "content": "I feel this might be a weird/stupid question, but here goes...\n\nIn the questionIs NULL in C required/defined to be zero?, it has been established that theNULLpointer points to an unaddressable memory location, and also thatNULLis0.\n\nNow, supposedly a 32-bit processor can address2^32memory locations.\n\n2^32is only the number of distinct numbers that can be represented using32bits. Among those numbers is0. But since0, that is,NULL, is supposed to point to nothing, shouldn't we say that a 32-bit processor can only address2^32 - 1memory locations (because the0is not supposed to be a valid address)?"}, {"role": "assistant", "content": "If a 32-bit processor can address 2^32 memory locations, that simply means that a C pointer on that architecture can refer to 2^32 - 1 locations plusNULL."}]} {"messages": [{"role": "user", "content": "First I declare a class:\n\n```\nclass Op(var x : Int) {\n def +++(op: Op) = {\n println(this.x + \" +++ \" + op.x)\n this.x += op.x\n this\n } \n def ***(op: Op) = {\n println(this.x + \" *** \" + op.x)\n this.x *= op.x\n this\n }\n}\n```\n\nNow I execute the expression in REPL:\n\n```\nop1 +++ op2 +++ op3 *** op4\n```\n\nand it outputs\n\nBut why doesn't the method***go first? Isn't the priority of***higher than+++? And how about Java and C? Is it the same as in Scala?"}, {"role": "assistant", "content": "```\nop1 +++ op2 +++ op3 *** op4\n```\n\nis equivalent to\n\n```\n((op1 +++ op2) +++ (op3 *** op4))\n```\n\nsince method calls are left-associative. Thus first(op1 +++ op2)is evaluated, since it's the first operand to the second+++. Then the second operand,(op3 *** op4)is evaluated. And finally, the outermost operator is evaluated.\n\nThe same would be true forop1 + op2 + op3 * op4in C or Java."}]} {"messages": [{"role": "user", "content": "I'm attempting to run an event loop from within a pthread but I've run into a problem I can't seem to google-fix. Basically, it looks like this:\n\n```\nevent_thread = pthread_create(&event_thread, NULL, \n (void *) g_main_loop_run, (void *) event_loop);\n\nprintf(\"GOT HERE\\n\");\n```\n\nThe message below pthread_create never prints, is there a way to \"fire and forget\" a thread?"}, {"role": "assistant", "content": "Well, figured that one out as soon as I posted this, here's what I ended up doing:\n\n```\npthread_attr_t attr;\n...\npthread_attr_init(&thread_attr);\npthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);\nevent_thread = pthread_create(&event_thread, &thread_attr, \n (void *) g_main_loop_run, (void *) event_loop);\n```\n\nYou just need to set the threads state to \"detached\"."}]} {"messages": [{"role": "user", "content": "I'm having trouble understanding what this line of code does:\n\n```\nsprintf(obj, \"%s.o\", root);\n```\n\nobj and root are both character buffers, from what I read root is basically copied to obj?\nI'm not sure what \"%s.o\" is doing. %s is to specify a String but the .o?\n\nthanks for any help"}, {"role": "assistant", "content": "The%swill be replaced with the contents ofroot, and followed by the.opart of the string, which is just an \"additional\" text. For example, ifroothas \"file\",objwill be set to \"file.o\"."}]} {"messages": [{"role": "user", "content": "This question already has answers here:Closed11 years ago.\n\nPossible Duplicate:Using C/Pthreads: do shared variables need to be volatile?\n\nIn Linux/C: Do the global variables shared between threads need to be declared volatile (assume the variable get modified in one of the threads)?\n\nWhat all situations do I need to declare a variable as volatile in threads?"}, {"role": "assistant", "content": "If you are using pthreads, then no -volatileis neither necessary nor sufficient for correct synchronisation. If your accesses to the global variable are properly protected by a mutex (or another synchronisation primitive), then you can simply declare them as ordinary variables."}]} {"messages": [{"role": "user", "content": "Please highlight the difference between the following function declarations:\n\nvoid (*p) (void *a[], int n)void *(*p[]) (void *a, int n)"}, {"role": "assistant", "content": "void (*p) (void *a[], int n)definesa pointer to a function that takes avoid*array and anintas parametervoid *(*p[]) (void *a, int n)definesan array of pointers to functions that return avoid*, and take avoid*and anintas parameter."}]} {"messages": [{"role": "user", "content": "My MacBookPro, running BootCamp, has an Intel i7-640M processor, which has 2 cores. Like all the other i7 chips, each core is hyperthreaded, so you can have up to 4 threads. Using Visual Studio 2010 c/c++ to determine these:\n\n```\ncoresAvailable = omp_get_num_procs ( );\nthreadsAvailable = omp_get_max_threads ( ) ;\n```\n\nThe \"threadsAvailable\" comes back with a value of 4, as expected. But \"coresAvailable\" also is reported as 4.\n\nWhat am I missing?"}, {"role": "assistant", "content": "omp_get_num_procsreturns the number of CPUs the OS reports, and since a hyperthreaded core reports itself as 2 CPUs, a dual-core hyperthreaded chip will report itself as 4 processors.\n\nomp_get_max_threadsreturns the most threads that will be used in a parallel region of code, so it makes sense that the most threads it will use will be the number of CPUs available."}]} {"messages": [{"role": "user", "content": "This may sounds a little trivial but I really dont get it.\n\nTheProjectView(Left side of the screen) displays all files of your project. You are able to create and delete files but you can't move files to different folders (I'm familar with MSVC).\n\nIs there a way of moving source files in Kdevelop?"}, {"role": "assistant", "content": "I wonder the same thing-- I always manually create a new 'src' folder and manually move the source files into the new folder. Then I edit the cmake file to compile the sources in the src folder."}]} {"messages": [{"role": "user", "content": "There is a piece of C code\n\n```\nint i, j = 0;\nfor (i = 0, j = n-1; i < n; j = i++) {\n // array operations\n}\n```\n\nthat I'm trying to convert into Lua code\n\n```\nlocal j = n-1\nfor i = 1, n do -- arrays are 1-based in Lua\n -- array operations\n j = i+1\nend\n```\n\nbut for some reason Lua code doesn't work. Am I getting that C loop right?"}, {"role": "assistant", "content": "Imagine an array as a circular buffer.iis the current item andjis always the previous one:\n\n```\nn = 5\nlocal j = n\nfor i = 1, n do -- arrays are 1-based in Lua\n -- array operations\n io.write('i=', i, ' j=', j, '\\n')\n j = i\nend\n```\n\nDemo:\n\n```\ni=1 j=5\ni=2 j=1\ni=3 j=2\ni=4 j=3\ni=5 j=4\n```"}]} {"messages": [{"role": "user", "content": "Is there a way to convert cvMat to cvMAt* in opencv?\nI basically have to convert a Mat object to cvMat*. So initially I convert the Mat object to a cvMat object. Now, I need to convert it into a cvMat* pointer."}, {"role": "assistant", "content": "This isn't an OpenCV question, it's basic C. If you're this unfamiliar with C, perhaps you should try some other solution.\n\nThat said, converting fromObject somethingtoObject *somethingis as easy as passing&somethingto the function you're calling."}]} {"messages": [{"role": "user", "content": "I have a C library that isnotthreadsafe -- and probably will never be. I'm calling it from C# with PInvoke and that's working out quite nicely.\n\nNow that C library has to be called from a C# program that certainly is multi-threaded. I can manage this in the C# by having each instance of the C code called from separate AppDomains, except that doesn't seem to be working out very well. I'm still getting a lot of cross-thread problems in the C library.\n\nWill AppDomains isolate the C code mess (globals, etc..) from each other or no? If not, what will?"}, {"role": "assistant", "content": "No, AppDomains will not help. If you call into your C lib concurrently, it doesn't matter which AppDomain the calls come from.\n\nIf the C lib is not thread-safe, you will have to serialize access to it. Actually, having multiple AppDomains makes this harder - you will have to synchronize across the domains."}]} {"messages": [{"role": "user", "content": "I have a question about the buffering in standard library for I/O:\nI read \"The Linux Programming Interface\" chapter 13 about File I/O buffering, the author mentioned that standard library used I/O buffering for disk file and terminal.\nMy question is that does this I/O buffering also apply to FIFO, pipe, socket and network file?"}, {"role": "assistant", "content": "Yes, if you're using theFILE *based standard I/O library. The only odd thing that might happen is if the underlying system file descriptor returns non-zero for theisattyfunction. Then stdio might 'line buffer' both input and output. This means it tends to flush when it sees a'\\n'.\n\nI believe that it's required to line bufferstdoutif file descriptor 1 returns non-zero forisatty."}]} {"messages": [{"role": "user", "content": "Im really new to C and just got Codeblocks to compile/run any code that I write and I can't make it run this block of code.\n\n```\n#include \n\nint main() {\n printf(\"\\nHello, world!\\n\");\n return 0;\n}\n```\n\nIf someone could list out how to make it do something it would really be appreciated\n\n(Maybe its just me but it seems like theres alot going on, I mean theres alot of shiny buttons)"}, {"role": "assistant", "content": "Select File->New->Project from the menu\n\nFrom the \"New from template\" window, select \"Console application\"\n\nRun through the wizard and give your project a title. (Select defaults if you don't know what to set)\n\nFrom the workspace manager (shift+F2), expand the dropdown through your project,the sources folder, and select main.cpp\n\nCopy your code into the pre-built main.cpp file.\n\nFrom the top menu, select Build, and then the \"Build and Run\" option.\n\nAnd that should do it."}]} {"messages": [{"role": "user", "content": "I am trying to make a mini shell where commands are piped to each other. At some points in the code I do:\n\n```\nclose(1) //closing stdout\n```\n\nand\n\n```\nclose(0) //closing stdin\n```\n\nHowever later on I am forking so I want my new subprocess to reset everything. So how would I:\n\n```\n*function_name_here*(1) //reopening stdout\n```\n\nand\n\n```\n*function_name_here*(0) //reopening stdin\n```"}, {"role": "assistant", "content": "If you're on a UNIX-type system (and you most likelyareif you're callingfork), you can generally do one of two things.\n\nThe first is to open/dev/ttywhich will give you access to your terminal device (assuming the terminal device is what you want rather than the original file handle).\n\nThe second is todupthat file handle before you close it so you have a usable copy. Then, you can usedup2to get it back. Details for Linuxhere, or you could also executeman duporman dup2."}]} {"messages": [{"role": "user", "content": "When I compile my code I am getting a unknown Opcode '.pword' error. The only line of code in my project that has .pword is:\n\n```\ndo {\n __asm__ volatile (\" .pword 0xDA4000\");\n Nop();\n} while(0)\n```\n\nCommenting the line out does nothing.\n\nI searched.pword 0xDA4000and know it is supported by the IDE MPLab for PICs.\n\nIn my case the IDE I am using is CrossStudio for a STMf32f2xx chip.\n\nI have the updated CrossStudio which comes with binutils 2.21 and gcc 4.6.0\n\nI initially had a problem with compiling unnamed structs and unions but adding-fms-extensionsinto additional C compiler options fixed it.\n\nI dont know if I need to do something similar to fix Opcode '.pword' error.\n\ncould it just be that .pword is only a PIC opcode?"}, {"role": "assistant", "content": "In MPLAB ASM30 assembler the.pworddeclare 24 bit constant in code memory. It can be also any MPLAB ASM30 instruction.\n\nCheck:MPLAB ASM30 assembler"}]} {"messages": [{"role": "user", "content": "It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago.\n\nHow to take some unknown number of integers from input and display them on the console?\n\nThe number of values will be given through console."}, {"role": "assistant", "content": "Well the prototype for main is:\nmain(void) or\nmain(int argc, char *argv[]);\n\nThis are the command line arguments of the program \nyou can iterate through them with something along this lines\n\n```\nint i = 0;\n for (i=0; i < argc; i++) {\n printf(\"%s\" argv[i]);\n}\n```\n\nUntested but should be enough to get you going."}]} {"messages": [{"role": "user", "content": "Having the signature of the function :\n\n```\nint my_print(const char *format, ...);\n```\n\nI want to implement it by callingprintfwith arguments passed tomy_printandfflush(stdout);\n\nWhat do you think the best way to implement it?"}, {"role": "assistant", "content": "You can usevprintf. It accepts ava_list, which is what you get inmy_print:\n\n```\nint my_print(char * format, ...)\n{\n va_list args;\n va_start (args, format);\n int ret = vprintf (format, args);\n va_end (args);\n return ret;\n}\n```"}]} {"messages": [{"role": "user", "content": "```\n-(IBAction)enterVeryBasics:(id)sender {\n VeryBasics *enterIntro = [[VeryBasics alloc]initWithNibName:Nil bundle:Nil];\n [self presentModalViewController:enterIntro animated:YES];\n [enterIntro release];\n}\n```\n\nI have this code here, and on[self presentModalViewController:enterIntro animated:YES];it's giving me a SIGABRT\n\nI have multiple other actions in the same .m file, but they aren't having the same problem."}, {"role": "assistant", "content": "Look at UIViewController Class reference instance method signature:\n\n```\n- (void)presentModalViewController:(UIViewController *)modalViewController animated:(BOOL)animated\n```\n\nIs your VeryBasics is Subclass of UIViewController ? It doesn't look like from your code."}]} {"messages": [{"role": "user", "content": "Is it possible to pass the data from CPU to GPU without explicitly passing it as a parameter?\n\nI don't want to pass it as a parameter primarily for syntax sugar reasons - I have about 20 constant parameters I need to pass, and also because I successively invoke two kernels with (almost) same parameters.\n\nI want something along the lines of\n\n```\n__constant__ int* blah;\n\n__global__ myKernel(...){\n ... i want to use blah inside ...\n}\n\nint main(){\n ...\n cudaMalloc(...allocate blah...)\n cudaMemcpy(copy my array from CPU to blah)\n\n}\n```"}, {"role": "assistant", "content": "cudaMemcpyToSymbolseems to be the function you're looking for. It works similarly tocudaMemcpy, but with an additional 'offset' argument which looks like it'll make it easier to copy across 2D arrays.\n\n(I'm hesitant to provide code, since I'm unable to test it - but seethis threadandthis postfor reference.)"}]} {"messages": [{"role": "user", "content": "Are there any size limitations for C structures?"}, {"role": "assistant", "content": "From the C standard:\n\n5.2.4.1 Translation limits1 The implementation shall be able to translate and execute at least\n one program that contains at least one instance of every one of the\n following limits:...\n — 65535 bytes in an object (in a hosted environment only)... \n — 1023 members in a single structure or union... \n — 63 levels of nested structure or union definitions in a single\n struct-declaration-list\n ...\n 13) Implementations should avoid imposing fixed translation limits\n whenever possible.\n\nOther than that, the upper bound isSIZE_MAX(maximum value forsize_t)."}]} {"messages": [{"role": "user", "content": "What I am trying to do is have the C preprocessor output#ifdef,#else, and#endifdirectives. That is, I would like to somehow \"escape\" a directive so that the output of the preprocessor includes the directive were the preprocessor to run on the output.\n\nIs it possible to \"escape\" a CPP directive so that it is outputted by the preprocessor such that the output of an escaped directive would be a preprocessor directive if the CPP output were to be itself preprocessed?"}, {"role": "assistant", "content": "A slight variant ofMarcelo Cantos's answerworks for me on GNU cpp 4.4.3:\n\n```\n#define HASH(x) x\n\n...\n\nHASH(#)ifdef __cplusplus\nclass foo { };\nHASH(#)endif\n```"}]} {"messages": [{"role": "user", "content": "How do you define constant array of constant objects in C (not C++)?\n\nI can define\n\n```\nint const Array [] = {\n /* init data here */\n};\n```\n\nbut that is a non-constant array of constant objects.\n\nI could use\n\n```\nint const * const Array = {\n /* init data here */\n};\n```\n\nand it would probably work.\nBut is it possible do this with array syntax? (Which looks more clean)"}, {"role": "assistant", "content": "An array cannot be \"constant\" -- what is that even supposed to mean? The array size is already a compile-time constant in any case, and if all the members are constants, then what else do you want? What sort of mutation are you trying to rule out that is possible for aconst int[]?"}]} {"messages": [{"role": "user", "content": "Om mac OS 10.6.7, I am creating some files in the temp directory. After a while I start getting failure in open syscall and error returned is 24 which means disk full. I checked the disk space and still 80GB is available. Are there any restrictions or special quota on temporary directory? I used following flags to open the file:\nopen(path, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR)\n\nThe RAM usage is fairly high during this point, (around 90%), but I dont think it should affect the file open especially when it says disk full as the returned error.\n\nDid anyone face such a situation?"}, {"role": "assistant", "content": "Error 24 is EMFILE meaning too many open files."}]} {"messages": [{"role": "user", "content": "```\nvoid DoSomeThing(CHAR parm[])\n{\n\n}\n\nint main()\n{\n DoSomeThing(NULL);\n}\n```\n\nIs the passing NULL for array parameter allowed in C/C++?"}, {"role": "assistant", "content": "What you cannot do is pass an array by value. The signature of the function\n\n```\nvoid f( char array[] );\n```\n\nis transformed into:\n\n```\nvoid f( char *array );\n```\n\nand you can always pass NULL as argument to a function taking a pointer.\n\nYou can however pass an array by reference in C++, and in that case you will not be able to pass a NULL pointer (or any other pointer):\n\n```\nvoid g( char (&array)[ 10 ] );\n```\n\nNote that the size of the array is part of the type, and thus part of the signature, which means thatgwill only acceptlvalue-expressionsof typearray of 10 characters"}]} {"messages": [{"role": "user", "content": "Look at the following two codes, and tell me the reason why answers vary a lot.\n\n```\n#include\nint main() {\n float a = 0.9;\n if(a<0.9)\n printf(\"hi\"); // This will be the answer\n else\n printf(\"bye\");\n return 0;\n}\n```\n\nAnd if we change 0.9 to 0.8, then else's statement is printed:\n\n```\n#include\nint main() {\n float a = 0.8;\n if(a<0.8)\n printf(\"hi\");\n else\n printf(\"bye\");//this will be the answer\n return 0;\n}\n```\n\nSo why this output changes when we just change a single digit?"}, {"role": "assistant", "content": "This error is due to floating point accuracy and because you are comparing afloattype with adoublevalue. Try to compare it versus floating point literals:if(a<0.8f)\n\nI suggest you read the accordingwikipedia article, it explains in detail why your error happens."}]} {"messages": [{"role": "user", "content": "I can't figure out how to set default value for integer in structure. For example\n\n```\ntypedef struct {\n char breed[40];\n char coatColor[40];\n int maxAge = 20;\n } Cat;\n```\n\nThe code above gives me an error on execution - Expected ';' at end of declaration list"}, {"role": "assistant", "content": "You cannot specify default values in C. What you probably want is an 'init' style function which users of your struct should call first:\n\n```\nstruct Cat c;\nCat_init(&c);\n\n// etc.\n```"}]} {"messages": [{"role": "user", "content": "I have used fork() to create 2 different processes operating on 2 different address spaces.\nNow, in parent process I need the value of a variable from child's address space or if the child process can modify the variable in parent's address space.\nIs this possible?"}, {"role": "assistant", "content": "No, once you've forked, each process gets itsownaddress space and you'll have to look into either:\n\nsome form of IPC between the processes to access each others data (such as shared memory or message queues).some more lighweight variant of fork that allows sharing of data (including possibly threading)."}]} {"messages": [{"role": "user", "content": "I want to write a program that checks for the existence of a directory; if that directory does not exist then it creates the directory and a log file inside of it, but if the directory already exists, then it just creates a new log file in that folder.\n\nHow would I do this in C with Linux?"}, {"role": "assistant", "content": "Look atstatfor checking if the directory exists,\n\nAndmkdir, to create a directory.\n\n```\n#include \n#include \n#include \n\nstruct stat st = {0};\n\nif (stat(\"/some/directory\", &st) == -1) {\n mkdir(\"/some/directory\", 0700);\n}\n```\n\nYou can see the manual of these functions with theman 2 statandman 2 mkdircommands."}]} {"messages": [{"role": "user", "content": "Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed7 years ago.Improve this question\n\nI am looking for a lightweight opensource library/framework preferably written in C/C++ (it doesn't have to support x languages and should be easy to understand and use.) which can be used to make RPC over internal linux sockets or pipes.\nIn other words I am looking for an RPC possibility which can be run over some of the linux IPC mechanisms.\n\nThanks"}, {"role": "assistant", "content": "Look atmsgpack-rpc. It's easy and very simple RPC implementation."}]} {"messages": [{"role": "user", "content": "```\nif(stat(\"seek.pc.db\", &files) ==0 )\n sizes=files.st_size;\n\nsizes=sizes/sizeof(int);\nint s[sizes];\n```\n\nI am compiling this in Visual Studio 2008 and I am getting the following error: \nerror C2057: expected constant expression\nerror C2466: cannot allocate an array of constant size 0.\n\nI tried using vector s[sizes] but of no avail. What am I doing wrong?\n\nThanks!"}, {"role": "assistant", "content": "The sizes of array variables in C must be known at compile time. If you know it only at run time you will have tomallocsome memory yourself instead."}]} {"messages": [{"role": "user", "content": "Why this code does not work ?\n\n```\n#include \n#include \nint main() {\n printf(\"%X\", 1327644190303473294);\n}\n```\n\nI am getting o/p5f264e8e\n\nbut expected o/p is126cbd5b5f264e8eas given by below php script\n\n```\n\n```"}, {"role": "assistant", "content": "format '%X' expects type 'unsigned int', but argument 2 has type 'long int'\n\n```\n#include \n\nint main(void) {\n printf(\"%lX\",1327644190303473294);\n return 0;\n}\n```\n\noutputs\n\n```\n126CBD5B5F264E8E\n```"}]} {"messages": [{"role": "user", "content": "Does Macports have Ch and Cint (C interactive interpreters) as available ports? I can't seem to find them through port search.\n\nFailing which, can anyone recommend what is the easiest way to install either Ch or Cint on Mac OS X?"}, {"role": "assistant", "content": "There is an effort by CERN developers to port their Cint to Clang: nicely namedClint.\n\nAlthough I think CINT works fine on Mac: seeherefor build/install instructions"}]} {"messages": [{"role": "user", "content": "Why does this program below not show any error ?\n\n```\nint main (void) {\n \"ANGUS\";\n 1;\n 3.14;\n return 0;\n}\n```"}, {"role": "assistant", "content": "Each of those statements are expressions that evaluate to a value, which is then discarded.\nCompare it to if you called a function that returned an int, a char or a float, without using the return value. That's also an expression that evaluates to a value.\n\nIt is not uncommon to have functions that return values that the caller may or may not be interested in, like for example whereprintf(\"%d\", 9001)returns the number of characters printed. A caller can use the number returned, or they can just ignore it.\n\nIf the compiler complained whenever you ignored a return value, you'd have a very noisy build log. Some compilers however diagnose (if sufficient warning flags are enabled) such pointless side-effect-less uses of literals and variables."}]} {"messages": [{"role": "user", "content": "```\nint main()\n{\n unsigned int b;\n signed int a;\n char z=-1;\n b=z;\n a=z;\n printf(\"%d %d\",a,b);\n}\n```\n\ngives -1 -1. why does no sign extension occur, ALSO, when does it occur?"}, {"role": "assistant", "content": "Sign extension DID occur, but you are printing the results incorrectly. In your printf you specified%dforb, butbis unsigned, you should have used%uto printb.\n\nprintf does not know the type of its arguments and uses the format specifies to interpret them.\n\n```\nprintf(\"%d %u\",a,b);\n```"}]} {"messages": [{"role": "user", "content": "The below code runs in an infinte loop. \n'i' has been intialised with the value 1 and then compared with 0.\n\nSo printf() stmt should execute once but it runs infinetly.\n\n```\nunsigned int i = 1;\nfor (; i >= 0; i--) {\n printf(\"Hello: %u\\n\",i);\n}\n```\n\nplease explain this behaviour."}, {"role": "assistant", "content": "Becauseiisunsignedit can't go negative, soi>=0is always true.\n\nWheniis zero and you doi--, the value ofiwraps round to themaximumvalue anunsigned intcan have (which is greater than zero).\n\nYou should use a signed integer, by removing theunsignedmodifier."}]} {"messages": [{"role": "user", "content": "what is the purpose of signed char if both char and signed char ranges from -127 - 127?\nwhat is the place where we use signed char instead of just char?"}, {"role": "assistant", "content": "unsigned charis unsigned.signed charis signed.charmay be unsignedorsigned depending on your platform.\n\nUsesigned charwhen you definitely want signedness.\n\nPossibly related:What does it mean for a char to be signed?"}]} {"messages": [{"role": "user", "content": "How to call a varargs function via dbus, like printf?\n\nThe server is written in C, the client is written in Python.\n\nMy questions are how to write the XML spec file? And how to write my GObject?\n\nThanks in advance.\n\n[I use DBus-GLib.]"}, {"role": "assistant", "content": "There is no way to call a variadic function programmatically with varying number and type of arguments. You could use the corresponding \"v\" functions (vprintfetc.) but there's no way to make theva_listto pass to them from foreign code and pass it over DBus.\n\nIn any case you really need to rethink your design. It's unsafe to callprintfwith a format string that's not 100% controlled by your program. Passing a client-provided format string is a formula for disaster, becauseprintfinvokesundefined behaviorif the format string does not match the arguments. In nearly all real-world situations,this will mean privilege elevation vulns!"}]} {"messages": [{"role": "user", "content": "What will be printed as the result of the operation below:\n\n```\nx=5; \nprintf(\"%d,%d,%d\\n\",x,x<<2,x>>2);\n```\n\nAnswer: 5,20,1\n\nI thought order is undefined yet I found above as interview question on many sites."}, {"role": "assistant", "content": "From the C++ standard:\n\nThe order of evaluation of arguments is unspecified. All side effects of argument expression evaluations take effect before the function is entered. The order of evaluation of the postfix expression and the argument expression list is unspecified.\n\nHowever, your example would only have undefined behavior if the arguments werex>>=2andx<<=2, such that x were being modified."}]} {"messages": [{"role": "user", "content": "I know that #define replaced before the compiling to real values. so why the first code here compile with no error, and the 2nd not?\n\nthe 1st;\n\n```\n#include \n#include \nint main()\n{\n printf(\"bc\");\n return 0;\n}\n```\n\nthe 2nd(not working);\n\n```\n#include \n#include \n#define Str \"bc\";\nint main()\n{\n printf(Str);\n return 0;\n}\n\nerror: expected ')' before ';' token\n```\n\nthank you for the answers, and sorry about my poor English..."}, {"role": "assistant", "content": "Because theStrmacro evaluates to\"bc\";— the semicolon is included. So your macro expands to:\n\n```\nprintf(\"bc\";);\n```\n\nYou do not need to follow a #define with a semicolon. They end at a newline, rather than at the semicolon like a C statement. It is confusing, I know; the C preprocessor is a strange beast and was invented before people knew better."}]} {"messages": [{"role": "user", "content": "I'm trying thegetoptAPI:\n\nhttp://www.gnu.org/s/hello/manual/libc/Example-of-Getopt.html#Example-of-Getopt\n\nBut I find it only supports options in the middle?\n\nAs I find that it's judgingargv[optind]toargv[argc-1]as non-opt arguments.\n\nIs that the case?"}, {"role": "assistant", "content": "GNU getopt allows options anywhere on the command line. It re-ordersargvwhen parsing, though. You can verify this by saving the example code in a file, compiling it, and running the result:\n\n```\n./a.out\n./a.out -a\n./a.out foo\n./a.out -a foo\n./a.out foo -a\n```\n\nThe last two will give the same results."}]} {"messages": [{"role": "user", "content": "How do I get the local IP address before usingsendto()that is going to be used for the transmission to a remote host?\n\nIf I understand correctly, it should be known already aftergethostbyname(remoteHostname)call.\n\nI need this for including the local IP in the transmitted packet (127.0.0.1 wouldn't make sense). UDP is used."}, {"role": "assistant", "content": "Try callinggetsockname(2)on a connected UDP socket; the stack would need to perform a fair amount of routing to connect the socket, sufficient to know which local address would be used once packets are sent or received."}]} {"messages": [{"role": "user", "content": "If I have two or more computers on a LAN communicating via UDP, do they all have to be using the same port to be able to receive messages from one another? For example, say my desktop is using port 1550 to send a message and my notebook, which is also on the LAN, is using port 3746 to listen for and receive messages. Would sending using just the destination IP in such a situation work? If not, would each computer have to know and specify the receiver's port?"}, {"role": "assistant", "content": "For a UDP or TCP endpoint an address and port must be set. The initiator must know what address-port to send to. The receiver can use the getpeername() call to determine the address-port combination of the sender and then use this information to build up the address structure for a reply message. The two do not need to use the same port number."}]} {"messages": [{"role": "user", "content": "This question already has answers here:Closed12 years ago.\n\nPossible Duplicate:Is there a printf converter to print in binary format?\n\nHere is my program\n\n```\n#include\nint main ()\n{\n int i,a=2;\n i=~a;\n printf(\"a=%d\\ni=%d\\n\",a,i);\n\n return 0;\n}\n```\n\nThe output is\n\n```\na=2\ni=-3\n```\n\nI want this to print in binary. There are %x, %o, and %d which are for hexadecimal, octal, and decimal number, but what is for printing binary in printf?"}, {"role": "assistant", "content": "printf() doesn't directly support that. Instead you have to make your own function.\n\nSomething like:\n\n```\nwhile (n) {\n if (n & 1)\n printf(\"1\");\n else\n printf(\"0\");\n\n n >>= 1;\n}\nprintf(\"\\n\");\n```"}]} {"messages": [{"role": "user", "content": "There are many example thread based web servers online, but I haven't really seen anything that gives a good example of an event-loop based one (without being very complex, e.g. lighttp and nginx).\n\nAre there any? If not, what should I read/look at to help me learn how to make a server of this sort? (This includes asynchronous IO in C, etc.)\n\nI already understand the basics of how event-loop based programming works, especially in higher level languages like Python, but I need to be able to implement one in C."}, {"role": "assistant", "content": "Here is onewhich is part ofTupleServersource that useslibevent."}]} {"messages": [{"role": "user", "content": "I'm writing a simple shell in C and I want to implement the user input the same way the other shells do, or at least how bash does (never used others). If you enter a command with random whitespace then it can still run the command:\n\nex.\n\nls -1\n\nObviouslystrtok()wont work on this when separating the command and args...\n\nHow does bash do this? Should I search through the thousands of lines of the source code?"}, {"role": "assistant", "content": "Youcanskip spaces while you're parsing your command:\n\n```\nwhile(*p==' '||*p=='\\t') ++p;\n```"}]} {"messages": [{"role": "user", "content": "I am writing a multithreaded program where I want to handle a possibleCtrl-Ccommand from the user to terminate execution. As far as I know there is no guarantee that the main thread, which is able to cancel every working thread, will catch the signal. Is it, therefore, necessary to have a different signal handler to the code of the working thread so that anyone will catch the signal if it arrives, or is there another way to do that with having a signal handler only in the main thread's code?"}, {"role": "assistant", "content": "You can block signals from the calling thread with pthread_sigmask().\n\nAnd, as the blocked signals are inherited to newly created threads, you can block SIGINT in the main thread, then launch your other threads, and then unblock it in the main thread, if that is preferable."}]} {"messages": [{"role": "user", "content": "select(2) (amongst other things) tells me whether I can write to a fd of a file without blocking. However, does it guarentee me that I can write a full 4096 bytes without blocking?\n\nNoteI am interested in normal files on disk. Not sockets or the like.\n\nIn other words: doesselectsignal when we can just write one single byte to a file fd without blocking,ordoes it signal when we can writen(4096, ... ?) bytes to a file fd without blocking."}, {"role": "assistant", "content": "Wheneverselect()indicates that your file is ready, you can try writing N bytes, for any N>0.write()will return the number of bytes actually written. If it equals N, you can write again. If it's less than N, then the next write will block.\n\nNoteNormal files on disk don't block. Sockets, pipes and terminals do."}]} {"messages": [{"role": "user", "content": "I need to deal with some data in the following form:\n\n```\ntypedef struct{\n unsigned n1 : 12;\n unsigned n2 : 12;\n unsigned n3 : 12;\n unsigned n4 : 1;\n unsigned n5 : 35;\n} data;\n```\n\nI made sure that in total they count up to 9 bytes.But they don't.. Writing 9 bytes of that struct to a file and reading it back doesn't restore all the data, andsizeof(data)returns 16.What's the problem here ?"}, {"role": "assistant", "content": "The problem is some padding is being added by the compiler for efficiency reasons.\n\nThis behavior can be overridden.\n\nFor how to do this with gcc seeforcing alignment in GCC\n\nFor how to do this with visual c++ see:forcing alignment in Visual C++"}]} {"messages": [{"role": "user", "content": "I'm a ruby developer and its been long time since I've coded in C. I want to use a datatype in C which behaves like a symbol.\n\nIs this possible?\n\nProgram asks user for nameUser replies - \"foobar\"Program declares an integer with the same name i.e.int foobar;"}, {"role": "assistant", "content": "Unlike in interpreted languages, C does not have a dictionary of variable names at runtime. There exist no variable names at runtime at all. Hence unfortunately it is impossible to do what you want in C."}]} {"messages": [{"role": "user", "content": "I often see source code using types like uint32, uint64 and I wonder if they should be defined by the programmer in the application code or if they are defined in a standard lib header.\n\nWhat's the best way to have these types on my application source code?"}, {"role": "assistant", "content": "The C99stdint.hdefines these:\n\nint8_tint16_tint32_tuint8_tuint16_tuint32_t\n\nAnd, if the architecture supports them:\n\nint64_tuint64_t\n\nThere are various other integer typedefs instdint.has well.\n\nIf you're stuck without a C99 environment then you should probably supply your own typedefs and use the C99 ones anyway.\n\nTheuint32anduint64(i.e. without the_tsuffix) are probably application specific."}]} {"messages": [{"role": "user", "content": "I am using the UNIXalarmsystem call to deliver a signal to the currently running process on a schedule.\n\nThe man page describes the argument to this function as being in units of seconds. I would like to have precision in milliseconds.\n\nIs there an alternative system call on UNIX (or Linux specifically) that will allow this?"}, {"role": "assistant", "content": "Take a look atsetitimer() or the more modern (and more flexible)timer_setitime() APIs."}]} {"messages": [{"role": "user", "content": "I want to read string from standart input and output it in on console. I use this way:\n\n```\nchar* cmdline;\n\ndo{\n scanf(\"%s\\n\", &cmdline);\n printf(\"%s\\n\", cmdline);\n}while(cmdline != \"quit\");\n```\n\nBut this doesn't work. I have this errorSegmentation fault (core dumped)"}, {"role": "assistant", "content": "```\nchar* cmdline\n```\n\nis a pointer. You are not allocating space for storing the string.\nYou should do:\n\n```\ncmdline = malloc(size_of_string);\n```\n\nfor allocating dynamic memory for storing the string.\nOtherwise use an array of char instead of a pointer:\n\n```\nchar cmdline[size_of_string];\n```"}]} {"messages": [{"role": "user", "content": "I see that there are several ways to distort an image. like...Circle, Diffuse, Marble, Ripple, Twirl, Water, ...\n\nI have come across some ipl functions like, iplRotateCenter(), iplWarpAffine(), iplShear() etc. does OpenCV have any such functions? if i need to use the ipl library in opencv, how to do it?"}, {"role": "assistant", "content": "Open CV has such functions.\nOld openCV (C inreface), methods like cvWarpPerspective(), cvRemap(), cvLogPolar()\nNew openCV (C++ inreface), methods like warpPerspective(), remap(),..."}]} {"messages": [{"role": "user", "content": "How can I install the C library in MinGW?\n\nI always get some error like when I want to run some scripts:\n\nCannot find Please ensure libClang is installed\n\nHow do I fix this problem?"}, {"role": "assistant", "content": "That library is available from theLLVMproject.clangis a \"a C language family frontend for LLVM.\" I don't believe they make binary releases yet. So, you would need to check out the code usingSubversion (SVN), and then build the library yourself under minGW. Please refer to the \"Getting Started: Building and Running Clang\" page for detailed instructions."}]} {"messages": [{"role": "user", "content": "A client requested that the MTU limit should be 1492.\n\nIs there a way to do it in the source code (program in C)?\n\nIs there any other way to do it in general? (ifconfig?)\n\nWhy does somebody needs to modify MTU to a certain limit? What is the benefit? And the most\nimportant: By changing the MTU is there any risk to break the code?"}, {"role": "assistant", "content": "Programmaticaly way using C:\n\n```\nint sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);\nstruct ifreq ifr;\nstrcpy(ifr.ifr_name, \"eth0\");\nif(!ioctl(sock, SIOCGIFMTU, &ifr)) {\n ifr.ifr_mtu // Contains current mtu value\n}\nifr.ifr_mtu = ... // Change value if it needed\nif(!ioctl(sock, SIOCSIFMTU, &ifr)) {\n // Mtu changed successfully\n}\n```\n\nIt works at least on Ubuntu, seeman netdevice."}]} {"messages": [{"role": "user", "content": "The below fails to compile:\n\n```\ntypedef int arr[10];\nint main(void) {\n return sizeof arr;\n}\n\nsizeof.c:3: error: expected expression before ‘arr’\n```\n\nbut if I change it to\n\n```\nsizeof(arr);\n```\n\neverything is fine. Why?"}, {"role": "assistant", "content": "According to 6.5.3, there are two forms forsizeofas the following:\n\n```\nsizeof unary-expression\nsizeof ( type-name )\n```\n\nSincearrin your code is atype-name, it has to be parenthesized."}]} {"messages": [{"role": "user", "content": "I am writing a multithreaded application and would like to pass around pointers to a struct.\n\nDo the structs in the struct need to be malloced or if the outer struct is malloced will it prevent the internal structs from being deleted or lost when passing around the pointer?\n\nStruct I am asking about is\n\n```\nstruct thread_data\n{\n position starttile;\n position destinationtile;\n char *message;\n};\n```\n\nwhere position is a struct itself that contains no pointers"}, {"role": "assistant", "content": "If the struct contains child structs, then it is generally all one block of memory. And so there would be no separate allocation.\n\nIf the struct instead contains pointers to structs, then my previous comment would not apply. In this case, it kind of depends on what you are doing.\n\nHad you considered posting a tiny bit of code so people would have a clue what you had in mind."}]} {"messages": [{"role": "user", "content": "I want to know how can I work with Bluetooth in android usingC/C++notJAVA APIif somebody have useful links or can give advice ?\n\nI foundthispost but I want to know if i gives complete information ?"}, {"role": "assistant", "content": "During my research I found this, and now I want somebody tell me what ishciattach,hcidand where to know how can I work inUserspace\n\nbluez: it provides 'hcid' daemon and it's responsible for all related bluetooth services\ndbus-daemon: the bridge between hcid and system serverD-Bus is a simple inter-process communication (IPC) system for software applications to communicate with one another.debug utility: d-feet (a dbus UI debugger ), dbus-monitor (debug probe to print message bus messages), dbus-send (Send a message to a message bus)bluez dbus API document: /mydroid/external/bluez/utils/hcid/dbus-api.txtone example as below\n\nHere isarticlethat gives all answers !"}]} {"messages": [{"role": "user", "content": "I need to parse a document in C language. I was about to use the strtok function but I don't know if it's the best method or if just a token system is enough (searching for \\n, space etc).\n\nThe structure of each line of the document is : element \\n element \"x\".\n\nthanks :-)"}, {"role": "assistant", "content": "Token system if fine,strtokis just an implementation of that. However, you're better off with usingstrtok_rwhich does not keep any internal state outside control of your program."}]} {"messages": [{"role": "user", "content": "my question is not a duplicate ofthisthe solution provided in the above does not work when using Nsight as a debugger.how can i view all the elements of an array inside a kernel when using Nsight as a debugger?QuickWhatch only shows the first 4 elements of the array!"}, {"role": "assistant", "content": "The number of elements NSight will copy to the host for debugging is set in:\n\nNsight->Nsight Options->Debugger->Max Array elements\n\nThe default is 4, which is why you only see 4 elements. Increase this (and restart your debugging session), and you will be fine."}]} {"messages": [{"role": "user", "content": "There is one var named \"users\" in one process and the process fork some child processes, I want know how could these child processes access the \"users\" variable ?\n\nBTW:The variable will be modified by parent process in runtime"}, {"role": "assistant", "content": "You want to use shared memory. You will needto opena file, usethisto set the length (probably sizeof(*var)),mmapit. Do this before the fork. After you are finishedunmap it,close the file, andunlinkthe shared file.\n\n```\nvoid *mem;\nint shm_fd;\nshm_fd = shm_open(\"file\", O_CREAT | O_RDWR, 0644);\nftruncate(shm_fd, sizeof(int));\nmem = mmap(0, sizeof(int), PROT_WRITE | PROT_READ, MAP_SHARED, shm_fd, 0);\n/* fork it, use it */\nmunmap(mem, sizeof(int));\nclose(shm_fd);\nshm_unlink(\"file\");\n```"}]} {"messages": [{"role": "user", "content": "Is there any way to create a user defined signals in Linux? My signal (signal number) should not match any of the existing signal numbers.\n\nIn other words, i want to create my own unique signal, which will be registered and caught by my handler.\n\nIs it possible? If yes, how?\n\nThanks in advance."}, {"role": "assistant", "content": "SIGRTMINthroughSIGRTMAX(these are not normally constants but macros which expand to functions evaluated at runtime) are available for whatever use you like, as areSIGUSR1andSIGUSR2. The former have additional realtime queueing support; the latter don't. Simply choose one to use."}]} {"messages": [{"role": "user", "content": "I want to declare a new integer in the heap,\n\n```\nint *intPtr = (int*) malloc(sizeof(int));\n```\n\nHow do I change the value of the space in the heap, to which*intPtrpoints to?\nThanks"}, {"role": "assistant", "content": "DereferenceintPtr:\n\n```\n*intPtr = 0;\n```"}]} {"messages": [{"role": "user", "content": "is there any simple way how to measure computing time in C? I tried time utility when executed, but I need to measure specific part of a program.\n\nThanks"}, {"role": "assistant", "content": "You can use theclockfunction inalong with the macroCLOCKS_PER_SEC:\n\n```\nclock_t start = clock() ;\ndo_some_work() ;\nclock_t end = clock() ;\ndouble elapsed_time = (end-start)/(double)CLOCKS_PER_SEC ;\n```\n\nNowelapsed_timeholds the time it took to calldo_some_work, in fractional seconds."}]} {"messages": [{"role": "user", "content": "```\nvoid CalculateFrameRate()\n{ \n static float framesPerSecond = 0.0f; // This will store our fps\n static float lastTime = 0.0f; // This will hold the time from the last frame\n float currentTime = GetTickCount() * 0.001f; \n ++framesPerSecond;\n if( currentTime - lastTime > 1.0f )\n {\n lastTime = currentTime;\n if(SHOW_FPS == 1) fprintf(stderr, \"\\nCurrent Frames Per Second: %d\\n\\n\", (int)framesPerSecond);\n framesPerSecond = 0;\n }\n}\n```\n\nShould I call this function invoid play(void)orvoid display(void)?\n\nOr it does not make any difference?"}, {"role": "assistant", "content": "You should put it in the display loop.Here'san article that explains some intricacies of game loops that you should read."}]} {"messages": [{"role": "user", "content": "I have some code that moves bytes in a buffer usingmemmove(). The buffer is accessed by multiple threads. I get a very weird behavior; sometimes the buffer it's not what it should be and I was thinking ifmemmove()or/andmalloc()are thread safe. I'm working on iOS (in case this is platform dependent)."}, {"role": "assistant", "content": "In an implementation that provides threads,mallocwill normally be thread safe (i.e., it will take steps to assure the heap doesn't get corrupted, even ifmallocgets called from multiple threads). The exact way it will do that varies: some use a single heap, and internal synchronization to ensure against corruption. Others will use multiple heaps, so different threads can allocate memory simultaneously without collisions.\n\nmemmovewill normally be just like if you did assignments in your own code -- if you're sharing a buffer across threads, it's your responsibility to synchronize access to that data."}]} {"messages": [{"role": "user", "content": "This question already has answers here:Closed12 years ago.\n\nPossible Duplicate:What should main() return in C/C++?\n\nExample1\n\n```\n#include \n\nint main(void)\n{\n printf (\"Hello World!\\n\");\n getch();\n}\n```\n\nExample2\n\n```\n#include \nvoid main()\n{\n printf (\"Hello World!\\n\");\n getch();\n}\n```\n\nBoth output:\n\n```\nHello World\n```"}, {"role": "assistant", "content": "The first example is recommended but also you need to put this line as the last one in the main()\n\n```\nreturn 0;\n```\n\nwhich returns zero to the system indicating that everything went alright."}]} {"messages": [{"role": "user", "content": "How do i change the c coding style format in emacs ? Specifically i need to change the indentation in the c code shown by emacs from i per block to 2 per block"}, {"role": "assistant", "content": "Type M-x followed by \"customize-mode\" followed by \"c-mode\". Then use the built-in customization page to override the default \"C Basic Offset\" with your new value of \"2\". When you're done, be sure to select \"Save for future sessions\" at the top of the page."}]} {"messages": [{"role": "user", "content": "I was going through an open source codebase and I see the following:-\n\n```\nchar *buf;\nchar *line;\n#define BUFSIZE 5000\n\nbuf = malloc(BUFSIZE)\nline = buf;\n\nwhile(fgets(line, (unsigned)(buf + BUFSIZE -line), in) != NULL) {\n // do stuff\n // ....\n}\n```\n\nWhy is the second argument to fgets given asbuf + BUFSIZE - line?"}, {"role": "assistant", "content": "That gives the number of characters fromlineto end ofbuf. Your//do stufflikely incrementsline\n\nbuf + BUFSIZEis achar *pointing to the first charafterthe memory allocated forbuf\n\nbuf + BUFSIZE - lineis an integral, the number of chars fromlinetobuf + BUFSIZE- and therefore the number of characters you can safely write tolinewithout overflowingbuf"}]} {"messages": [{"role": "user", "content": "How can one extract gzip data using C?\n\nExample code\n\n```\n\n \n H4sIAAAAAAAAA+3YIQ6AMAwF0AEKEATwSO5/RCoRmGHY2BMvaVLzRb/pkVI6gOZ0oQ9DAVlynbd5DFOYH3Y1WcMW9gKytGbJ8HXWFtXaaQAAAAAA/s8Pm1xuBvLpDW9ciGmfRhAnAAA=\n \n\n```\n\nI need to extract that gzip data and continue parsing the xml (tmx) file."}, {"role": "assistant", "content": "You can use thezliblibrary that can decompress gzipped data. Before that, you'll have to decode thebase64encoding. You can uselibbase64for that."}]} {"messages": [{"role": "user", "content": "```\nfd1 = open(\"/dev/test_kft\" \"1\",00);\n```\n\nWhat does\"/dev/test_kft\" \"1\"mean?"}, {"role": "assistant", "content": "It's implicit concatenation as performed by the compiler. It results in\"/dev/test_kft1\"."}]} {"messages": [{"role": "user", "content": "Does every process havestdin,stdoutandstderrassociated to it to the Keyboard and Terminal?\n\nI have a small program. I want to replace the keyboard input to a file callednew.txt. How do I go about it?\n\n```\nFILE *file1\nfopen(\"new.txt\", \"r\")\nclose(0); // close the stdio\ndup2(file1, 0);\n```\n\nWould this work? Now mystdiois redirected to theFILE?"}, {"role": "assistant", "content": "No, noteveryprocess. But on operating systems that give you a command-line window to type in, a program started from that command line will have stdin connected to the keyboard, and stdout and stderr both going to the terminal.\n\nIf one program starts another, then often the second program's standard streams are connected to the first program in some way; for example, the first program may have an open descriptor through which it can send text and pretend that it's the \"keyboard\" for the second process. The details vary by operating system, of course."}]} {"messages": [{"role": "user", "content": "```\n#include \n\nvoid findpairs(int arr[], int arr_size, int sum)\n{\n int i, temp;\n int hash[100] = {0}; \n\n for(i = 0; i < arr_size; i++)\n {\n temp = sum - arr[i];\n if(hash[temp] == 1)\n {\n printf(\"Pair with given sum %d is (%d, %d) \\n\", sum, arr[i], temp);\n }\n hash[arr[i]] = 1;\n }\n}\n\nint main()\n{\n int A[] = {4,-4,9,2,1,6,5,11};\n int sum =7;\n int arr_size = 8;\n findpairs(A, arr_size, sum);\n return 0;\n}\n```\n\nlink to the same program"}, {"role": "assistant", "content": "```\nhash[arr[i]] = 1;\n...\nhash[-4] = 1;\n```\n\nYourhasharray has indices from 0 to 99, so you're accessing out-of-bounds data.\n\nYour next out-of-bounds access will be for the value 9,\n\n```\ntemp = 7 - 9;\nif (hash[temp] == 1)\n```"}]} {"messages": [{"role": "user", "content": "Is it possible to replace BuildAll of Eclipse CDT by a Makefile?\n\nI mean I have a Makefile in C and I would buildall from this file. I build a Target in Eclipse to compile but I would use the Ctrl+B to buildall. My environment is Eclipse-Cdt."}, {"role": "assistant", "content": "There is no problem in creating a makefile that would invoke other make files.\n\nBut achieving interaction between Eclipse and the makefile would be extremely hard."}]} {"messages": [{"role": "user", "content": "What conditions are necessary for open() to fail, with UDP sockets, on Windows?\n\nThanks."}, {"role": "assistant", "content": "The only time I've seen that happen is when I didn't initialize WinSock with WSAStartup()."}]} {"messages": [{"role": "user", "content": "EDIT: Removed code/explanation because this project has been given again and students can easily find the solution via this post.\n\nTo clarify what happened, I simply passed the wrong length/size in my recvfrom() call."}, {"role": "assistant", "content": "In this line:\n\n```\nif(recvfrom( temp->sockfd, sendHostIP, BUFFER_LEN, 0, (struct sockaddr *)&recvAddr, &recvLen) < 0)\n errorMsg(\"recvfrom\");\n```\n\nYou passBUFFER_LENas the length (256), butsendHostIPis only of lengthMAXHOSTNAMELEN(64).\n\nThis causesrecvfrom()to overflow that buffer. The same problem occurs when you read in tolocalHostIP."}]} {"messages": [{"role": "user", "content": "May I know how I can a write a character string into a 2D character array?\nI need to read every character in the string and put it into a 2D array.\n\nFor example:\n\nchar string[10];\n\nI want to write all the characters in the string into a 2D array.\n\nThat means, when I read array[0][0], I should get the first character.\n\nUpdate:\n\nsuppose my string is \"GOODMORN\"\nthen the 2D array should be look like this..\n\n```\n0|1|2|3\n0 G|O|O|D\n1 M|O|R|N\n```"}, {"role": "assistant", "content": "First, make surearray[0]is big enough to hold your string. Second, usememcpyorstrncpyto copy the bytes ofstringintoarray[0].\n\nIf you need to process and address each character individually, you can start by doing what memcpy does, but in a for loop:\n\n```\n#define NUM_ARRAYS 2\n#define LENGTH 4\n\nchar *string = \"GOODMORN\";\n\nfor (arr = 0; arr < NUM_ARRAYS; arr++)\n{\n for (idx = 0; idx < LENGTH; idx++)\n {\n array[arr][idx] = string[idx + (arr * LENGTH)];\n }\n}\n```"}]} {"messages": [{"role": "user", "content": "The follow program declares a pointer then again a new pointer to hold address of previous pointer variable.. How much can I use nested pointer variable to hold memory address \nis there any limit?\n\n```\n#include \n#include \n\nvoid main()\n{\n int x=2,y=5;\n\n int *ptr;\n int **sptr;\n int ***ssptr;\n\n ptr = &x; // address of x\n *ptr = 0; \n sptr = &ptr;\n ssptr = & sptr;\n\nprintf(\" address is ip = %u %u %u\",ptr,sptr,ssptr);\n _getch();\n}\n```"}, {"role": "assistant", "content": "There is no limit. A pointer is a chunk of memory (typically one word) whose contents are an address. A pointer to a pointer is also a word whose contents are an address, but it just so happens that the contents atthataddress is another address. There is nothing particularly special about a pointer to a pointer (to a pointer to a pointer... etc.,ad nauseum)."}]} {"messages": [{"role": "user", "content": "function wait() is declared in another function. Is it legal?\n\n```\nvoid panic(const int reason, const char *strg) \n{\nint ErrNo;\nstruct machine_attributes mach;\nint ret, docstat, cnt;\npid_t pid, wait(int *), setsid(void); \n ......\n}\n```\n\nThank you!"}, {"role": "assistant", "content": "Yes, so long as this declaration matches the actual definition of the function.\n\n```\npid_t pid, wait(int *), setsid(void);\n```\n\nThis declares three entities: apid_tnamedpid, a function (takingint*and returningpid_t) namedwaitand a function (taking no parameters and returningpid_t) namedsetsid.\n\nThe declaration ofpidis also a definition."}]} {"messages": [{"role": "user", "content": "Is there any way I can synchronize the data(data sharing) between C and Java code with JNI using mutex or any other methods.\n\nPlease let me know if you have any documentation about the methods for data sharing."}, {"role": "assistant", "content": "You can use any lock you prefer in C and make it available to Java via JNI. \nYou can do the reverse as well, calling a method in Java from C to use the lock.\n\nI would do it natively in the framework which created the thread."}]} {"messages": [{"role": "user", "content": "I have looked through GDB documentation, but haven't found anything that works or shows what I need: the maximum amount of memory that is used by my application.\n\nI'm using MinGW-w64 (GCC for Windows) if that's relevant. I'd like something programmatically, not \"look in your task manager\". Also: my application executes in one go, it doesn't stop or halt anywhere, and I'd like to keep it that way.\n\nThanks!"}, {"role": "assistant", "content": "You could wrap malloc/free or new/delete:How-to-profile-memory-usage-of-a-c-program\n\nThereby you can check how much memory (heap) you are using at any time."}]} {"messages": [{"role": "user", "content": "I would like to know exactly what is going on withomp parallel forand other similiar constructs. How do I find how these are implemented? A short summary of someone who knows about this would be great. Thanks."}, {"role": "assistant", "content": "Open MP is merely a spec, how a vendor chooses to implement it is up to them. that being said, the libraries GCC uses are open source, so is Intels Thread building blocks, which has a parallel for, just not as a pragma, but its implementation is what your after"}]} {"messages": [{"role": "user", "content": "How can I modify/rotate an axis angle from world coords to object coords?\n\nSee below:\n\n```\nvoid RotateMatrix4(float *m, float angle, float *axis);\n//This function rotates a matrix in object space\n\nvoid RotateLocal(float angle, float *axis) {\n RotateMatrix4(m, angle, axis)\n}\n\nvoid RotateGlobal(float angle, float *axis) {\n //Do something to axis here\n RotateMatrix4(m, angle, axis)\n}\n```"}, {"role": "assistant", "content": "You found the answer yourself - that is simply a multiplication between a tranformation matrix and a vector - you are simply transforming the axis vector into object coords.\n\nLook atTransformation Matrixfor more information on Transformation matrices.\n\n(I would comment on your answer - but my rank is not yet high enough...)"}]} {"messages": [{"role": "user", "content": "I'm trying to develop a GTK desktop application.\n\nI want to display an image and make some clickable areas on the image. For this reason, I'm using GtkFixed container to put the image and clickable areas(GtkEventBox is used for areas). After the user clicks on a GtkEventBox, I want to display a box in the clicked area. For this reason, I have thought to use GtkVBox to make a box to display.\n\nThe problem is that GtkVBox is not visible inside a GtkFixed container parent. So I am stuck at that point. Is it possible to use GtkVBox inside GtkFixed? If not, what is the proper method of doing this job?"}, {"role": "assistant", "content": "I found the answer, it was a mistake that I usedgtk_widget_showto make container visible instead ofgtk_widget_show_all. It works now"}]} {"messages": [{"role": "user", "content": "I have a file saved as UTF-8, and i'm reading it like this:\n\n```\nReadFile(hFile, pContents, pFile->nFileSize, &dwRead, NULL);\n```\n\n(pContents is a BYTE* of size nFileSize)\n\nits just a small file with 100 bytes or so, contains text which i want to read into memory in wchar_t* format, so i can set the text of edit and static controls with the unicode text.\n\nHow can i convert the bytes to UTF-8?\n\nedit (i don't want to use fstream or wfstream)"}, {"role": "assistant", "content": "MultiByteToWideCharto convert from UTF-8 to UTF-16 (wchar_t).WideCharToMuliByteto convert from UTF-16 to UTF-8."}]} {"messages": [{"role": "user", "content": "I currently have code that looks like\n\n```\nwhile (very_long_loop) {\n ...\n y1 = getSomeValue();\n ...\n x1 = y1*cos(PI/2);\n x2 = y2*cos(SOME_CONSTANT);\n ...\n outputValues(x1, x2, ...);\n}\n```\n\nthe obvious optimization would be to compute the cosines ahead-of-time. I could do this by filling an array with the values but I was wondering would it be possible to make the compiler compute these at compile-time?\n\nEdit: I know that C doesn't have compile-time evaluation but I was hoping there would had been some weird and ugly way to do this with macros."}, {"role": "assistant", "content": "If you're lucky, you won't have to do anything: Modern compilers do constant propagation for functions in the same translation unit and intrinsic functions (which most likely will include the math functions).\n\nLook at the assembly to check if that's the case for your compiler and increase the optimization levels if necessary."}]} {"messages": [{"role": "user", "content": "Base on the answers i've got, i think this problem is kind of meaningless. Thanks for all your kind replies!\n\ni want to get a binary number with its rightmost j bits set to 1 and others set to be 0. basically, there are two methods. i wanna know which of them is more efficient, or is there a more efficient way than these two?\n\n```\n1. ~(~0 << j)\n2. (1 << j) - 1\n```"}, {"role": "assistant", "content": "Not sure if it's the answer you're looking for, but I'll bet it won't make more than a nanosecond of difference. :)\n\nOr, to put it another way: Don't micro-optimize it unless that one-liner is the bottleneck in your code.\n\nIf you needotherforms of fast bit manipulation that might actually be slower, try looking at the compiler intrinsic functions, like_BitScanForward. Those might actually make your bit operations faster, when used correctly (butnotin a situation like this)."}]} {"messages": [{"role": "user", "content": "My project right now works with XP and up, WINVER == 0x501 . However, for those using Vista and up, I would like to do:\n\n```\ncase WM_MOUSEHWHEEL:\n```\n\nin my WNDPROC\n\nHowever when I try to build that I get undeclared identifier WM_MOUSEHWHEEL\n\nis there a way to maintain compatibility with XP, but to let Vista & 7 users have this capability?\n\nThanks"}, {"role": "assistant", "content": "Use this:\n\n```\n#ifndef WM_MOUSEHWHEEL\n#define WM_MOUSEHWHEEL 0x020E\n#endif\n```\n\nThere, that should be correct\n\nNOTE: I originally answered WM_MOUSEWHEEL, not WM_MOUSEHWHEEL. Correct. :P"}]} {"messages": [{"role": "user", "content": "When debugging a program which uses (either C or C++),gdbdisplays complex numbers as_M_value = xxx + yyy*I(with a type ofcomplex double).\n\nWhile debugging, I need to print that number multiplied by a factor.\n\nThe followingdoes notwork:\n\n```\nprint a * 8.0\n```\n\nI getArgument to arithmetic operation not a number or boolean.\n\nAlso, I cannot access thereal and imaginary partsso that I can write a gdb macro to do the above. My current solution is to write a C function for manipulating complex values and arrays, and calling that function from gdb. Somehow, this just doesn't feel right."}, {"role": "assistant", "content": "If you use the standard C++ complex template then complex::real() and complex::imaj() should work.\n\nmy2c\n\nNote : Was a comment ^^"}]} {"messages": [{"role": "user", "content": "Have a question abouttypedefin C.\n\nI have defined struct:\n\n```\ntypedef struct Node {\n int data;\n struct Node *nextptr;\n} nodes;\n```\n\nHow would I createtypedefpointers tostructNode ??\n\nThanks !"}, {"role": "assistant", "content": "You can typedef them at the same time:\n\n```\ntypedef struct Node {\n int data;\n struct Node *nextptr;\n} node, *node_ptr;\n```\n\nThis is arguably hard to understand, but it has a lot to do with why C's declaration syntax works the way it does (i.e. whyint* foo, bar;declaresbarto be an int rather than anint*\n\nOr you can build on your existing typedef:\n\n```\ntypedef struct Node {\n int data;\n struct Node *nextptr;\n} node;\n\ntypedef node* node_ptr;\n```\n\nOr you can do it from scratch, the same way that you'd typedef anything else:\n\n```\ntypedef struct Node* node_ptr;\n```"}]} {"messages": [{"role": "user", "content": "In c( ansi ) , we say input taken by (s/v/f)scanf and stored in stdin , same as we say \nstdout . I wonder, in linux ( unix ) where are they reside, under which folder . \nOr they ( stdin / stdout ) are arbitrary ( that is, no such things exist )"}, {"role": "assistant", "content": "They are streams created for your process by the operating system. There is no named file object associated with them, and so they do not have a representation within the file system, although as unwind points out, they may be accessed via a pseudo file system if your UNIX variant supports such a thing."}]} {"messages": [{"role": "user", "content": "This is my code:\n\n```\nint main()\n{\n const int LEN = 5;\n int x[LEN];\n}\n```\n\nVS10 says:\n\nerror C2057: expected constant\n expressionerror C2466: cannot allocate an array\n of constant size 0error C2133: 'x' : unknown size\n\nI even tried the the code in this page and it gives the same problem (I commented the code which gives the error, and uncommented the correct one):http://msdn.microsoft.com/en-us/library/eff825eh%28VS.71%29.aspx\n\nIf I was trying a crappy compiler, I would think it's a bug in the compiler, but it's VS2010!"}, {"role": "assistant", "content": "You might have compiled your code using .c extension. MS Visual C doesn't support C99. In C89 the size of an array must be a constant expression.constqualified variables are notconstantsin C. They cannot be used at places where a realconstantis required.\n\nAlso readthis excellent postby AndreyT.\n\nTry saving the file with .cpp extension."}]} {"messages": [{"role": "user", "content": "I am using Xcode (mac) and I want to import my own header file inside of a C project. How do I do this?"}, {"role": "assistant", "content": "With your project open, go to theProjectmenu, chooseAdd to Project..., browse to the header file you want to add, on the next dialog click thecopy into destination group's folder(assuming the file is NOT within your project's path), then click theAddbutton. The file will now appear within your project."}]} {"messages": [{"role": "user", "content": "I made 2 files which are different from the program above\none is temp1.h and another is temp2.c to understand how extern is used.\nSo here is temp1.h\n\n```\n#include\ntypedef struct node * bond;\nextern int jk;\n```\n\nand temp2.c is\n\n```\n#include\n#include\nstruct node {\nint data;\n};\nint main ()\n{\nbond t1;\nt1=(bond)malloc(sizeof(bond));\nt1->data=23;\nprintf(\"the data is %d\\n\",t1->data);\njk=0;\nprintf(\"The variable jk = %d\\n\",jk);\n}\n```\n\nand when I compile these ascc -I ./ temp2.cthen I get\n\n```\n/tmp/ccdeJCat.o: In function `main':\ntemp2.c:(.text+0x3c): undefined reference to `jk'\ntemp2.c:(.text+0x46): undefined reference to `jk'\ncollect2: ld returned 1 exit status\n```\n\nI had declared jk in temp1.h as an extern int so why can I not initialize it in temp2.c?"}, {"role": "assistant", "content": "```\nint jk;\n```\n\nThe above declaration must be made somewhere in the code. Also,jkmust be global."}]} {"messages": [{"role": "user", "content": "This question already has answers here:Copying a part of a string (substring) in C(13 answers)Closed9 years ago.\n\nFor example, I have this\n\n```\nchar *buff = \"this is a test string\";\n```\n\nand want to get\"test\". How can I do that?"}, {"role": "assistant", "content": "```\nchar subbuff[5];\nmemcpy( subbuff, &buff[10], 4 );\nsubbuff[4] = '\\0';\n```\n\nJob done :)"}]} {"messages": [{"role": "user", "content": "How do you test to see if your program is working and able to connect with server? I tried stackoverflow server's ip through port 40 and it fails after a min atconnect().\n\n```\ntest.exe 64.34.119.12 echo 40\n```\n\nProgram arguments take a syntax: []\n\nAlso, can you test without having to connect to internet?"}, {"role": "assistant", "content": "You should be able to connect to your own echo server on 127.0.0.1:7 if it is running, or get a 'connection refused' (ECONN) if it isn't running. Either would show that your code is OK actually."}]} {"messages": [{"role": "user", "content": "I'm very new to dealing with bits and have got stuck on the following warning when compiling:\n\n7: warning: left shift count >= width of type\n\nMy line 7 looks like this\n\n```\nunsigned long int x = 1 << 32;\n```\n\nThis would make sense if the size oflongon my system was 32 bits. However,sizeof(long)returns8andCHAR_BITis defined as8suggesting that long should be 8x8 = 64 bits long.\n\nWhat am I missing here? AresizeofandCHAR_BITinaccurate or have I misunderstood something fundamental?"}, {"role": "assistant", "content": "longmay be a 64-bit type, but1is still anint. You need to make1along intusing theLsuffix:\n\n```\nunsigned long x = 1UL << 32;\n```\n\n(You should also make itunsignedusing theUsuffix as I've shown, to avoid the issues of left shifting a signed integer. There's no problem when alongis 64 bits wide and you shift by 32 bits, but it would be a problem if you shifted 63 bits)"}]} {"messages": [{"role": "user", "content": "I am using c .\nI have fd1 as a file descriptor, can I call like this twice?\n\n```\nmain () {\n....\nshutdown(fd1, SHUT_WR);\n....\nshutdown(fd1, SHUT_WR);\n....\n}\n```\n\nI personally think it works because fd1 has not been really free yet. Just want somebody to confirm."}, {"role": "assistant", "content": "You should check the return value of the second call -shutdown(2)probably returns-1- and check the value oferrno(3)."}]} {"messages": [{"role": "user", "content": "I have two programs interacting via a shared memory segment. When using the segment for read or write, they hold a lock.\n\nShould either of them crash (get killed, typically - possibly with something untrappable) in a critical section, I would like them to release the lock so that the shmem isn't locked out completely.\n\nOther questions point the way to the answer in Windows, Java, etc. but how do you do it in Unix (and specifically Linux)?\n\n(I'm not attached to the pthreads mutex functions; SysV semaphores or anything else will do just fine.)"}, {"role": "assistant", "content": "I believe POSIX robust mutexes are what you're looking for:\n\nhttp://www.opengroup.org/onlinepubs/9699919799/functions/pthread_mutexattr_getrobust.html"}]} {"messages": [{"role": "user", "content": "Using C or a bat file, I'm trying to edit the file hosts file from c:\\Windows\\System32\\drivers\\etc but I can;t bc it is write protected.\n\nCan you tell me what can i do?"}, {"role": "assistant", "content": "The program modifying the host file needs to run as Administrator"}]} {"messages": [{"role": "user", "content": "I'm trying to encode and transfer raw video frames over LAN (100 Mbps) connection (frames captured by a web cam). What video/image encoding format is recommended for fast compression (with not much regard for the compression ratio) ?\n\nThanks,"}, {"role": "assistant", "content": "If you need individual frames to be independent of one another, use mjpeg (which is equivalent to encoding each frame as a jpeg). It's simple and you have plenty of tools with which to manipulate it.\n\nOtherwise, as long as you have a remotely modern cpu and the resolution isn't insanely high, just use a simple mpeg4 asp or even h264 profile. Encoding 320x240 video with the simplest profile should take less than 5% cpu on a current low-end machine."}]} {"messages": [{"role": "user", "content": "I recently read a sample job interview question:\n\nWrite a function to convert an integer\n to a string. Assume you do not have\n access to library functions i.e.,\n itoa(), etc...\n\nHow would you go about this?"}, {"role": "assistant", "content": "fast stab at it: (edited to handle negative numbers)\n\n```\nint n = INT_MIN;\nchar buffer[50];\nint i = 0;\n\nbool isNeg = n<0;\n\nunsigned int n1 = isNeg ? -n : n;\n\nwhile(n1!=0)\n{\n buffer[i++] = n1%10+'0';\n n1=n1/10;\n}\n\nif(isNeg)\n buffer[i++] = '-';\n\nbuffer[i] = '\\0';\n\nfor(int t = 0; t < i/2; t++)\n{\n buffer[t] ^= buffer[i-t-1];\n buffer[i-t-1] ^= buffer[t];\n buffer[t] ^= buffer[i-t-1];\n}\n\nif(n == 0)\n{\n buffer[0] = '0';\n buffer[1] = '\\0';\n} \n\nprintf(buffer);\n```"}]} {"messages": [{"role": "user", "content": "This question already has answers here:Closed12 years ago.\n\nPossible Duplicate:Converting a Uniform Distribution to a Normal Distribution\n\nHello.\n\nI'd like to know of any algorithm implemented in C which can take a random value between 0 and 1, the mean and standard deviation and then return a normally distributed result.\n\nI have too little brainpower to figure this out for myself right now.\n\nI can't find anything useful on the internet.\n\nThank you."}, {"role": "assistant", "content": "Box-Mulleris the transform you need."}]} {"messages": [{"role": "user", "content": "I was wandering how could capture video from the built-in camera of my netbook, under Linux, ubuntu. The programming language could is not an issue (but I prefer Java or the old school c)\n\nThanks in advance for your answers,\nGian"}, {"role": "assistant", "content": "You can look into OpenCV, for C/C++. It is very powerful."}]} {"messages": [{"role": "user", "content": "Is there a way to find out if the machine is 32-bit or 64-bit by writing some code in C?"}, {"role": "assistant", "content": "```\n#include \n/* ... */\nprintf(\"This machine's pointers to void, in a program \"\n \"compiled with the same options as this one and \"\n \"with the same compiler, use %d bits\\n\",\n (int)sizeof (void*) * CHAR_BIT);\n```"}]} {"messages": [{"role": "user", "content": "I have an issue regarding freeing memory as under:\n\n```\nstring points; // some points sequences\n\n char* charPoints = (char*)malloc((points.length() +1) * sizeof(char));\n\n //do something\n\n free(charPoints);\n```\n\nEven then after freeing memory is leaked when checked with instruments"}, {"role": "assistant", "content": "The pointer you pass tofreemust be the same one which returned bymalloc. If you pass a different pointer it will result in a undefined behavior. Take a copy of the pointer before you do the operation such as incrementing thecharPointsand then pass this original pointer tofreefunction to properly release memory."}]} {"messages": [{"role": "user", "content": "```\nsize_t pixelsWidth = (size_t)bitmapSize.width;\n```\n\nOr is it totally fine to do without the casting to size_t? bitmapSize is of type CGSize..."}, {"role": "assistant", "content": "You should use the proper type, which is probably CGFloat. size_t is something int'ish and inappropriate."}]} {"messages": [{"role": "user", "content": "I have to open a file using ZwOpenFile API. This is my requirement. When I set the path in object name parameter. I could see fields Length and maximumlength in the object name.\n\nLength is just length of the path and I usually keep maximumlength as the value of Length.\n\nIt worked mostly, however some times it doesnot work. In some cases I solved it via maximumlength = length *2. Even this computation doesn't work for few other cases.\n\nI am very much puzzled with the Maximumlength value computation.\n\nCan some one help."}, {"role": "assistant", "content": "Look at UNICODE_STRING structure definition:link\n\nLength is wcslen(str.Buffer) * sizeof(WCHAR) == * 2\n\nMaximumLength field may be Length + sizeof(WCHAR) == Length + 2\n\nZwOpenFile will not write to this string, so we shouldn't care about capacity of string."}]} {"messages": [{"role": "user", "content": "I had some questions about puttingfnext to literal values. I know it defines it as afloatbut do I really need it? \nIs this2.0f * 2.0fany faster or compiled any different than2.0 * 2.0? Is a statement likefloat a = 2.0;compiled differently thanfloat a = 2.0f;?"}, {"role": "assistant", "content": "Sometimes you need it to explicitly have typefloat, like in the following case\n\n```\nfloat f = ...;\nfloat r = std::max(f, 42.0); // won't work; (float, double).\nfloat r = std::max(f, 42.0f); // works: both have same type\n```"}]} {"messages": [{"role": "user", "content": "Does C allow to place a string terminator at the end of read bytes full of garbage or is it only guaranteed if the read bytes are chars ?\n\nI need to read something like this from stdin but I do not know how many chars to read and EOF is not guaranteed:\n\n```\nHello World!---full of garbage until 100th byte---\n```\n\n```\nchar *var = malloc(100 + 1);\n\nread(0, var, 100); // read from stdin. Unfortunately, I do not know how many bytes to read and stdin is not guaranteed to hold an EOF. (I chose 100 as an educated guess.)\n\nvar[100] = '\\0'; // Is it possible to place a terminator at the end if most of the read bytes are garbage ?\n```"}, {"role": "assistant", "content": "read()returns the number of characters that were actually read into the buffer (or <0 in the case of an error). Hence the following should work:\n\n```\nint n;\nchar *var = malloc(100 + 1);\nn = read(0, var, 100);\nif(n >= 0)\n var[n] = '\\0';\nelse\n /* error */\n```"}]} {"messages": [{"role": "user", "content": "I am looking for existing implementations of different types of DES in C/C++/C##. My running platform is Windows XP/Vista/7.\n\nI am trying to write a C# program which will encrypt and decrypt using the DES algorithm. I need some implementations with which i can verify my code output to see if i did the things in right order. For the implementations the code along with the executable will be good however not a must."}, {"role": "assistant", "content": "Nearly all open source C/C++ crypto libraries implement DES. You could for instance use OpenSSL, PolarSSL, LibTomCrypt, Crypto++, or any other library of your choosing for testing/experimentation.\n\nIn C# there seem to be fewer options, simply because the default .NET crypto libraries somewhat inhibit the desire for anyone else to compete in this space, butBouncyCastle's C# code(http://www.bouncycastle.org/csharp/index.html) does contain an implementation (in src/crypto/engines/DesEngine.cs)."}]} {"messages": [{"role": "user", "content": "I need to do the following equation floor(e%100000) where e is a double. I know mod only accepts int values, how do I go about achieving this same result?\n\nThanks"}, {"role": "assistant", "content": "Use thefmod()function instead of%. It acceptsdoubleparameters, and returns adoubleresult."}]} {"messages": [{"role": "user", "content": "If I do*ptr[x], is that equivalent to*(ptr[x]), or(*ptr)[x]?"}, {"role": "assistant", "content": "*(ptr[x])\n\nSee theWikipedia operator precedence table, or, for a more detailed table,this C/C++ specific table."}]} {"messages": [{"role": "user", "content": "I am compiling on a 64 bit architecture with the intel C compiler. The same code built fine on a different 64 bit intel architecture.\n\nNow when I try to build the binaries, I get a message \"Skipping incompatible ../../libtime.a\" or some such thing, that is indicating the libtime.a that I archived (from some object files I compiled) is not compatible. I googled and it seemed like this was usually the result of a 32->64 bit changeover or something like that, but the intel C compiler doesnt seem to support a -64 or some other memory option at compile time. How do I troubleshoot and fix this error?"}, {"role": "assistant", "content": "You cannot mix 64-bit and 32-bit compiled code. Config instructions for Linuxare here."}]} {"messages": [{"role": "user", "content": "I need to write a standalone (not under XULRunner) c/c++ application (Windows OS) that uses XUL as its backend GUI library.\n\nIf it is possible, can you give me a link to an example application ? I saw something about libXul, is it needed ? where can i find it ?\n\nTNX, Vertilka"}, {"role": "assistant", "content": "I need to write a standalone (not under XULRunner) c/c++ application (Windows OS) that uses XUL as its backend GUI library.\n\nThe usual way to create a XUL GUI on top of a C++ application is by writing a XULRunner application with the C++ code wrapped in an XPCOM plugin.\n\nYou can make your application \"stand-alone\" by creating an installer program that copies the XULRunner runtime together with the XPCOM plugin to the user's computer. This is howGStreamerSongBirdworks, for example."}]} {"messages": [{"role": "user", "content": "I have code written using GNU Pth (http://www.gnu.org/software/pth/) and I want to move to Pthreads because I want it to be cross-platform (Unix, Mac, Windows).\n\nAre there and caveats I should watch out for while going about switching from Pth to Pthreads, or is it mostly just a matter of realigning arguments and variable types?"}, {"role": "assistant", "content": "Just to let people know: it is a fairly easy transition. Some of the naming is different, and there are slight differences in argument number and order but they are very similar overall.\n\nJust look up the api docs for both and look up what they do and then compare it to the other api docs."}]} {"messages": [{"role": "user", "content": "This question already has answers here:Closed13 years ago.\n\nPossible Duplicate:Is there a printf converter to print in binary format?\n\nConsider this small C application\n\n```\nint main () {\n int bits = 100 >> 3; \n printf(\"bits => %d\", bits); \n return 0;\n}\n```\n\nHow can I print thebitsvariable so I can see it as a binary value (with the bits clearly shifted), e.g.00001100?\n\nI'm also learning, so feel free to correct any terminology."}, {"role": "assistant", "content": "This should work (not tested):\n\n```\n#define PRINT_BITS 7\n\nvoid printbits(int input){\n int i, mask;\n\n for(i=PRINT_BITS; i >= 0; i--){\n mask = 1 << i;\n if(input & mask){\n printf(\"1\");\n }else{\n printf(\"0\");\n }\n }\n }\n```"}]} {"messages": [{"role": "user", "content": "The following (test withgcc -E blah.c):\n\n```\n#define UNUSED(type) type UNUSED_ ## __COUNTER__\nUNUSED(char const *)\nUNUSED(int)\n```\n\nGenerates:\n\n```\nchar const * UNUSED__COUNTER__\nint UNUSED__COUNTER__\n```\n\nI'm expecting:\n\n```\nchar const * UNUSED0\nint UNUSED1\n```\n\nI've tried calling another macro, wrapping the arguments in brackets to no avail.\nIf I don't paste the tokens it seems to work fine.\nThedocumentationspecifically mentions the use of__COUNTER__in token pasting.\n\nWhat am I doing wrong?"}, {"role": "assistant", "content": "Experimenting with gcc 4.4, this works:\n\n```\n#define UNUSED(type) UNUSED_(type, __COUNTER__)\n#define UNUSED_(type, counter) UNUSED__(type, counter)\n#define UNUSED__(type, counter) type UNUSED_ ## counter\nUNUSED(char const *)\nUNUSED(int)\n```\n\nBut it doesn't work if I take out even one level of intermediates."}]} {"messages": [{"role": "user", "content": "I wrote a program in python (using standard python libraries) long ago. Now I need to write the same program in standard C due to the lack of python support for that device.\n\nPlease suggest me programs or conversion method to convert that python code into C code.\n\nThanks in advance."}, {"role": "assistant", "content": "Shedskincould do the trick:\n\nShed Skin is an experimental compiler,\n that can translate pure, but\n implicitly statically typed Python\n programs into optimized C++. It can\n generate stand-alone programs or\n extension modules that can be imported\n and used in larger Python programs."}]} {"messages": [{"role": "user", "content": "I have looked after, without luck, a free C/C++ API for Windows that can be used in a project I am about to start. There are libraries for Java and C# but the fact is there is no one for C/C++. I need an API that can be integrated in a vs project and we cannot use libraries that run in servers ( as CGI scripts or whatever ). Does anyone know this type of API?"}, {"role": "assistant", "content": "if you want to generate QRcodes have a look atlibqrencodeit works with cygwin on windows (not sure about VS).\n\nIf you want to decode QRcodes have a look atzxing"}]} {"messages": [{"role": "user", "content": "as in the title, it doesn't appear to generate an event unless another key/button is pressed at the same time. thanks,\njames"}, {"role": "assistant", "content": "Running xev and pressing shift gives me this:\n\n```\nKeyPress event, serial 34, synthetic NO, window 0x5a00001,\n root 0xf7, subw 0x0, time 1739516541, (174,173), root:(1021,367),\n state 0x10, keycode 50 (keysym 0xffe1, Shift_L), same_screen YES,\n XLookupString gives 0 bytes: \n XmbLookupString gives 0 bytes: \n XFilterEvent returns: False\n\nKeyRelease event, serial 34, synthetic NO, window 0x5a00001,\n root 0xf7, subw 0x0, time 1739516717, (174,173), root:(1021,367),\n state 0x11, keycode 50 (keysym 0xffe1, Shift_L), same_screen YES,\n XLookupString gives 0 bytes: \n XFilterEvent returns: False\n```\n\nSo yes, it is possible."}]} {"messages": [{"role": "user", "content": "I'm using code like the following to check whether a file has been created before continuing, thing is the file is showing up in the file browser much before it is being detected by stat... is there a problem with doing this?\n\n```\n//... do something\n\nstruct stat buf;\n\nwhile(stat(\"myfile.txt\", &buf))\n sleep(1);\n\n//... do something else\n```\n\nalternatively is there a better way to check whether a file exists?"}, {"role": "assistant", "content": "Usinginotify, you can arrange for the kernel to notify you when a change to the file system (such as a file creation) takes place. This may well be what your file browser is using to know about the file so quickly."}]} {"messages": [{"role": "user", "content": "I'm using OpenGL and drawing polygons in a 2D view. How could I blur a polygon, without using glsl, and only things like stencil buffer and stuff. Thanks"}, {"role": "assistant", "content": "The normal method uses the accumulation buffer instead of the stencil buffer. You basically re-draw your polygon(s) a number of times, but change the viewing perspective slightly each time. Exactly what you change determines the style of blur you get. For example, if you want an effect like zooming a camera lens, you can change the view frustum slightly between frames. If you want motion blur, you change the camera view angle instead. With some extra work, you can do some slightly odd-looking effects, such as moving your viewpoint forward, and zooming back at the same time, so (most of) the scene remains roughly the same size, but the perspective you're viewing it from constantly changes."}]} {"messages": [{"role": "user", "content": "Is there any portable way (on POSIX systems) to determine if a file descriptor is seekable? My thought is to uselseek(fd, 0, SEEK_CUR);and check if the return value is -1, but I'm uncertain if this could give false negatives or false positives. Usingfstatand making assumptions about what types of files are seekable/nonseekable does not sound like a good idea. Any other ideas?"}, {"role": "assistant", "content": "Thelseekmethod seems reasonable. It certainly can't cause a false negative - if it did, something is seriously wrong with the implementation. Also, according to thePOSIX spec, it is supposed to fail if the descriptor is a pipe, FIFO or socket, so theoretically you shouldn't have false positives either. The only remaining question is how well different systems comply with the specs. However, it seems like any other methods, whatever they may be, would definitely be less portable than this."}]} {"messages": [{"role": "user", "content": "When a menu item or context menu is made, it has a shadow, if I create a window with WS_POPUP instead of WS_CHILD it has no shadow. How can I get the shadow? Thanks"}, {"role": "assistant", "content": "It is enabled with WNDCLASSEX.style. Turn on theCS_DROPSHADOW style. I think this only works on top-level windows."}]} {"messages": [{"role": "user", "content": "AreStatement and Declarations in Expressionsspecific to GNU C ? Or this feature is also included in C99 standard ?"}, {"role": "assistant", "content": "It's a GCC extension. (See the GCC docs,e.g. here for gcc 4.3.3, for a full list of GCC extensions; and theC99 spec is available here.)\n\nGCC will warn about such things if you use the-pedantic -std=c99flags, e.g.:\n\n```\n$ cat foo.c\nint main(void)\n{\n return ({ int a = 0; a; });\n}\n$ gcc -pedantic -std=c99 -c foo.c\nfoo.c: In function 'main':\nfoo.c:3: warning: ISO C forbids braced-groups within expressions\n```"}]} {"messages": [{"role": "user", "content": "This question already has answers here:Closed13 years ago.\n\nPossible Duplicate:Can you write object oriented code in C?\n\nI'm wondering if it's possible to use strict ANSI C as a object oriented language. And if it's possible, how do I make a class in ANSI C. Allthough the language isn't designed for OO, I'm really eager to try this.\n\nAny examples, links etc. are appreciated."}, {"role": "assistant", "content": "C doesn't have direct support for OO via classes, but you can easily emulate it.\n\nThe basics of how to do this is that you can make a struct which holds your data members and an associated list of functions which takes a pointer to that struct as it's first parameter.\n\nMore information"}]} {"messages": [{"role": "user", "content": "Right now I'm drawing a cube with OpenGL, I'm using Windows and WGL context. I have blending enabled so my cube looks semi transparent. Basically the background == the clear color (Black). I'd like to be able to save the image in raw RGBA format which I can then make into a png. I basically want the cube to blend in with a NULL background (0,0,0,0). How could I save the OpenGL output and have the background color be (0,0,0,0) (transparent) Without using a color mask (like 255,0,255).\n\nThanks"}, {"role": "assistant", "content": "Just draw the cube, setting the clear color to (0, 0, 0, 0), and save the output using glReadPixels."}]} {"messages": [{"role": "user", "content": "Let's say I had a char pointer pointing to a buffer that contained these values (in hex):\n\n```\n12 34 56 78 00 00 80 00\n```\n\nI want to modify the last two bytes to ashortvalue of 42. So I would think I would have to do something like this:\n\n```\n(short)*(pointer+6)=42;\n```\n\nThe compiler doesn't complain but it does not do what I'm expecting it to do. Can someone tell me the correct way to assign the value?"}, {"role": "assistant", "content": "The cast to \"short\" is happening after the assignment. What you want is:\n\n```\n*(short*)(pointer+6) = 42;\n```\n\nBy the way, beware of aliasing issues. In this case you're probably ok since chars are assumed to be able to alias anything (edit: I stand corrected; this example breaks strict aliasing unless this data's actual type is \"short\"). But in general you should be very wary of cases where you are casting one pointer type to another. Google \"strict aliasing\" for more info."}]} {"messages": [{"role": "user", "content": "I found this structure called OBJECT_ATTRIBUTE in one of the nt dll functions..I was curious to know about that structure and I went through its documentation(msdn)...In the OBJECT_ATTRIBUTE structure there is a parameter called PUNICODE_STRING objectName...As per the msdn documentation..it says that the objectName \"the name of the object for which a handle is to be opened\" which is actually a name or some root directory,am confused with this.Can anybody explain this term \"name of the object\"(root directory).what it represents."}, {"role": "assistant", "content": "This structure is used by device drivers and other kernel mode code to specify attributes of file objects. When you open a file with theNtOpenFileorIoCreateFilefunctions, you have to pass anOBJECT_ATTRIBUTESwith the name of the file.\n\nTheObjectNamemember of the structure is simply a pointer to anUNICODE_STRINGstructure containing the file or directory name."}]} {"messages": [{"role": "user", "content": "Content ofX.c:\n\n```\nint i;\nmain ()\n{\nfun ();\n}\n```\n\nContent ofY.c:\n\n```\nint i;\nfun ()\n{\n}\n```\n\nWhy does these two files compile with no error ? (using GCC)\n\nBut if i useint i = 10;it prints a multiple definition error."}, {"role": "assistant", "content": "You may be interested in this question and the answers. Keywords: \"tentative definition\".\n\nTentative definitions in C99 and linking"}]} {"messages": [{"role": "user", "content": "I have a buffer with the UTC time stamp in C, I broadcast that buffer after every ten seconds. The problem is that the time difference between two packets is not consistent. After 5 to 10 iterations the time difference becomes 9, 11 and then again 10. Kindly help me to sort out this problem.\n\nI am usingfor UTC time."}, {"role": "assistant", "content": "If your time stamp has only 1 second resolution then there will always be +/- 1 uncertainty in the least significant digit (i.e. +/- 1 second in this case).\n\nClarification: if you only have a resolution of 1 second then your time values arequantized. The real time,t, represented by such a quantized value has a range oft..t+0.9999. If you take the difference of two such times,t0andt1, then the maximum error int1-t0is-0.999..+0.999, which when quantized is+/-1second. So in your case you would expect to see difference values in the range9..11seconds."}]} {"messages": [{"role": "user", "content": "I want to create a custom malloc which allocates memory blocks within a given address range.\n\nI am writing a pthreads application in which threads are bound to unique cores on a many-core machine. The memory controllers are statically mapped, so that certain range of addresses on main memory are electrically closer to a core. \nI want to minimize the latency of communication between cores and main memory by allocating thread memory on these \"closer\" regions.\n\nAny ideas would be most appreciated.\nThank you!\nNandu"}, {"role": "assistant", "content": "There is already libnuma for that purpose. Take a look atnuma_alloc_onnode"}]} {"messages": [{"role": "user", "content": "I'm trying to check whether or not the second argument in my program is a substring of the first argument. The problem is that it only work if the substring starts with the same letter of the string.\n\nEDIT: It must be done in C, not C++.\n\n```\nint main(int argc, char **argv){\n\n if (argc != 3) {\n printf (\"Usage: check \\n\");\n }\n\n int result = my_strstr(argv[1], argv[2]);\n\n if(result == 1){\n printf(\"%s is a substring of %s\\n\", argv[2], argv[1]);\n }\n else{\n printf(\"%s is not a substring of %s\\n\", argv[2], argv[1]);\n }\n return 0;\n}\n```"}, {"role": "assistant", "content": "I am assuming homework, so: Take a look at whatsubStartis initialized with."}]} {"messages": [{"role": "user", "content": "What I know about unsigned numerics (unsigned short, int and longs), that It contains positive numbers only, but the following simple program successfully assigned a negative number to an unsigned int:\n\n```\n1 /*\n 2 * =====================================================================================\n 3 *\n 4 * Filename: prog4.c\n 5 *\n 6 * =====================================================================================\n 7 */\n 8 \n 9 #include \n 10 \n 11 int main(void){\n 12 \n 13 int v1 =0, v2=0;\n 14 unsigned int sum;\n 15 \n 16 v1 = 10;\n 17 v2 = 20;\n 18 \n 19 sum = v1 - v2;\n 20 \n 21 printf(\"The subtraction of %i from %i is %i \\n\" , v1, v2, sum);\n 22 \n 23 return 0;\n 24 }\n```\n\nThe output is :The subtraction of 10 from 20 is -10"}, {"role": "assistant", "content": "%iis the format specifier for asignedinteger; you need to use%uto print an unsigned integer."}]} {"messages": [{"role": "user", "content": "From a long time ago I have a memory which has stuck with me that says comparisons against zero are faster than any other value (ahem Z80).\n\nIn some C code I'm writing I want to skip values which have all their bits set. Currently the type of these values ischarbut may change. I have two different alternatives to perform the test:\n\n```\nif (!~b)\n /* skip */\n```\n\nand\n\n```\nif (b == 0xff)\n /* skip */\n```\n\nApart from the latter making the assumption that b is an 8bit char whereas the former does not, would the former ever be faster due to the old compare to zero optimization trick, or are the CPUs of today way beyond this kind of thing?"}, {"role": "assistant", "content": "If it is faster, the compiler will substitute it for you.\n\nIn general, you can't write C better than the compiler can optimize it. And it is architecture specific anyway.\n\nIn short,don't worry about itunless that sub-micro-nano-second is ultra important"}]} {"messages": [{"role": "user", "content": "so if I do:\n\n```\ndup2(0, backup); // backup stdin\ndup2(somefile, 0); // somefile has four lines of content\nfgets(...stdin); // consume one line\nfgets(....stdin); // consume two lines\ndup2(backup, 0); // switch stdin back to keyboard\n```\n\nI am finding at this point.. stdin still contains the two lines I haven't consumed. Why is that? Because there is just one buffer no matter how many times you redirect? How do I get rid of the two lines left but still remember where I was in the somefile stream when I want to go back to it?"}, {"role": "assistant", "content": "You haven't flushed the stdin buffer. It has buffered up all the lines of somefile even if the underlying file descriptor is restored."}]} {"messages": [{"role": "user", "content": "```\n#include\n#include\n\nint main ()\n{\n FILE *fp;\n fp=fopen(\"output\",\"w\");\n float t,y=0,x=0,e=5,f=1,w=1;\n for (t=0;t<10;t=t+0.01)\n {\n if( y==inf && y== nan) \n break;\n fprintf(fp,\"%lf\\t%lf\\n\",y,x);\n y = y + ((e*(1 - x*x)*y) - x + f*cos(w*t))*t;\n x = x + y*t;\n }\n return 0;\n}\n```\n\nWhy is the ouput giving infinite and NAN values?"}, {"role": "assistant", "content": "Your calculation is blowing up. Just look at the values printed out for x and y and you will see they start to get very large and then turn info inf. Because your conditional is wrong, you wind up using inf in the calculation which turns into nan."}]} {"messages": [{"role": "user", "content": "```\n#include\n\n#define a(x) (x * x) \n\nint main() \n{\n int i = 3, j;\n\n j = a(i + 1);\n printf(\"%d\", j);\n\n return 0;\n}\n```\n\nI want to know why the program is not giving the output16. (I'm getting the output7.)\n\nI understood the point very much but if the program is like this:\n\n```\n#include\n\n#define a(x) (x * x)\n\nint main()\n{\n int i = 3, j, k;\n\n j = a(i++);\n k = a(++i);\n printf(\"%d\\n%d\", j, k);\n\n return 0;\n}\n```\n\nThen why does the above program give the following output:\n\n```\n9\n49\n```"}, {"role": "assistant", "content": "Because you made a bad macro:\n\n```\na(i + 1)\n```\n\nexpands to\n\n```\ni + 1 * i + 1\n```\n\nwhich is equivalent to\n\n```\ni + i + 1\n```\n\nor\n\n```\n2 * i + 1\n```\n\nUse parenthesis:\n\n```\n#define a(x) ((x) * (x))\n```\n\nAnd then you'll get it to expand to\n\n```\n(i + 1) * (i + 1)\n```\n\nwhich does what you want."}]} {"messages": [{"role": "user", "content": "I have set up the following struct:\n\n```\ntypedef struct _thread_node_t {\n pthread_t thread;\n struct thread_node_t *next;\n} thread_node_t;\n```\n\n... and then I have defined:\n\n```\n// create thread to for incoming connection\nthread_node_t *thread_node = (thread_node_t*) malloc(sizeof(thread_node_t));\npthread_create(&(thread_node->thread), NULL, client_thread, &csFD);\n\nthread_node->next = thread_arr; // assignment from incompatible pointer type\n\nthread_arr = thread_node;\n```\n\nwhere thread_arr isthread_node_t *thread_arr = NULL;\n\nI don't understand why the compiler is complaining. Maybe I'm misunderstanding something."}, {"role": "assistant", "content": "Shouldn'tstruct thread_node_t *next;bestruct _thread_node_t *next;\n\nAlso, do away with theexplicitcast.\n\n```\nthread_node_t *thread_node = (thread_node_t*) malloc(sizeof(thread_node_t));\n```\n\nto\n\n```\nthread_node_t *thread_node = malloc(sizeof(thread_node_t));\n```"}]} {"messages": [{"role": "user", "content": "C/Obj-C Developers- I am looking for a way to listen for a specific word or small set of words to be spoken and fire an event. Needs to be able to run on the iPhone/iPad ... Looking for ideas?"}, {"role": "assistant", "content": "There seem to be a few commercial options, but from what I can find no (Easy) free method. Searching around seems to indicate that Julius (http://julius.sourceforge.jp/en_index.php) could work for iPhone, but there aren't any instructions I can find.\n\nCommercial:\n* Creaceed"}]} {"messages": [{"role": "user", "content": "What is the quickest way to find the number of elements in a static array and dynamic array?"}, {"role": "assistant", "content": "There is no way of finding the number of elements in a dynamically created array. For a non-dynamic array, you can usesizeof(array)/sizeof(type). However, this is not as useful as it seems:\n\n```\nvoid f( int a[] ) {\n // sizeof(a) will be the size of a pointer, probably 4\n}\n\nint main() {\n int a[100];\n // sizeof(a)/sizeof(int) will be 100\n f( a );\n}\n```\n\nThis is because arrays decay into pointers when passed to functions. So in both cases, you probably need to remember the size of the array and pass it to functions as a separate parameter. So a function to sum an array (for example) would look like this:\n\n```\nint sum( int a[], int n ) {\n int total = 0, i; \n for ( i = 0; i < n; i++ ) {\n total += a[i];\n }\n return total;\n}\n```"}]} {"messages": [{"role": "user", "content": "In my C OpenGL app the window style requires WS_SYSMENU to show the close and minimize buttons, but it also brings up a stupid menu everytime I press alt.\n\nHow can I disable this?"}, {"role": "assistant", "content": "One way is to handle WM_DEADCHAR and WM_SYSCHAR and discard the press of the ALT key (or do your own processing). This will still allow the user to activate the menu with the mouse and from the taskbar... which is why you really shouldn't disable it completely, users like to be able to manipulate windows from the taskbar."}]} {"messages": [{"role": "user", "content": "Is there any difference between a variable declared asstaticoutside any function between C and C++. I read thatstaticmeans file scope and the variables will not be accessible outside the file. I also read that in C, global variables arestatic. So does that mean that global variables in C can not be accessed in another file?"}, {"role": "assistant", "content": "No, there's no difference between C and C++ in this respect.\n\nReadthis SO answerabout whatstaticmeans in a C program. In C++ there are a couple of other meanings related to the use ofstaticfor class variables (instead of instance variables).\n\nRegarding global vars beingstatic- only from the point of view of memory allocation (they are allocated on the data segment, as all globals are). From the point of view of visibility:\n\n```\nstatic int var; // can't be seen from outside files\nint var; // can be seen from outside files (no 'static')\n```"}]} {"messages": [{"role": "user", "content": "When running the following code I get no output but I cannot work out why.\n\n```\n# include \n\nint main()\n{\n fputs(\"hello\", stdout);\n\n while (1);\n\n return 0;\n}\n```\n\nWithout the while loop it works perfectly but as soon as I add it in I get no output. Surely it should output before starting the loop? Is it just on my system? Do I have to flush some sort of buffer or something?\n\nThanks in advance."}, {"role": "assistant", "content": "You have to flushstdout. This happens automatically when you write a newline character. Change thefputsto:\n\n```\nfputs(\"hello\\n\", stdout);\n```\n\nOr to:\n\n```\nfputs(\"hello\", stdout);\nfflush(stdout);\n```"}]} {"messages": [{"role": "user", "content": "How to get he upper limit of a number in C?\n\nIf I divide 3 by 2 I want the answer to be 2 (ie 1.5 rounded to 2)."}, {"role": "assistant", "content": "If you are just interested in dividing by 2, then just take (n + 1) / 2 to keep it in integer math. For example (3 + 1) / 2 gives 2. For a larger number x, use x - 1. For example, (3 + 7) / 8 = 1, for 3 divided by 8.\n\nFor the general case, you are looking for the ceiling function -- ceil. A quick Google search for \"math ceil C\" gave this page at the top of the results:http://www.elook.org/programming/c/ceil.html"}]} {"messages": [{"role": "user", "content": "How to install new units (i mean includes ex: stdio.h) for my C, and how to download more?"}, {"role": "assistant", "content": "put the header file on the same folder as your main source file,\nex:\n\n/folder /-->main.c-->function.h\n -->function.c\n\nthen on main.c include it by writing :\n\n```\n#include \"function.h\"\n```\n\nthe quotes are used to include a header file that's on the same folder as your c source file\nu can also write your own and include them like above."}]} {"messages": [{"role": "user", "content": "This question already has answers here:Why can't I use sizeof in a preprocessor condition?(2 answers)Closed9 years ago.\n\nI have this:\n\n```\n#if sizeof(int)\n #error Can't use sizeof in a #if\n#endif\n```\n\nI get this compiler error:\n\n```\nmissing binary operator before token \"(\"\n```\n\nWhy can't I use the sizeof operator here?"}, {"role": "assistant", "content": "Because sizeof() is calculated after the preprocessor is run, so the information is not available for#if.\n\nC compilers are logically split into two phases, even if most modern compilers don't separate them. First, the source is preprocessed. This involves working out and substituting all the preprocessor conditionals (#if, #define, replacing defined words with their replacements). The source is then passed, processed, to the compiler itself. The preprocessor is only minimally aware of the structure of C, it has no type knowledge, so it can't handle compiler-level constructs like sizeof()."}]} {"messages": [{"role": "user", "content": "The problem is simpler thanknapsack(or a type of it, without values and only positive weights). The problem consists of checking whether a number can be a combination of others. The function should returntrueorfalse.\n\nFor example,\n\n112 and a list with{ 17, 100, 101 }should returnfalse,469with the same list should returntrue,35should returnfalse,119should returntrue, etc...\n\nEdit: subset sum problem would be more accurate for this than knapsack."}, {"role": "assistant", "content": "This is a special case of the Subset Sum problem, with sets that only contain one negative number (i.e., express 112 and { 17, 100, 101 } as { -112, 17, 100, 101 }). There's a few algorithms on the Wikipedia page,http://en.wikipedia.org/wiki/Subset_sum_problem."}]} {"messages": [{"role": "user", "content": "I would like to know how to create console applications with better control of input and output using C. For example, how does the text-editor nano display the file contents in a certain portion of the screen and then keep a list of commands stationary on the bottom. I know you can use the win32 api to do this in Windows, but what is the Unix/Linux equivalent?"}, {"role": "assistant", "content": "More than likely there's ancursesinterface that controls the screen drawing and placement of items on the screen in a certain position. The api is standard across the linux systems and on unix also, some may be implementation defined depending on the variant of curses used under the commercial variants of unix but otherwise some standard ncurses functionality are compatible."}]} {"messages": [{"role": "user", "content": "Valgrind gives me the following leak summary on my code. However, I have freed all malloc'ed memory. Is this a bad thing, or is this normal? My program is in c.\n\n==3513== LEAK SUMMARY:==3513== definitely lost: 0 bytes in 0 blocks.==3513== possibly lost: 0 bytes in 0 blocks.==3513== still reachable: 568 bytes in 1 blocks.==3513== suppressed: 0 bytes in 0 blocks."}, {"role": "assistant", "content": "The valgrind messagestill reachable: 568 bytes in 1 blocks.means that there was memory freed in your application which is still \"reachable\", which means that you still have a pointer to it somewhere. At shutdown, this probably means a global variable of some kind. However, since the number of bytes \"definitely leaked\" or \"probably leaked\" is zero, this condition is completely benign. Don't worry about it."}]} {"messages": [{"role": "user", "content": "Why do I get segmentation fault in this function:\n\n```\n#include \n#include \n#include \"math.h\"\n\nvec_t mtrx_multiple (sparse_mat_t a, vec_t c) {\n\n vec_t result;\n int i;\n\n result.n = a.n;\n printf(\"result.n: %d\\n\", result.n);\n\n result.vec = malloc(a.n * sizeof *result.vec);\n for(i=0; i\n#include \n#include \n\nmain()\n{\n char* path = \"/bin/sh\";\n int err = execve(path, &path, NULL);\n printf(\"%d\\n\", err);\n printf(\"%s\\n\", strerror(errno));\n printf(\"%x, %x\\n\", path, &path);\n}\n```\n\nHowever the output is:\n\n```\n-1\nBad address\n80485c0, bf816f4c\n```"}, {"role": "assistant", "content": "Because you aren't sending a NULL terminated list of arguments.\nYou need:\n\n```\nchar* path[2];\npath[0] = \"/bin/sh\";\npath[1] = NULL;\nint err = execve(path[0], path, NULL);\n```"}]} {"messages": [{"role": "user", "content": "why can we do this in c?\n\n```\nint n;\nscanf(\"%d\",&n);\nint a[n];\n```\n\nI thought array is located memory during load time but seems like the above example works during runtime.\nDo I misunderstand any thing? can you guys help?\n\nThanks,"}, {"role": "assistant", "content": "I am no expert in C, but this could be avariable-length arrayas added byC99andsupported by GCC, for example. GCC allocates the memory for such array on stack, so that it gets automatically freed when you return from the function."}]}