typedef struct line {
int a;
int b;
} line;
int main() {
line *v;
int c, d, j;
char a;
int i;
scanf("%d", &n)
for (i = 0; i < n; i++) {
scanf("%c", &a);
v = (line*) malloc(n * sizeof(line));
if (a == '+') {
scanf("%d %d", &v[j]->a, &v[j]->b);
}
}
I want to make an array that holds a struct info, and then use that info in my function . But I am getting some errors and I don't know if I used well the pointer.
I have tried with v[j].a but it didn't work. (I used this because I am more familiar from linked-list.)
Use &(v[j].a) instead, which is equal to &((v+j)->a). The name of an array is a pointer to the first element. So v[j] is an element of type struct line. In order to get one of its fields you use .a.
Also, check your code for some other errors because some variebles are not initialized.
First of all you malloc a new memory on every iteration and the previous one becomes unavailable.
Abstracting from the logic of the program
typedef struct line {
int a;
int b;
} line;
int main(void) {
line *v;
int c, d, j;
char a;
int i,n;
scanf("%d", &n);
v = malloc(n * sizeof(line));
if(v == NULL) return -1;
for (i = 0; i < n; i++) {
scanf("%c", &a);
if (a == '+') {
scanf("%d %d", &v[j].a, &v[j].b);
}
}
}
Related
I am relatively new to programming. I have been working on a project that takes the users input passes it to a function that finds the factors of the number, stores them in an array (only for 100 factors max) and then returns the array to the main program. Once I call the array to the main program, then print it using a for loop i run into an issue. I need a counter to figure out the size of the array to figure out how many times to run the for loop.
So far I have tried to use a pointer to count the first loop and send it to the main function with no luck. The only thing that works is a global variable, but for obvious reasons I would prefer not to do that.
#include <stdio.h>
#define MAX_SIZE 100
int* get_factors(int number)
{
int x;
int z;
int y = 0;
static int arr[MAX_SIZE];
for(x=1; x <= number; ++x)
{
if (number%x == 0)
{
arr[y] = x;
y++;
}
}
return arr;
}
int main(void)
{
int *num;
int temp;
int z = 0;
printf("Enter a number: ");
scanf("%d",&temp);
printf("Factors of %d: ", temp);
num = get_factors(temp);
for(z=0; z<=20; z++) //This is the loop that i need to figure out a
counter for
{
printf("%d ", num[z]);
}
return 0;
}
#include <stdio.h>
#define MAX_SIZE 100
struct myObject {
int arr[MAX_SIZE];
int index;
};
struct myObject
get_factors (int number)
{
int x;
struct myObject holder;
holder.index = 0;
for (x = 1; x <= number; ++x)
{
if (number % x == 0)
{
holder.arr[holder.index] = x;
holder.index++;
}
}
return holder;
}
int
main (void)
{
struct myObject num;
int temp;
int z;
printf ("Enter a number: ");
scanf ("%d", &temp);
printf ("Factors of %d: ", temp);
num = get_factors (temp);
for (z = 0; z < num.index; z++) //This is the loop that i need to figure out a
//counter for
{
printf ("%d ", num.arr[z]);
}
return 0;
}
If you change your function interface design, it could be easier to pass that information.
The idiomatic way to pass array in C function is via parameter, where the first paramenter is the array itself, and the second parameter is it maximun length.
In this way your function is not more responsible for allocating or deallocating the array. In other words, it does not own it anymore.
In your case, you can use the function return to pass the amount of slots used in this array and, on error, just a negative number.
In this way, your program can be something like that:
int get_factors(int number, int number[], size_t length)
{
int x;
int z;
int y = 0;
if ( number > length ) return -1;
for(x=1; x <= number; ++x)
{
if (number%x == 0)
{
arr[y] = x;
y++;
}
}
return y;
}
and at call site:
int main(void) {
int num[MAX_SIZE];
int temp;
int z = 0;
printf("Enter a number: ");
scanf("%d",&temp);
printf("Factors of %d: ", temp);
int slots = get_factors(temp, num, MAX_SIZE);
for(z=0; z<=slots; z++) //This is the loop that i need to figure out a
printf("%d ", num[z]);
return 0;
}
So I have a problem:
My program has to find the most common element in an array. We have to make this array with calloc. My code is working but I am asked to move part of my code to a function in which I have to create an array and enter numbers.
int main() {
int n, i, dazn;
int *A;
dazn = 0;
printf("Iveskite naturalu skaiciu: \n");// enter how many elements in an array we will have
scanf("%d", &n);
A = (int*)calloc(n, sizeof(int)); // Starting from here...
for (i = 0; i < n; i++) {
printf("Iveskite skaiciu \n");
scanf("%d", &A[i]); //
}
... // and ending here have to be in a function
... // sorting and finding the most common element
As instructed, move the code to a separate function:
#include <stdio.h>
#include <stdlib.h>
int *allocate_and_read_array(int size) {
int *A = (int*)calloc(size, sizeof(int));
if (A != NULL) {
for (int i = 0; i < size; i++) {
printf("Iveskite skaiciu \n");
if (scanf("%d", &A[i]) != 1) {
printf("Missing values\n");
break;
}
}
}
return A;
}
int main(void) {
int n, i, dazn;
int *A;
dazn = 0;
printf("Iveskite naturalu skaiciu: \n");// enter how many elements in an array we will have
scanf("%d", &n);
A = allocate_and_read_array(n);
... // sort the array
... // find the most common element
free(A);
return 0;
}
For reading some data that describes the coordinates of lines I wrote the following code:
int numLines;
scanf("%d", &numLines);
int xStart, yStart, xEnd, yEnd;
for (int i = 0; i < numLines; i++) {
scanf("%d %d %d %d", &xStart, &yStart, &xEnd, &yEnd);
}
But I think it would be more useful for the rest of the program if I stored the data into multidimensional array. How do I do that and which is better: storing the data into one 4-dimensional or two 2-dimensional arrays?
Your first scanf() is wrong, you need to tell scanf() what to scan for, that is doen by means of the specifiers.
Without specifiers, it will interpret the passed parameter as the format string, which will cause problems, so you need
if (scanf("%s", &numLines) == 1)
{
for (int i = 0 ; i < numLines ; ++i)
{
if (scanf("%d %d %d %d", &xStart, &yStart, &xEnd, &yEnd) == 4)
{
/* process the data here */
}
}
}
You don't really need an array of so many dimentions, you can use a struct for that, something like
struct Data
{
int xStart;
int xEnd;
int yStart;
int yEnd;
};
now, you can create an array of structs and many other things, and when using it you just need
struct Data data[SIZE];
int j;
j = 0;
if (scanf("%s", &numLines) == 1)
{
for (int i = 0 ; ((i < numLines) && (j < SIZE)) ; ++i)
{
if (scanf("%d %d %d %d",
&data[j].xStart,
&data[j].yStart,
&data[j].xEnd,
&data[j].yEnd) == 4)
{
j++;
}
}
}
I would even go further, and define
struct Item
{
int start;
int end;
};
struct Items
{
struct Item x;
struct Item y;
};
which would make the code more readable and understandable.
I would suggest to use structure.
For example
struct Line{
int startX;
int startY;
int endX;
int endY;
};
And then use array of this structure.
Rather than multidemensional array, I recommend to use 2 structs. This is more natural.
#include <stdio.h>
#define numlines 10
struct point {
int x;
int y;
};
struct line {
struct point a; /* start */
struct point b; /* end */
};
struct line lines[numlines];
int main() {
int i;
for ( i = 0; i < numlines; i++ ) {
scanf("%d %d", &lines[i].a.x, &lines[i].a.y);
scanf("%d %d", &lines[i].b.x, &lines[i].b.y);
}
}
void load(int *n, int *x, int **arr)
{
arr = (int**)malloc(sizeof(int*)*(*n));
for(int i = *n; i >= 0; i--)
{
scanf("%d", &arr[i]);
}
}
int main()
{
int n = 0, x = 0;
int *arr;
load(&n, &x, &arr);
printf("%d", arr[1]);
return EXIT_SUCCESS;
}
The program compiles properly, but it throws windows error during the printf() in main function. Displaying just "arr" gives random big numbers. What is wrong here?
arr = (int**)malloc(sizeof(int*)*(*n));
doesn't change anything in main, it only overwrites the copy of the pointer (address of arr in main) that load receives.
What the function should do is change arr in main, for that, you have to dereference the argument,
*arr = (int*)malloc(sizeof(int)*(*n)); // cast for C++ compiler left in
to change the value of arr in main. (The object that the argument arr of load points to, that is arr in main, needs to be changed, hence you need to modify *arr in load.)
The scans should then be
scanf("%d", &(*arr)[i]);
or (equivalent)
scanf("%d", *arr + i);
#include <stdio.h>
#include <stdlib.h>
void load(int *n, int *x, int **arr)
{
int i = 0;
*arr = (int*) malloc(*n * sizeof(int));
if(!*arr) {
perror("Can not allocate memory!");
return;
}
for(i = *n; i >= 0; i--)
{
scanf("%d", *arr + i);
}
return;
}
int main()
{
int n = 0, x = 0;
int *arr;
int i;
/* You probably need to initialize n */
n = 5;
load(&n, &x, &arr);
for(i = n; i >= 0; i--)
{
printf("%d - %d\n", i, arr[i]);
}
return EXIT_SUCCESS;
}
I am tryin to take input from the user and store it into an array and print it out: i have 2 functions:
/* Read a vector with n elements: allocate space, read elements,
return pointer */
double *read_vector(int n){
double *vec = malloc(n * sizeof(double));
int i;
for (i = 0; i < n; i++)
vec[i] = n;
return vec;
}
and the print function is:
void print_vector(int n, double *vec){
int i;
for (i = 0; i < n; i++) {
printf("%d\n", vec[i]);
}
}
the main function is:
#include <stdio.h>
#include <stdlib.h>
double *read_vector(int n);
void print_vector(int n, double *vec);
void free_vector(double *vec);
int main(){
int n;
double *vector;
/* Vector */
printf("Vector\n");
printf("Enter number of entries: ");
scanf("%d", &n);
printf("Enter %d reals: ", n);
vector = read_vector(n);
printf("Your Vector\n");
print_vector(n,vector);
free_vector(vector);
}
when i run this, it does not let me enter any numbers, it just skips it and prints out 0's. How do i fix this?
Try the code below. You're almost certainly either not compiling with warnings, or ignoring the warnings. All warnings mean something, and to a beginner they all matter. With gcc use the -Wall option, or even -pedantic.
As halfelf pointed out, you need a scanf in your read loop but it needs to be a pointer (&vec[i]). Always return something at the end of main. Also check the return value of malloc, it could fail and return a null pointer.
#include <stdio.h>
#include <stdlib.h>
double *read_vector(int n)
{
double *vec = malloc(n * sizeof(double));
int i;
for (i = 0; i < n; i++) {
printf("Enter number %i of %i: ", i + 1, n);
scanf("%lf", &vec[i]);
}
return vec;
}
void print_vector(int n, double *vec)
{
int i;
for (i = 0; i < n; i++) {
printf("%f\n", vec[i]);
}
}
void free_vector(double *vec)
{
free(vec);
}
int main()
{
int n;
double *vector;
printf("Vector\n");
printf("Enter number of entries: ");
scanf("%i", &n);
vector = read_vector(n);
printf("Your Vector\n");
print_vector(n, vector);
free_vector(vector);
return 0;
}
In the read_vector(int n) function's for loop:
for (i=0; i<n; i++)
vec[i] = n; // this should be scanf("%lf",vec+i) to read input from stdin
and notice your { and } there. If there's only one line in the loop, { and } is not necessary, OR you have to use a pair of them. The return clause must be out of the loop.
Btw, add return 0 at the end of your main function.
simple..you forgot to write scanf..!
double *read_vector(int n)
{
double *vec = malloc(n * sizeof(double));
int i;
for (i = 0; i < n; i++)
scanf("%d",&vec[i]);
return vec;
}