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);
}
}
Related
#include<stdio.h>
struct create
{
int a;
int b;
int c;
float total;
};
struct create Create[3];
float givename(struct create* storage[3]);
int main()
{
for(int j = 0; j<4; ++j)
{
printf("Input a[%d]:", j+1);
scanf("%d", &Create[j].a);
printf("Input b[%d]:", j+1);
scanf("%d", &Create[j].b);
printf("Input c[%d]:", j+1);
scanf("%d", &Create[j].c);
float sum = givename(&Create);
printf("%f", sum);
}
}
float givename(struct create* storage[3])
{
for(int i = 0; i<4; ++i)
{
storage[i]->total = storage[i]->a + storage[i]->b + storage[i]->c;
return storage[i]->total;
}
}
This is something I wrote and of course it doesn't work, it might seem stupid to elitist C programmers but a help would be appreciated. I wanted to take an input into array of structure and then use it inside a function that has been called by reference.
Please tell me can someone help me show what I am misunderstanding with the logic ?
The function
float givename(struct create* storage[3])
takes an array of pointers to struct create, you are sending the address of an array of struct create. If you want an array of pointers to struct create, do it like this:
struct create * array[3];
array[0] = & Create[0];
array[1] = & Create[1];
array[2] = & Create[2];
Plus, this function stops during the first iteration, because of the return.
Array's size is 3, you're looping 4 times.
Your main needs a return value;
If you wanted to pass the whole array to givename (an array of struct create, not pointers), you don't need to since Create is global;
For each iteration in the first loop (3 after fixing), you iterate the whole array, I doubt this is what you wanted to do.
The following version prompts to fill 3 struct create, computes the total for each (and stores it), and prints it.
Is this what you wanted to do ?
#include<stdio.h>
#include <stdlib.h>
struct create
{
int a;
int b;
int c;
float total;
};
struct create Create[3];
float givename(struct create * storage);
int main()
{
for(int j = 0; j < 3; ++j)
{
printf("Input a[%d]:", j+1);
scanf("%d", & Create[j].a);
printf("Input b[%d]:", j+1);
scanf("%d", & Create[j].b);
printf("Input c[%d]:", j+1);
scanf("%d", & Create[j].c);
float sum = givename(& Create[j]);
printf("%f\n", sum);
}
return EXIT_SUCCESS;
}
float givename(struct create * storage)
{
storage->total = storage->a + storage->b + storage->c;
return storage->total;
}
echo 1 2 3 4 5 6 7 8 9 | yourProgram
>> Input a[1]:Input b[1]:Input c[1]:6.000000
>> Input a[2]:Input b[2]:Input c[2]:15.000000
>> Input a[3]:Input b[3]:Input c[3]:24.000000
What you wanted to achieve is quite unclear, and the naming doesn't help, I recommend you to give better names:
struct create doesn't describe what is stored inside
Consider compiling with -Wall -Wextra -Werror.
Your givename() (seems like a bad name) currently only processes one struct as it returns inside the loop. And the way you are calling it after each input of 3 integers it would only process a struct (the first struct each time), and not the array of structs. To process the array of structs you could call it after you got all the input - outside the loop taking input. This shows a version processing during the loop for each struct and then a version processing after the loop with all input.
#include<stdio.h>
struct create
{
int a;
int b;
int c;
float total;
};
struct create Create[3];
float givename(struct create *storage);
float calculate_totals(struct create storage[3]);
float get_grand_total(struct create [3]);
int main()
{
for(int j = 0; j<3; ++j)
{
printf("Input a[%d]:", j+1);
scanf("%d", &Create[j].a);
printf("Input b[%d]:", j+1);
scanf("%d", &Create[j].b);
printf("Input c[%d]:", j+1);
scanf("%d", &Create[j].c);
float sum = givename(&Create[j]);
printf("%f\n", sum);
}
get_grand_total(Create);
/* calculate all totals after input */
for(int j = 0; j<3; ++j)
{
printf("Input a[%d]:", j+1);
scanf("%d", &Create[j].a);
printf("Input b[%d]:", j+1);
scanf("%d", &Create[j].b);
printf("Input c[%d]:", j+1);
scanf("%d", &Create[j].c);
}
float grand_total = calculate_totals(Create);
printf("grand total = %f\n",grand_total);
}
float givename(struct create *storage)
{
storage->total = storage->a + storage->b + storage->c;
return storage->total;
}
float get_grand_total(struct create storage[3])
{
float grand_total = 0;
for (int i = 0; i < 3; i++)
{
grand_total += storage[i].total;
}
printf("grand total sum=%f\n",grand_total);
return grand_total;
}
float calculate_totals(struct create storage[3])
{
float grand_total = 0;
for(int j = 0; j<3; ++j)
{
storage[j].total = storage[j].a + storage[j].b + storage[j].c;
printf("total for struct %d=%f\n",j+1,storage[j].total);
grand_total += storage[j].total;
}
return grand_total;
}
I want to copy my array over to a pointer, so I can sort the array without changing the original. I'm not getting any errors, and am at a dead end. I've tried printing the pointer's contents, but it's always junk data. If anyone could help me it'd be much appreciated.
#include <stdio.h>
void bubbleSort(char *array[], int arrIndex);
void displaySort (char *array[], int arrIndex);
int main (void)
{
int index;
int count = 0;
printf("Enter number of people (0 - 50): ");
scanf("%d", &index);
index -= 1;
char userLastFirst[25][index];
int userAge[index];
//defining pointer
char *namePtr[25][index];
//do while loop, loops while count is less than or equal to the index
do{
printf("Enter name %d (last, first): ", count);
scanf(" %[^\n]s", userLastFirst[count]);
printf("Enter age %d: ", count);
scanf("%d", &userAge[count]);
// printf("\n\n%s %d\n\n", userLastFirst[count], userAge[count]);
count++;
} while (count <= index);
//assigning values to pointer
for(int i = 0; i < index; i++){
namePtr[25][i] = &userLastFirst[25][i];
}
//does not print values of pointer
for(int i = 0; i < index; i++){
printf("value of ptr[%d] = %s\n", i, namePtr[i]);
}
bubbleSort(*namePtr, index);
displaySort(*namePtr, index);
return 0;
}
void bubbleSort(char *array[], int arrIndex)
{
for (unsigned int pass = 0; pass < arrIndex - 1; ++pass) {
for (int i = 0; i < arrIndex - 1; ++i) {
if (array[i] < array[i + 1]) {
int temp = *array[i];
*array[i] = *array[i + 1];
*array[i + 1] = temp;
}
}
}
}
void displaySort(char *array[], int arrIndex)
{
for(int i = 0; i < arrIndex; i++){
printf("%s",*array[i]);
}
}
Sorry it's a lot, but I've looked everywhere, and am not exactly sure what the problem is. I suspect it's how I pass pointers thru the functions, or how I'm using * and & but am not totally sure what I'm doing wrong. The for loop below the one that assigns the array values to the pointer is for testing. It's supposed to print out the values I had given it in the previous for loop, but it doesn't. It just prints junk data.
There are couple of issues here, and since I don't know what exactly you want your final code to look like, I am going to give a few examples of what is wrong and how you could possibly fix that.
char userLastFirst[25][index];
This should be
char userLastFirst[index][25];
You don't want 25 people with names up to index characters in them, but rather index people with names up to 25 characters int them.
char *namePtr[25][index];
should be
char namePtr[index][25];
Same as before + you don't need the * here. Since you decided to go with vla let's stick with it. You would use * and more specifically char ** if you went with malloc/calloc.
namePtr[25][i] = &userLastFirst[25][i];
rather than doing this awkward copying, try:
strcpy(namePtr[i], userLastFirst[i]);
it copies the entire string for you, rather than just a single character. You will need to #include the <string.h> library for that.
void bubbleSort(char *array[], int arrIndex)
The first bubble sort argument should be:
char array[][25] // the same in displaySort
if you want to do it without the hassle of malloc/calloc.
And also don't go with int as your temp type. Rather do char temp[25] and copy them around with strcpy.
And don't compare strings with <, it doesn't work in C. Use strcmp for that.
And that's it for doing it without malloc/calloc, here's an example code:
#include <stdio.h>
#include <string.h>
void bubbleSort(char array[][25], int size);
void displaySort(char array[][25], int size);
int main (void)
{
int num_of_people;
printf("Enter number of people (0 - 50): ");
scanf("%d", &num_of_people);
char original_array[num_of_people][25];
char copied_array[num_of_people][25];
for (int i = 0; i < num_of_people; i++) {
printf("Enter name %d (last, first): ", i);
scanf(" %[^\n]s", original_array[i]);
}
for(int i = 0; i < num_of_people; i++){
strcpy(copied_array[i], original_array[i]);
}
bubbleSort(copied_array, num_of_people);
displaySort(copied_array, num_of_people);
return 0;
}
void bubbleSort(char array[][25], int size)
{
for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - 1 - i; ++j) {
if (strcmp(array[j], array[j + 1]) > 0) {
char temp[25];
strcpy(temp, array[j]);
strcpy(array[j], array[j + 1]);
strcpy(array[j + 1], temp);
}
}
}
}
void displaySort(char array[][25], int size)
{
for(int i = 0; i < size; i++){
printf("%s\n",array[i]);
}
}
and the program work like this:
Enter number of people (0 - 50): 4
Enter name 0 (last, first): Kowalski, Jan
Enter name 1 (last, first): Kowalska, Anna
Enter name 2 (last, first): Nowak, Miłosz
Enter name 3 (last, first): Amper, Ohm
Amper, Ohm
Kowalska, Anna
Kowalski, Jan
Nowak, Miłosz
I hope this is something you wanted to achieve.
This program is to find all prime numbers and store them in an array. I don't want to take unnecessary memory by defining a fixed array before getting the exact number of prime numbers in a specific range. I also want to make this code to be able to run in C89 so, variable sized array is out of question here.
This is my code with 2 methods I found for this.
#include<stdio.h>
#include<stdlib.h>
struct prime{
int *arr;
int count;
};
int prmchk();
struct prime method1();
struct prime method2();
int main()
{
int min,max;
int i,j;
struct prime p[2];
printf("Enter limits of range..\n");
printf("min: ");
scanf("%d",&min);
printf("max: ");
scanf("%d",&max);
p[0] = method1(min,max);
p[1] = method2(min,max);
for(i = 0; i < 2; i++) //to test the results by printing them
{ //has nothing to do with the problem
printf("result of method %d: ",i+1);
for(j = 0; j < p[i].count; j++)
printf("%d ",p[i].arr[j]);
printf("\n");
}
}
struct prime method1(int min, int max) //function starts
{
struct prime pf;
int i;
int temparr[10000]; //No 2 consecutive no.s can be prime numbers simulteneously
int pcount = 0;
for(i = min; i <= max; i++)
{
if(prmchk(i) == 1)
temparr[pcount++] = i; //
}
pf.arr = (int*) malloc(pcount * sizeof(int));
for(i = 0; i < pcount; i++)
{
pf.arr[i] = temparr[i];
}
pf.count = pcount;
return pf;
}
struct prime method2(int min, int max)
{
struct prime pf;
pf.arr = (int*) malloc(0);
int i;
int pcount = 0;
for(i = min; i < max; i++)
{
if(prmchk(i) == 1)
{
pf.arr = (int*) realloc(pf.arr,++pcount*sizeof(int));
pf.arr[pcount-1] = i;
}
}
pf.count = pcount;
return pf;
}
int prmchk(int num)
{
int i;
if(num == 1)
return 0;
if(num == 2)
return 1;
for(i = 2; i < num; i++)
{
if(num%i == 0)
return 0;
}
return 1;
}
My questions are
Since I'm new to competitive programming I don't know which method will consume less memory and which one will consume less time. I want to know which method is better than the other.
If possible feel free to add a new method if you can think of any.
Can we use malloc(0) as used here
How the readability of this particular code could be improved more. I'm read some articles about it. But unable to get any proper understanding.
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;
}
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);
}
}
}