I'm trying to do a convolution algorithm in C but is stacking on the array of convolution.
#include <stdio.h>
#include <math.h>
#include <stddef.h>
#define convtotal 2590
int main(int argc, char *argv[]) {
int m,n,i,j;
double x[convtotal],h[convtotal];
m=sizeof(x)/sizeof(double);
n=sizeof(h)/sizeof(double);
double aux1[convtotal], aux2[convtotal],conv[convtotal][1];
for (i=0;i<n+m;i++){
if (i<n)
aux1[i]=x[i];
else
aux1[i]=0;
if (i<m)
aux2[i]=h[i];
else
aux2[i]=0;
}
for (i=0;(n+m-1);i++){
conv[i][1]=0;
for (j=0;j<m;j++)
if (i-j+1>0)
conv[i][1]=conv[i][1]+(aux1[j]*aux2[i-j+1]);
}
}
Any suggestions for this problem?
Two problems:
for (i=0;(n+m-1);i++)
You're not limiting i to anything, so the loop doesn't exit when you reach the end of your arrays; it just keeps incrementing i until you hit memory you don't own, at which point you get the segfault. Since conv only goes to m or n, I think you meant to write
for (i = 0; i < n; i++)
Secondly, you declared conv as an Nx1 array, meaning the only legal index in the second dimension may be 0, so the lines
conv[i][1] = 0;
and
conv[i][1]=conv[i][1]+(aux1[j]*aux2[i-j+1]);
should be
conv[i][0] = 0;
and
conv[i][0]=conv[i][0]+(aux1[j]*aux2[i-j+1]);
Not sure why you declared an Nx1 array (seems you could have just declared conv with one dimension), but I may be missing something obvious.
Note that your x and h arrays initially contain random values.
for (i=0;(n+m-1);i++){
conv[i][1]=0;
for (j=0;j<m;j++)
if (i-j+1>0)
conv[i][1]=conv[i][1]+(aux1[j]*aux2[i-j+1]);
}
(n+m-1) infinite loop with constant as a stop condition.
Not actually infinite, runs untill it segfaults.
for (i=0;(n+m-1);i++){
Shouldn't it be i < m+ n - 1?
Related
I am quite new to C so my apologies if this is a straight forward problem but I cannot seem to find my error. My code is as follows
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* makeString(char character,int count)
{
int i;
char* finalString=malloc(count+1);
for(i=1;i<=count;i++)
{
finalString[i]=character;
}
finalString[count]=0;
return finalString;
}
int main()
{
char* string=makeString('*',5);
printf("%s\n",string);
}
I am trying to get an output of the finalString which would be 'character', 'count' number of times. I am not getting any errors or warnings but It is not generating any output. When debugging it runs the loop successfully but does not ever store any character into finalString. Any help appreciated.
As with many programming languages, C uses 0-based indices for arrays. The first element of the character array at finalString is finalString[0], not finalString[1].
Your for loop should go from 0 to count - 1, instead of from 1 to count. The line:
for(i = 1; i <= count; i++)
should instead be:
for(i = 0; i < count; i++)
As your code is now, you have undefined behaviour, because you try to print finalString[0], which is uninitialized. In this case, it seems to be 0 ('\0').
I've ignored the fact that makeString is missing its closing }, since you say this compiles correctly, I assume that's a pasting error.
Arrays in C begin at 0, i.e. the 1st element is finalString[0].
Since you do not set it, it contains garbage, and most probably a NUL which ends the string immediately.
Your loop should look like
for(i=0;i<count;i++)
...
and so on.
What is the problem with the following code? C compiler shows me error: Segmentation fault.
#include <stdio.h>
#include <math.h>
int main() {
int n = 4;
float A[n][n][n][n];
A[n][n][1][1] = 1;
A[n][n][1][2] = 0;
A[n][n][1][3] = -3;
A[n][n][1][4] = 0;
A[n][n][2][1] = 1;
A[n][n][2][2] = 0;
A[n][n][2][3] = -3;
A[n][n][2][4] = 0;
return 0;
}
All these assignments access memory outside the defined variable length array.
A[n][n][1][1]=1;
A[n][n][1][2]=0;
A[n][n][1][3]=-3;
A[n][n][1][4]=0;
A[n][n][2][1]=1;
A[n][n][2][2]=0;
A[n][n][2][3]=-3;
A[n][n][2][4]=0;
That is the valid range of indices for each dimension of the array is [0, n ). Thus the expression A[n] is invalid.
It seems you mean the following assignments
A[0][0][0][0]=1;
A[0][0][0][1]=0;
A[0][0][0][2]=-3;
A[0][0][0][3]=0;
A[0][0][1][0]=1;
A[0][0][1][1]=0;
A[0][0][1][2]=-3;
A[0][0][1][3]=0;
If you define an array of length N, the access to the last element is at the N-1 index, and the access to the first element is at index 0 because indexes start from 0 and end at N-1.
So your code should be like this:
#include<stdio.h>
#include<math.h>
#define N 4
int main() {
float A[N][N][N][N];
A[N-1][N-1][0][0]=1;
A[N-1][N-1][0][1]=0;
A[N-1][N-1][0][2]=-3;
A[N-1][N-1][0][3]=0;
A[N-1][N-1][1][0]=1;
A[N-1][N-1][1][1]=0;
A[N-1][N-1][1][2]=-3;
A[N-1][N-1][1][3]=0;
return 0;
}
Also, you're using a variable to define the length of your array, which is good only in the C99 standard and onwards. If you don't need a VLA (variable length array), you should use the #define instead.
int n=4;
float A[n][n][n][n];
A[n][n][1][1]=1;
is not valid in every C standard (read n1570 or better). You may want to code const int n=4; or #define n 4
(on cheap microcontrollers you might not even have enough stack space for 256 floats -> possible stack overflow)
And then, you always have a buffer overflow (read about undefined behavior). In A[x][x][1][1] the valid indexes are from x being 0 to x being 3 -that is n-1 - (not 4).
You might want to code
A[n-1][n-1][1][1] = 1;
but you should know that A[0][0][0][0] is being uninitialized. It may contain garbage (signalling NaN), and an hypothetical printf("%f\n", A[0][0][0][0]); could fail ....
I guess that Frama-C would have caught your mistake (I leave you to check that). Be aware of Rice's theorem.
I would initialize A with zeros (to ease debugging, and to have more reproducible runs) -after having corrected the buffer overflow-:
float A[n][n][n][n]={0.0};
This is an unfinished program I'm writing to learn C (only checks multiples of 2 currently...)
Ultimately, I want this to be an implementation of the Sieve of Eratosthenes (prime numbers)
The problem I'm having is that the output is non-deterministic: sometimes the output includes 11, other times it does not - This happens for a handful of numbers. I have experimented by changing a few things, such as actually initializing the array of booleans to false.
Any ideas why this might be happening?
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(int argc, char *argv[]) {
int n = atoi(argv[1]);
int initialPrimeIterator = 2;
_Bool compositePrimeNumbers[n];
printf("Prime Numbers from 2 -> %d\n", n);
for (int i = initialPrimeIterator; i < n; i += initialPrimeIterator) {
compositePrimeNumbers[i-1] = true;
}
printf("Done...\n");
printf("Printing prime numbers from 2-> %d\n", n);
for (int i = 2; i < n; i++) {
if (!compositePrimeNumbers[i]){
printf("%d\n", i + 1);
}
}
return 0;
}
edit: haha. Just realized I have an array named 'compositePrime...' Should just be 'compositeNumbers'
Since I understand you are aiming at completing the program when overcoming this hurdle, I will not post a completed program, but only point out issues in your current version:
As it has been noted, the array compositePrimeNumbers is uninitialized. Since it must be initialized with all values false which is represented by 0, the quickest way is this:
memset(compositePrimeNumbers, 0, sizeof(compositePrimeNumbers));
You should not mark the current initialPrimeIterator as a composite number, hence the for-loop should start with the next multiple. Also, n must be included:
for (int i = 2 * initialPrimeIterator; i <= n; i += initialPrimeIterator) {
(actually, this can be optimized by replacing 2 * initialPrimeIterator with initialPrimeIterator * initialPrimeIterator).
With these changes, I believe you are well on the way to complete the program.
In C, a local array is not initialized, probably for performance reasons.
One way to fix this is to loop over it to set each element to false.
Write a program that will create an integer array with 1000 entries. After creating the array, initialize all of the values in the array to 0. Next, using the rand function, loop through the array and save a random number between 1 and 10 (inclusive) in each entry of the array.
This is for my homework due tomorrow but I need some help with it since I'm barely a beginner at code.
This is the only code I've made so far with single dimensional arrays
#include <stdio.h>
#include <stdlib.h>
int mean(int array[], int size);
int main()
{
int i;
int array[5]={5, 1, 3, 2, 4};
for (i=0; i<5; i++)
{
printf("%d", array[i]);
}
printf("\nThe mean is %d", mean(array,5));
return 0;
}
int mean(int array[], int size)
{
int i, sum = 0;
for (i=0; i<5; i++)
{
sum=sum + array[i];
}
return sum/5;
}
Not sure why you wrote a program to calculate the mean, given that there's nothing in the requirements about that.
However, you just have to think about the steps. Note that the following example do not perfectly match what you need, they're there just to show you the method, not to be cut and pasted into your assignment.
First, you can create an array of size (for example) seven with the statement:
int value[7];
You can then set all elements to a given value with:
for (size_t idx = 0; idx < sizeof(value) / sizeof(*value); idx++)
value[idx] = 42;
(although, at the level of your assignment, it's probably better to use 7 rather than the sizeof expression).
In order to generate random numbers, you first include the requisite header and, as the first thing in main(), set the seed to something "random":
#include <stdlib.h>
#include <time.h>
:
srand (time (0));
Then, at the time when you need to generate a random number from one to fifty inclusive, you can use:
int rnum = rand() % 50 + 1;
(keeping in mind the distribution won't be perfect but it should be more than good enough for the intended purpose here).
Whatever loop you chose above to initialise the array elements to 42 (or zero) can also be used to set them to random values.
That should be enough to get you started.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int prime(long long int);
long long int *arr; //array to hold n prime numbers
int main()
{
int i,count=4;;
long long int n;
scanf("%lli",&n);
arr=malloc(sizeof(long long int)*n);
arr[0]=2;
arr[1]=3;
arr[2]=5;
arr[3]=7;
if (n==1) printf("%lli",arr[0]);
else{ if (n==2) printf("%lli",arr[1]);
else{ if (n==3) printf("%lli",arr[2]);
else{ if (n==4) printf("%lli",arr[3]);
else
{
for(i=2;count<n;i++)
{
if(prime(6*i-1)) { /*As prime nos are always 6k+1 or
arr[count]=6*i-1; 6k-1fork>=2 I checked only for those*/
count++; }
if(prime(6*i+1)&&count<=n) {
arr[count]=6*i+1;
count++; }
}
printf("%lli",arr[count]);
}}}}
//free(arr);
return 0;
}
int prime(long long int x)
{
int j=1,flag=1;
while(arr[j]<=sqrt(x))
{
if (x%arr[j]==0)
{
flag=0;
break;
}
j++;
}
return flag;
}
The code is working only for n=1,2,3,4, i.e i=0,1,2,3 for which the values are explicitly given. For n=5 onwards it is giving 0 as O/P
There is some glitch related to the global dynamic array as free(arr) is giving core dump error.
Q: Is this the right way to declare a global dynamic array? What could be the problem in this code?
Thank You in advance.
If that is your actual code you have 4 bugs:
2 line comment scopes out a line of your code
the second if should check count < n not count <= n as if count == n you cannot write to arr[count]
You cannot print arr[count] only arr[count-1] which is probably what you mean
In the case where n is less than 4 you still set arr[1], arr[2] and arr[3] which may be out of bounds
It is of course also inefficient to call sqrt(x) in every loop iteration, potentially you should call it outside and there may be a potential rounding issue bug due to the way square roots are calculated, so you might prefer:
while( arr[j] * arr[j] < x )
It would be preferable not to make this global and to pass it into your function.
It would also be preferable to move the main loop logic of your program outside of main().
I'm surprised you say you program works for n=1, 2 and 3 as it looks like you are setting out of bounds.
Your counter goes beyond the size of the array. Specifically both conditions (6i-1 and 6i+1) are met for i=2, and therefore counter is incremented twice, resulting in using arr[5] where you only allocated 5 places in the array. This is because you check counter<=n and not counter
Not sure this could be also be the reason for free creating a core dump, but it is possible (because once corrupting the memory, free may access corrupted data).