I am compiling a small C program with Microsoft Visual Studio 2010 on Windows 7. Here's a small snippet:
void test(char[] s)
{
//some code here
}
But I am getting the following error:
Expected a ')'
How would I resolve this issue?
Actually the full code is here , which implement radix sort MSD in C (chapter 10 of this book):
#define N // integers to be sorted with values from 0 -256
void MSD (char[] s) {
msd_sort(s, 0, len(s), 0)
}
msd_sort(char [][] s, int lhs, int rhs, int d )
{
if (rhs<=lhs+1) return;
int * count =(int * )malloc(257*sizeof(int));
for(int i = 0; i < N; ++i)
count[s[i][d]+1]++;
for(int k = 1; k < 256; ++k)
count[k] += count[k-1];
for(int j = 0; j < N; ++j)
temp[count[s[i][d]]++] = a[i];
for(int i = 0; i < N; ++i)
s[i] = temp[i];
for(int i = 0; i<255;++i)
msd_sort(s, 1 + count[i], 1 + count[i+1], d+1);
}
void test(char s[]) {}
^^---brackets go here
What you wrote is Java.
Also :
don't forget to give a value to your #define N.
I see one malloc and no free, that's a memory leak.
Related
How do I make my code more efficient (in time) pertaining to a competitive coding question (source: codechef starters 73 div 4):
(Problem) Chef has an array A of length N. Chef wants to append a non-negative integer X to the array A such that the bitwise OR of the entire array becomes = Y .
Determine the minimum possible value of X. If no possible value of X exists, output -1.
Input Format
The first line contains a single integer T — the number of test cases. Then the test cases follow.
The first line of each test case contains two integers N and Y — the size of the array A and final bitwise OR of the array A.
The second line of each test case contains N space-separated integers A_1, A_2, ..., A_N denoting the array A.
Please don't judge me for my choice of language .
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int* binary_number(int n) // returns pointer to a array of length 20(based on given constrains) representing binary
{
int* ptc;
ptc = (int*) malloc(20*sizeof(int));
for(int i = 0; i < 20; i++)
{
if((n / (int) pow(2,19-i)) > 0){*(ptc + i) = 1;}
else {*(ptc + i) = 0;}
n = n % (int) pow(2,19-i) ;
}
return ptc;
}
int or_value(int* ptc, int n) // Takes in pointers containing 1 or zero and gives the logical OR
{
for(int k = 0; k < n; n++)
{
if(*ptc == *(ptc + 20*k)){continue;} // pointers are 20 units apart
else{return 1;break;}
}
return *ptc;
}
int main(void) {
int t; scanf("%d", &t);
for (int i = 0; i < t; i++)
{
int n, y;
scanf("%d %d", &n, &y);
int a[n];
for(int j = 0; j < n ; j++)
{
scanf("%d", &a[j]);
}
int b[20*n];
for (int j = 0; j < n; j++)
{
for (int k = 0; k < 20; k++)
{
b[20*j + k] = *(binary_number(a[n])+k);
}
}
int c = 0;
int p = 0;
for (int j = 0; j < 20; j++)
{
if ((*(binary_number(y) + j) == 1) && (or_value((&b[0] + j),n) == 0)){c = c + pow(2,19 - j);}
else if ((*(binary_number(y) + j) == 0) && (or_value((&b[0] + j),n) == 1)){p = 1; break;}
}
if (p==1){printf("-1");}
else {printf("%d\n", c);}
}
return 0;
}
I am trying to allocate triangular array using single malloc but I could'nt find any solution for this. My structure is something like this :
a - - - -
b c - - -
d e f - -
g h i j -
k l m n o
I've made it using two malloc.
How are you planning to use the structure — what code would you write to access an array element? Also, what size of array are you dealing with?
If the array is small enough (say less than 100x100, but the boundary value is negotiable) then it makes sense to use a regular rectangular array and access that as usual, accepting that some of the allocated space is unused. If the array will be large enough that the unused space will be problematic, then you have to work harder.
Do you plan to use lt_matrix[r][c] notation, or could you use a 1D array lt_matrix[x] where x is calculated from r and c? If you can use the 1D notation, then you can use a single allocation — as shown in Technique 1 in the code below. If you use the double-subscript notation, you should probably do two memory allocations — as shown in Technique 2 in the code below. If you don't mind living dangerously, you can mix things up with Technique 3, but it isn't recommended that you use it unless you can determine what the limitations and issues are and assess for yourself whether it is safe enough for you to use. (If you ask me, the answer's "No; don't use it", but that could be regarded as being over-abundantly cautious.)
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
static inline int lt_index(int r, int c) { assert(r >= c); return r * (r + 1) / 2 + c; }
int main(void)
{
int matrixsize = 5;
/* Technique 1 */
char *lt_matrix1 = malloc(matrixsize * (matrixsize + 1) / 2 * sizeof(*lt_matrix1));
assert(lt_matrix1 != 0); // Appalling error checking
char value = 'a';
for (int i = 0; i < matrixsize; i++)
{
for (int j = 0; j <= i; j++)
lt_matrix1[lt_index(i, j)] = value++;
}
for (int i = 0; i < matrixsize; i++)
{
int j;
for (j = 0; j <= i; j++)
printf("%-3c", lt_matrix1[lt_index(i, j)]);
for (; j < matrixsize; j++)
printf("%-3c", '-');
putchar('\n');
}
free(lt_matrix1);
/* Technique 2 */
char **lt_matrix2 = malloc(matrixsize * sizeof(*lt_matrix2));
assert(lt_matrix2 != 0); // Appalling error checking
char *lt_data2 = malloc(matrixsize * (matrixsize + 1) / 2 * sizeof(*lt_matrix1));
assert(lt_data2 != 0); // Appalling error checking
for (int i = 0; i < matrixsize; i++)
lt_matrix2[i] = <_data2[lt_index(i, 0)];
value = 'A';
for (int i = 0; i < matrixsize; i++)
{
for (int j = 0; j <= i; j++)
lt_matrix2[i][j] = value++;
}
for (int i = 0; i < matrixsize; i++)
{
int j;
for (j = 0; j <= i; j++)
printf("%-3c", lt_matrix2[i][j]);
for (; j < matrixsize; j++)
printf("%-3c", '-');
putchar('\n');
}
free(lt_data2);
free(lt_matrix2);
/* Technique 3 - do not use this */
void *lt_data3 = malloc(matrixsize * sizeof(int *) + matrixsize * (matrixsize + 1) / 2 * sizeof(int));
assert(lt_data3 != 0); // Appalling error checking
int **lt_matrix3 = lt_data3;
int *lt_base3 = (int *)((char *)lt_data3 + matrixsize * sizeof(int *));
for (int i = 0; i < matrixsize; i++)
lt_matrix3[i] = <_base3[lt_index(i, 0)];
value = 1;
for (int i = 0; i < matrixsize; i++)
{
for (int j = 0; j <= i; j++)
lt_matrix3[i][j] = value++;
}
for (int i = 0; i < matrixsize; i++)
{
int j;
for (j = 0; j <= i; j++)
printf("%-3d", lt_matrix3[i][j]);
for (; j < matrixsize; j++)
printf("%-3c", '-');
putchar('\n');
}
free(lt_data3);
return 0;
}
The output from the program is:
a - - - -
b c - - -
d e f - -
g h i j -
k l m n o
A - - - -
B C - - -
D E F - -
G H I J -
K L M N O
1 - - - -
2 3 - - -
4 5 6 - -
7 8 9 10 -
11 12 13 14 15
Valgrind version 3.13.0.SVN (revision 16398) gives this a clean bill of health on macOS Sierra 10.12.5 using GCC 7.1.0.
You can just malloc(width * height * sizeof(Object)) if you want to use one malloc and create one continuous array. If you want to access the (x, y) position, use: array[y * width + x].
Using two malloc just creates an array of pointers, which is a little different from a continuous array acting like a 2D array.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
The following code snippet will print every 4 character long combination (without repetition) of the elements of an array.
for (int i = 0; i < len; i++)
for (int j = i + 1; j < len; j++)
for (int k = j + 1; k < len; k++)
for (int l = k + 1; l < len; l++)
printf("%c%c%c%c\n", arr[i], arr[j], arr[k], arr[l]);
My problem is I don't know how to extend this to a general function (ie print every N character long combination). How can I make a function do the same thing but be called like this:
combinationPrint(array, numberOfForLoops); // With other params if needed
The recursive version of your function would work like this:
void recur (char* arr, int i, int len, char *x, int k, int n) {
if (k==n) { // the last inner loop
x[k]=0;
printf ("%s\n", x);
}
else {
for (int j=i+1; j<len; j++) { // recursive loop
x[k]=arr[j];
recur (arr, j, len, x, k+1, n); // call recursion for an inner loop
}
}
}
In this recursion, arr and len correspond to your definition and n is the depth of the loops you want to achieve (4 in your non recursive version).
The trick is to use a null terminated array of n+1 chars, that you keep across the recursion and build the string that you want to print at the last level. i is then the starting position of the loop and k is the current level of recursion.
You would call this:
recur (arr, -1, len, out, 0, 4 );
Online demo
Without recursion, you can use this (len = length of the array) :
int i, j, w, x;
for(i=0; i<pow(len,len); i++){ //n^n possibilities / combinaisons
w = i;
for(j=0; j<len; j++){ //Show the combinaison
x = w%len; //We have juste to calculate the correct position with some modulos
printf("%c", array[x]);
w = w/len;
}
printf("\n");
}
For exemple with this implementation :
#include <stdio.h>
#include <math.h>
int main(){
int array[] = {1,2,3};
int len = 3;
int i, j, w, x;
for(i=0; i<pow(len,len); i++){
w = i;
for(j=0; j<len; j++){
x = w%len;
printf("%d", array[x]);
w = w/len;
}
printf("\n%d\n", i);
}
}
You should have :
111
211
311
121
221 [...]
133
233
333
Well, instead of N loops - you just need one. Within this main loop you have to have just two inner loops for incrementing array of indices and for printing values:
int increment(int* index, int N, int len)
{
for (int i = N - 1; i >= 0; --i)
{
++index[i];
if (index[i] < len)
return 1;
index[i] = 0;
}
return 0;
}
So - the main loop:
int index[N] = {};
do
{
// print
for (int i = 0; i < N; ++i)
printf("%c", arr[index[i]]);
printf("\n");
} while (increment(index, N, len));
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to code the Waterman algorithm in C.
Now when the length of the sequence exceeds 35 the program just lags.
I have no idea where to start looking, tried but got nothing worked out.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Max Function Prototype.
int maxfunction(int, int);
// Prototype of the random Sequences generator Function.
void gen_random(char *, const int);
int main(int argc, char *argv[]) {
// Looping variable and Sequences.
int i = 0, j = 0, k = 0;
char *X, *Y;
int length1, length2;
// Time Variables.
time_t beginning_time, end_time;
// Getting lengths of sequences
printf("Please provide the length of the first Sequence\n");
scanf("%d", &length1);
printf("Please provide the length of the second Sequence\n");
scanf("%d", &length2);
X = (char*)malloc(sizeof(char) * length1);
Y = (char*)malloc(sizeof(char) * length2);
int m = length1 + 1;
int n = length2 + 1;
int L[m][n];
int backtracking[m + n];
gen_random(X, length1);
gen_random(Y, length2);
printf("First Sequence\n");
for (i = 0; i < length1; i++) {
printf("%c\n", X[i]);
}
printf("\nSecond Sequence\n");
for (i = 0; i < length2; i++) {
printf("%c\n", Y[i]);
}
// Time calculation beginning.
beginning_time = clock();
// Main Part--Core of the algorithm.
for (i = 0; i <= m; i++) {
for (j = 0; j <= n; j++) {
if (i == 0 || j == 0) {
L[i][j] = 0;
} else
if (X[i-1] == Y[j-1]) {
L[i][j] = L[i-1][j-1] + 1;
backtracking[i] = L[i-1][j-1];
} else {
L[i][j] = maxfunction(L[i-1][j], L[i][j-1]);
backtracking[i] = maxfunction(L[i-1][j], L[i][j-1]);
}
}
}
// End time calculation.
end_time = clock();
for (i = 0; i < m; i++) {
printf(" ( ");
for (j = 0; j < n; j++) {
printf("%d ", L[i][j]);
}
printf(")\n");
}
// Printing out the result of backtracking.
printf("\n");
for (k = 0; k < m; k++) {
printf("%d\n", backtracking[k]);
}
printf("Consumed time: %lf", (double)(end_time - beginning_time));
return 0;
}
// Max Function.
int maxfunction(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}
// Random Sequence Generator Function.
void gen_random(char *s, const int len) {
int i = 0;
static const char alphanum[] = "ACGT";
for (i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
Since you null terminate the sequence in gen_random with s[len] = 0;, you should allocate 1 more byte for each sequence:
X = malloc(sizeof(*X) * (length1 + 1));
Y = malloc(sizeof(*Y) * (length2 + 1));
But since you define variable length arrays for other variables, you might as well define these as:
char X[length1 + 1], Y[length2 + 1];
Yet something else is causing a crash on my laptop: your nested loops iterate from i = 0 to i <= m, and j = 0 to j <= n. That's one step too many, you index out of bounds into L.
Here is a corrected version:
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
The resulting code executes very quickly, its complexity is O(m*n) in both time and space, but m and n are reasonably small at 35. It runs in less than 50ms for 1000 x 1000.
Whether it implements Smith-Waterman's algorithm correctly is another question.
While trying to craft up a mergesort in C as an exercise, I am encountering a weird issue where the output of the algorithm changes with the presence of a printf. Let me elaborate it further. I have a "MergeSort.h" file in which I have my mergesort algorithm as follows:
#ifndef _MSORT_H_
#define _MSORT_H_
void merge(int a[],int lo,int mi,int hi){
int n1 = (mi - lo) +1;
int n2 = hi - mi;
int left[n1];
int right[n2];
int i;
int j;
int k;
for(i = 0;i < n1;i++){
left[i] = a[lo+i];
}
for(j = 0;j < n2;j++){
right[j] = a[mi+j+1];
}
i = 0;
j = 0;
for(k = lo;k <= hi;k++){
if(left[i] < right[j]){
a[k] = left[i];
i = i + 1;
}else{
a[k] = right[j];
j = j+1;
}
}
}
void msorthelper(int a[],int p,int r){
if(p < r){
int mid = (p + r)/2;
msorthelper(a,0,mid);
msorthelper(a,mid+1,r);
merge(a,p,mid,r);
}
}
void msortex(int a[],int size){
msorthelper(a,0,size-1);
int counter;
for(counter = 0;counter < size;counter++){
printf(" %d ",a[counter]);
}
}
#endif
I have my corresponding sort tester in sorttester.c:
#include <stdio.h>
#include "mergesort.h"
int main(){
int out[] = {8,1,6};
msortex(out,3);
}
The output from running the sorttester is as follows:
1 0 0
Now here's the interesting part, when I put any printf statement to the beginning of the merge, the correct output is generated. Here's an example:
#ifndef _MSORT_H_
#define _MSORT_H_
void merge(int a[],int lo,int mi,int hi){
printf("Hello\n");
int n1 = (mi - lo) +1;
int n2 = hi - mi;
int left[n1];
int right[n2];
.................Rest of the code.....
The output now is:
HelloHello 1 6 8
This is the correct sorted order for the array 8 6 1.
Can somebody tell me what I might be doing wrong here that is causing the output to be drastically by the presence of a printf?
Thanks
Have a look at your merging part of code:
for(k = lo;k <= hi;k++){
if(left[i] < right[j]){
a[k] = left[i];
i = i + 1;
}else{
a[k] = right[j];
j = j+1;
}
}
Lets assume that
left[] = {1, 2}
right[] = {3, 4, 5}
After 2 iterations of your merging loop (k) the value of "i" will be 2. From now on, you will try to compare
left[2] < right[j]
Which is invalid, as left[2] will refer to some random memory (left array size is only 2, so element of index 2 doesnt exist, only 0 and 1)
So, if you add guards for the i and j values, for example by changing first if condition to:
if(i != n1 && (j == n2 || left[i] < right[j])){
You should be fine.
Anyway, I should also tell you that you shouldnt declare array sizes with values that are not const, like:
int left[n1];
int right[n2];
Its actually forbidden by standard. You should either allocate it dynamically, use vectors(if c++) or jus declare them global with large enough size (maximum n value)