How to create a dynamically sized global array? - c

I am making a multi-threaded program to find prime numbers in C. How do I take an input in the following C program and not use (#define N =88)?
I am getting the following error:
main.c:8:7: error: expected declaration specifiers or ‘...’ before string constant
scanf("%d", &N);
^~~~
#include <stdio.h>
#include <pthread.h>
#include <conio.h>
#define MAX_THREADS 4
int N;
scanf("%d", &N);
int prime_arr[N]={0};
void *printprime(void *ptr)
{
int j,flag;
int i=(int)(long long int)ptr;
while(i<N)
{
printf("Thread id[%d] checking [%d]\n",pthread_self(),i);
flag=0;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
{
flag=1;
break;
}
}
if(flag==0 && (i>1))
{
prime_arr[i]=1;
}
i+=MAX_THREADS;
}
}
int main()
{
pthread_t tid[MAX_THREADS]={{0}};
int count=0;
for(count=0;count<MAX_THREADS;count++)
{
printf("\r\n CREATING THREADS %d",count);
pthread_create(&tid[count],NULL,printprime,(void*)count);
}
printf("\n");
for(count=0;count<MAX_THREADS;count++)
{
pthread_join(tid[count],NULL);
}
int c=0;
for(count=0;count<N;count++)
if(prime_arr[count]==1)
printf("%d ",count);
return 0;
}

You can't have general statements outside of functions.
The simple solution is to read the input in the main function and then create the array in the main function as well.
And keep the array as a local variable inside the function, and pass it as an argument to the functions to call (together with its size).
To mass multiple arguments to the thread function, create a structure with the "arguments" as members, and pass a pointer to one such structure.

Related

Some problem in package function(Wrapper function )in C .How do i package a founction and let the callee founction return multipe values or structure

There are some problems thatconfuse me:
The callee function needs return a structure, but there is not a structure statment in caller function.
If i have to write the declaration in the calling function,it can not be called packaging function.
If i return a structure pointer by callee function, but the structure is in the stack of the called function and will be destroyed after the end, which is not safe. Sometimes i get some warning or even wrong!
I have a limited ideas but it not good. I put the structure into the heap by malloc and return the void*pointer. But this gave birth to a new problem :after each call to this function, in the caller, I cannot release the heap through the free() function,the complier can not identify variable name of structure pointer. I think it verey dangerous. I want when the callee function quit,it can be released by itself.
This is the first time I came to this website to ask questions and I just came into contact with c language,If there is something stupid please point it out.
I have to write the structure declaration outside. This program for judging prime number, and I want to package the founction "judging_number". I do not want to write the structure declaration when I want to call the founction "judging_number".
Please give me some help, I would be very grateful.
Sorry, this is my fault. I compiled it with clang++, I saved it as *.cpp, but I wrote c code in it.
What I mean is, can I put the declaration in the called function to realize the function modularization, how can I not declare a structure before calling the function? Is there any way I can not write a declaration. Like use founction in stdio.h.It is as convenient as using the functions of the standard library. Only need to write a line of function call and pass parameters, the called function can return multiple results.
#include <stdio.h>
struct boundary{
int L;
int R;
};boundary *range;
int *get_number()
{
int *nPtr = (int *)malloc(sizeof(int));
do
{
printf("Please enter a vaild number for judging prime number.Or enter the number 1 to quit.\r\n");
scanf("%d", nPtr);
if (*nPtr == 1)
{
exit(1);
}
} while (*nPtr < 1);
printf("The object is %d\r\n", *nPtr);
return nPtr;
}
int judg_number(int N,boundary range){
if (N%range.L==0&&N!=2){
printf("The number %d is a composite number.\r\n", N);
}
else{
printf("The number %d is a prime number.\r\n", N);
}
return 0;
}
boundary* get_range(int N){
boundary *Ptr = (boundary *)malloc(sizeof(boundary));
*Ptr = {2,N-1};
printf("The range is between %d and %d .\r\n", Ptr->L, Ptr->R);
return Ptr;
}
int main(int argc,char**argv,char**env){
int*N;
while(1){
N=get_number();
range=get_range(*N);
judg_number(*N, *range);
free(N);
free(range);
}
getchar();
getchar();
return 0;
}
You dont need dynamic memory allocation here. If you want to retun an int, retun an int. If you want to retun a stuct return a struct.
You probably want this:
#include <stdio.h>
#include <stdlib.h>
struct boundary {
int L;
int R;
};
struct boundary range;
int get_number()
{
int n;
do
{
printf("Please enter a vaild number for judging prime number.Or enter the number 1 to quit.\r\n");
scanf("%d", &n);
if (n == 1)
{
exit(1);
}
} while (n < 1);
printf("The object is %d\r\n", n);
return n;
}
int judg_number(int N, struct boundary range) {
if (N % range.L == 0 && N != 2) {
printf("The number %d is a composite number.\r\n", N);
}
else {
printf("The number %d is a prime number.\r\n", N);
}
return 0;
}
struct boundary get_range(int N) {
struct boundary b = { 2, N - 1 };
printf("The range is between %d and %d .\r\n", b.L, b.R);
return b;
}
int main(int argc, char** argv, char** env) {
int N;
while (1) {
N = get_number();
range = get_range(N);
judg_number(N, range);
}
getchar();
getchar();
return 0;
}
BTW:
boundary get_range(int N) {... is invalid in C but valid in C++. In C it should be struct boundary get_range(int N) {...

How to pass an array of structures in a function? [duplicate]

This question already has answers here:
How do I pass an array of structures to a function?
(3 answers)
Closed 1 year ago.
About to ready to give up on this
Been having an issue with my code for hours, has been telling me I have an error about the error: expected expression before 'Robot_t' and cannot find a solution, if anyone has a working solution you will save me
This is the error message provided
Arrayintofn.c: In function 'main':
Arrayintofn.c:23:23: error: expected expression before 'Robot_t'
loading_Profiles (Robot_t RobotInfo[]);
No matter what I do or who I consult there is no solution
Here is the code as well
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <string.h>
typedef struct
{
int Robot_Number;
char Robot_Name[30];
int Year_Manufacturer;
float Top_Speed;
float Mass;
float Best_Score;
} Robot_t;
void loading_Profiles();
int main()
{
Robot_t RobotInfo[5];
loading_Profiles (Robot_t RobotInfo[]);
int i;
for (i = 0; i < 50; i++) {
printf("%d\t\t%s\t\t%d\t\t\t%.2f\t\t%.2f\t\t%.2f\n",
RobotInfo[i].Robot_Number, RobotInfo[i].Robot_Name,
RobotInfo[i].Year_Manufacturer, RobotInfo[i].Top_Speed,
RobotInfo[i].Mass, RobotInfo[i].Best_Score);
}
return 0;
}
void loading_Profiles()
{
int Counter = 0;
int i;
Robot_t RobotInfo[5];
FILE *ROBOTtxt = fopen("Robot.txt", "r");
if (ROBOTtxt == NULL) {
perror("an error occured during the loading of the file\n");
exit(-1);
}
for (i = 0; i < 50; i++) {
char LineNumber[100] = "";
fgets(LineNumber, 100, ROBOTtxt);
sscanf(LineNumber, "%d %s %d %f %f %f",
&RobotInfo[i].Robot_Number,
RobotInfo[i].Robot_Name,
&RobotInfo[i].Year_Manufacturer,
&RobotInfo[i].Top_Speed,
&RobotInfo[i].Mass,
&RobotInfo[i].Best_Score);
Counter++;
if (feof(ROBOTtxt)) {
break;
}
}
if (ferror(ROBOTtxt)) {
perror("an error has occured");
exit(-1);
}
fclose(ROBOTtxt);
}
Your function loading_Profiles() written like this doesnt accept any parameters but you pass an array in the main function. You should rewrite the declaration as
"void loading_Profiles(Robot_t arr_name[])"
In the main function you should pass an argument only by its name. So instead of this:
"loading_Profiles(Robot_t RobotInfo[]);"
just pass:
"loading_Profiles(RobotInfo);"
There were a number of errors in your code, I'll paste my commented solution below, but for reference:
in the loading_Profiles prototype you weren't specifying a parameter
in the main, you were calling the function uncorrectly
inside the loading_Profiles implementation, you were trying to work on a local array, and not the one passed as an argument.
Also, sometimes you were using 50, sometimes 5? Which is it?
Here's the code, tested using a file generated on Mockaroo.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <string.h>
typedef struct
{
int Robot_Number;
char Robot_Name[30];
int Year_Manufacturer;
float Top_Speed;
float Mass;
float Best_Score;
} Robot_t;
void loading_Profiles(Robot_t RobotInfo[]); // added parameter to prototype
int main()
{
Robot_t RobotInfo[50]; // 50 instead of 5
loading_Profiles(RobotInfo); // simply pass your variable
int i;
for (i = 0; i < 50; i++) {
printf("%d\t\t%s\t\t%d\t\t\t%.2f\t\t%.2f\t\t%.2f\n",
RobotInfo[i].Robot_Number, RobotInfo[i].Robot_Name,
RobotInfo[i].Year_Manufacturer, RobotInfo[i].Top_Speed,
RobotInfo[i].Mass, RobotInfo[i].Best_Score);
}
return 0;
}
void loading_Profiles(Robot_t RobotInfo[]) // added parameter
{
int Counter = 0;
int i;
FILE *ROBOTtxt = fopen("Robot.txt", "r");
//Robot_t RobotInfo[5]; // removed, work on the array passed as argument, not a local one
if (ROBOTtxt == NULL) {
perror("an error occured during the loading of the file\n");
exit(-1);
}
for (i = 0; i < 50; i++) {
char LineNumber[100] = "";
fgets(LineNumber, 100, ROBOTtxt);
sscanf(LineNumber, "%d %s %d %f %f %f",
&RobotInfo[i].Robot_Number,
RobotInfo[i].Robot_Name,
&RobotInfo[i].Year_Manufacturer,
&RobotInfo[i].Top_Speed,
&RobotInfo[i].Mass,
&RobotInfo[i].Best_Score);
Counter++;
if (feof(ROBOTtxt)) {
break;
}
}
if (ferror(ROBOTtxt)) {
perror("an error has occured");
exit(-1);
}
fclose(ROBOTtxt);
}
Let me know if it works
While declaring parameter for the function you need to specify variable type as structure and create an array of structure type.
void loading_Profiles(Robot_t RobotInfo[]) // added parameter

How to print an Array of strings after passing it to another function [duplicate]

This question already has an answer here:
Array of strings won't print
(1 answer)
Closed 2 years ago.
After receiving a certain number of students and their names, the program stops after passing it to another function to print it. How do I change this?
#include <stdio.h>
#define MAX_STUDENT 1024
void print_name(char* surname,char* first_name,int n_students)
{
int i,b=1;
for(int i=0;i<n_students;i++)
{
printf("%d. %s, %s\n",b,first_name[i],surname[i]);
b++;
}
}
int main()
{
int n_students,i,b=1;
char surname[MAX_STUDENT][20],first_name[MAX_STUDENT][20];
printf("number of students:");
scanf("%d",&n_students);
for(i=0;i<n_students;i++)
{
printf("%d. ",b);
scanf("%19s %19s",&surname[i],&first_name[i]);
b++;
}
print_name(surname,first_name,n_students);
return 0;
}
Match types between function arguments and what are passed. In main, you are passing 2D-arrays as arguments of print_name function , but the you are using character pointers as arguments in definition of print_name function
Remove & from arguments of scanf() to pass data having correct type and avoid undefined behavior.
#include <stdio.h>
#define MAX_STUDENT 1024
void print_name(char surname[][20],char first_name[][20],int n_students) /* fix 1 */
{
int i,b=1;
for(int i=0;i<n_students;i++)
{
printf("%d. %s, %s\n",b,first_name[i],surname[i]);
b++;
}
}
int main()
{
int n_students,i,b=1;
char surname[MAX_STUDENT][20],first_name[MAX_STUDENT][20];
printf("number of students:");
scanf("%d",&n_students); /* note: & here is necessary */
for(i=0;i<n_students;i++)
{
printf("%d. ",b);
scanf("%19s %19s",surname[i],first_name[i]); /* fix 2 */
b++;
}
print_name(surname,first_name,n_students);
return 0;
}

my terminal is only printing the first output from main

beginner to C here, and I am having trouble printing the words "one" in int one_three() and "two" in in the function().
the only words printing in my terminal is "starting now" - is anyone anyone aware as to why this is happening?
Any help would be very much appreciated.
int one_three();
int two();
int main(void)
{
// Countdown begins
printf("starting now: ");
printf("\n");
int one_three();
int two();
return 0;
}
int one_three()
{
printf("one");
int two();
return 0;
}
int two()
{
printf("two");
return 0;
}
You don't call the functions, you declare the functions (again).
To call e.g. one_three then you do
one_three();
And speaking about function declarations, in C you must explicitly use void as argument if a function doesn't take any arguments. A declaration such as
int two();
tells the compiler that the function two returns an int, and takes an unknown number of unspecified arguments. The proper declaration would be
int two(void);
int one_three();
int two();
int main(void)
{
// Countdown begins
printf("starting now: ");
printf("\n");
one_three();
two();
return 0;
}
int one_three()
{
printf("one");
two();
return 0;
}
int two()
{
printf("two");
return 0;
}
While calling the function you should not declare the type(ie. char, int or float).
You should change the code like this.
...
int main(void)
{
// Countdown begins
printf("starting now: ");
printf("\n");
one_three();
two();
return 0;
}
...
You have declared functions again inside main(). That's why printing only "starting now". You need to call that function from main() like this:
int main(void)
{
// Countdown begins
printf("starting now: ");
printf("\n");
one_three();
two();
return 0;
}
Let me explain you some basics.
The first two lines in your code
int one_three();
int two();
- are function declarations or function prototypes which tells the compiler that there is a function definition after the main function.
If you don't want it, you can keep the function definitions before main function.
int one_three()
{
printf("one");
int two();
return 0;
}
int two()
{
printf("two");
return 0;
}
int main(void)
{
// Countdown begins
printf("starting now: ");
printf("\n");
one_three(void);
two(void);
return 0;
}
You're re-declaring the functions again in main(), where you need to call them.
Pass a actual argument as void if you're not passing any value or reference.
Since you're returning 0 from those functions the return type is int, which will be fine.
int main(void)
{
// Countdown begins
printf("starting now: ");
printf("\n");
one_three(void);
two(void);
return 0;
}

Calling pthread_create error - expected primary expression before 'void'

This is a Matrix multiplication code. It creates a thread to multiply each row of the first matrix to the second matrix and saves the result in matrix C.
It gives an error in the pthread_create line expected primary-expression before 'void'.
I run this code on ubunto 13.10 virtual machine.
Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
struct matrices
{
int matrixA[10][10];
int matrixB[10][10];
int matricC[10][10];
int r1,r2,c1,c2;
}*ptr;
int p;
void *matrixMul(void *);
int main()
{
int i=0,j=0;
pthread_t threads[10];
ptr=(struct matrices*)malloc(sizeof(struct matrices));
printf("Enter size of first matrix(Rows then Columns)");
scanf("%d",&(ptr->r1));
scanf("%d",&(ptr->c1));
printf("Enter elements of first array : ");
for(i=0; i<ptr->r1; i++)
{
for(j=0; j<ptr->c1; j++)
{
scanf("%d",&ptr->matrixA[i][j]);
}
}
printf("Enter size of second matrix(Rows then Columns)");
scanf("%d",&(ptr->r2));
scanf("%d",&(ptr->c2));
if(ptr->c1!=ptr->r2)
{
printf("Dimensions ERRORR! ");
}
else
{
printf("Enter elements of second array : ");
for(i=0; i<ptr->r2; i++)
{
for(j=0; j<ptr->c2; j++)
{
scanf("%d",&ptr->matrixB[i][j]);
}
}
for(i=0;i<ptr->r1;i++)
{
for(j=0;j<ptr->c2;j++)
{
ptr->matricC[i][j]=0;
}
}
for (p=0;p<ptr->r1;p++)
{
**********pthread_create(&threads[p],NULL, *matrixMul,void &p);**********
}
for(i=0;i<ptr->r1;i++)
{
pthread_join(threads[i],NULL);
}
for(i=0;i<ptr->r1;i++)
{
for(j=0;j<ptr->c2;j++)
{
printf("%d",ptr->matricC[i][j]);
}
}
}
return 0;
}
void *matrixMul(void *rownum)
{
int *i;
int n=0,m=0;
i=(int*)rownum;
for(n=0;n<ptr->c2;n++)
{
for(m=0;m<ptr->c1;m++)
{
ptr->matricC[*i][n]+=(ptr->matrixA[*i][m])*(ptr->matrixB[m][n]);
}
}
return NULL;
}
Your code contains minor error, but the logic is correct, don't worry.
I downloaded the code and tested it on my machine, so please note the following:
This line should be written this way...
pthread_create(&threads[i],NULL, matrixMul, &i);
Because according to the specs of pthread library that pthread_create should take void pointer to the runner function and void pointer to the parameter. You don't need to add (void *) because you already declared your runner function matrixMul as void *.
Your primary error here was (void) &i and it should be &i only as you already delcaired this parameter as void * in the runner function's prototype. You shall too pass the runner function like this &matrixMul.
Some other notes: "Code Review"
You shouldn't put your logic in the else statement, you can simply after printf("Dimensions ERRORR! "); write exit(-1); because this is basically what you do if the dimensions error.
Check for the return value (status) of pthread_create and pthread_join

Resources