C writing into pointer array? - c

I have a homework that wants us to make an array of (x,y) coordinates that the user enters but we don't know how many will be entered, it will end when (0,0) is entered, the last one will not be added to the array and then we sort them and print them.So I used pointers to make array but I can't insert all the elements that I want to insert it only recognizes the last entered one. When I try to print them it will print only the last one I entered correctly the others mostly comes (0,0) or some random numbers.
int main()
{
int x,y,*xp,*yp;
int a = 0,s,m=12;
etiket:
scanf("%d %d",&x,&y);
printf("\n");
while (x != 0 || y != 0)
{
a=a+1;
xp = (int*) malloc(sizeof(int)*m);
yp = (int*) malloc(sizeof(int)*m);
//printf("%d %d\n",x,y);
if( a%10==0)
{
xp = (int*) realloc(xp,sizeof(int)*m+10);
yp = (int*) realloc(yp,sizeof(int)*m+10);
}
xp[a]=x;
yp[a]=y;
printf("%d %d\n",*(xp+a),*(yp+a));
goto etiket;
//SortPoints((xp+a),(yp+a),a);
}
//printf("siralama:\n");
//for(s=0; s<=a; s++)
//{
// printf("%d %d\n",*(xp+s),*(yp+s));
//}
}
So this is my work-in-progress code.
I don't even know if it's possible I would appreciate any help.
Thank you in advance.

As you have been restricted to use C it's lot easier to use structure for dynamically allocated memory for arrays. Here's the code:-
#include<stdio.h>
#include<malloc.h>
#define SIZE 20 // SIZE OF YOUR ARRAY FOR DYNAMIC MEMORY ALLOCATION
typedef struct {
int x;
int y; // That's the point with x and y coordinate
} point ; // Similar as int n, float a .... now point is a
// type which holds the value of x and y
int main(void){
point *p; // pointer decleration for point type
p= (point *)malloc(SIZE* sizeof(point)); // Memory Allocation
int i=0;
do{
p++; // increment of pointer
i++;
printf("Enter values for point %d: (x,y)= ",i);
scanf("%d", &p->x); // input x and y
scanf("%d", &p->y);
}while((p->x) !=0 || (p->y) !=0 ); // loop breaks when inputs 0,0
p--; // decrement pointer as 0,0 value will have no use
i--;
printf("\n\n\n");
for(;i>0;i--,p--)
printf("Point %d: (x,y)=(%d,%d)\n", i,p->x, p->y);
// displaying point values user given
printf("\n\n\n");
return 0;
}
Here p holds the hole array of points. Now, for sorting you just have to pass p in a function as a agrument like that and write the regular sorting algorithm inside the body.
point* SortingArray(point *p)
This function will return another arrays of points which is sorted. Hope you could do this yourself.
Furthermore, probably very soon You will learn C++ where this kind of works are so easy using class. In fact, in C++ there have a lot of features in the STL(Standard Template Library) like lists,vectors... for these kind of works which support dynamic memory allocation very soundly.
Let me know if You find any problem to grasp the concept. Thanks.

Related

Need help solving a problem with an array

Task: Calculate the 25 values of the function y = ax'2 + bx + c on the interval [e, f], save them in the array Y and find the minimum and maximum values in this array.
#include <stdio.h>
#include <math.h>
int main()
{
float Y[25];
int i;
int x=3,a,b,c;
double y = a*pow(x,2)+b*x+c;
printf("a = ", b);
scanf("%d", &a);
printf("b = ", a);
scanf("%d", &b);
printf("c = ", c);
scanf("%d", &c);
for(i=0;i<25;i++)
{
printf("%f",y); //output results, not needed
x++;
}
system("pause");
}
Problems:
Cant understand how can I use "interval [e,f]" here
Cant understand how to save values to array using C libraries
Cant understand how to write/make a cycle, which will find the
minimum and maximum values
Finally, dont know what exactly i need to do to solve task
You must first ask the user for the values of a, b, c or initialize those variables, and ask for the interval values of e, f, or initialize those variables.
Now you must calculate double interval= (f - e)/25.0 so you have the interval.
Then you must have a loop for (int i=0, double x=e; i<25; i++, x += interval) and calculate each value of the function. You can choose to store the result in an array (declare one at the top) or print them directly.
Problems:
Cant understand how can I use "interval [e,f]" here
(f-e) / 25(interval steps)
Cant understand how to save values to array using C libraries
You need to use some form of loop to traverse the array and save the result of your calculation at every interval step. Something like this:
for(int i = 0; i < SIZE; i++)
// SIZE in this case 25, so you traverse from 0-24 since arrays start 0
Cant understand how to write/make a cycle, which will find the minimum and maximum values
For both cases:
traverse the array with some form of loop and check every item e.g. (again) something like this: for(int i = 0; i < SIZE; i++)
For min:
Initialize a double value(key) with the first element of your array
Loop through your array searching for elements smaller than your initial key value.
if your array at position i is smaller than key, save key = array[i];
For max:
Initialize a double value(key) with 0;
Loop through your array searching for elements bigger than your initial key value.
if your array at position i is bigger than key, save key = array[i];
Finally, dont know what exactly i need to do to solve task
Initialize your variables(yourself or through user input)
Create a function that calculates a*x^2 + b*x + c n times for every step of your interval.
Create a function for min & max that loops through your array and returns the smallest/biggest value.
Thats pretty much it. I will refrain from posting code(for now), since this looks like an assignment to me and I am confident that you can write the code with the information #Paul Ogilvie & I have provided yourself. Good Luck
#include<stdio.h>
#include<math.h>
int main()
{
double y[25];
double x,a,b,c,e,f;
int i,j=0;
printf("Enter a:",&a);
scanf("%lf",&a);
printf("Enter b:",&b);
scanf("%lf",&b);
printf("Enter c:",&c);
scanf("%lf",&c);
printf("Starting Range:",&e);
scanf("%lf",&e);
printf("Ending Range:",&f);
scanf("%lf",&f);
for(i=e;i<=f;i++)
{
y[j++]=(a*pow(i,2))+(b*i)+c;
}
printf("\nThe Maximum element in the given interval is %lf",y[j-1]);
printf("\nThe Minimum element in the given interval is %lf",y[0]);
}
Good LUCK!

Bubblesort a 2-D Array - C

I am trying to use Bubblesort for a 2-D array, using a custom sized 2D Array with the max limit of [100][2]. I am a beginner at this, so i am not great at formatting code properly so shedding light would be great.
my input
How many items of data do you wish to enter? 4
Please enter in the X coordinate: 4
Please enter in the Y coordinate: 4
Please enter in the X coordinate: 3
Please enter in the Y coordinate: 3
Please enter in the X coordinate: 2
Please enter in the Y coordinate: 2
Please enter in the X coordinate: 1
Please enter in the Y coordinate: 1
So that prints out how many numbers you wish to enter from a custom array input.
output(Meant to compare each array and switch to ascending order).
Printing in Ascending Order:
[4][3]
[3][3]
[3][3]
It prints 3 arrays not 4, and doesn't print out any of the numbers i entered.
so
But could anybody shed some light on this? It is specifically the Bubblesort function.
int main()
{
int arrayHeight, array[100][2];
printf ("***** Bubble Sort ***** \n");
InputArray(array, arrayHeight);
}
int InputArray(int array[100][2], int arrayHeight, int swap)
{
int i, xCoord, yCoord;
printf("\n How many items of data do you wish to enter? ");
scanf("%d",&arrayHeight);
for(i=0; i<arrayHeight; i++)
{
printf("Please enter in the X coordinate: ");
scanf("%d", &xCoord);
printf("Please enter in the Y coordinate: ");
scanf("%d", &yCoord);
array[i][0] = xCoord;/* Name of XCoordinate and position within Array*/
array[i][1] = yCoord;/*Name of YCoordinate and position within Array*/
}
DisplayArray(array, arrayHeight);
}
int DisplayArray(int array[100][2], int arrayHeight, int swap)
{
int i, j;
printf("\n The 2-D Array contains : \n");
for(i=0; i<arrayHeight; i++)
{
printf("[%d][%d]\n\r", array[i][1], array[i][0]);
}
BubbleSort(array, arrayHeight);
}
int BubbleSort(int array[100][2], int arrayHeight)
{
int swap, i, j, k;
printf("\n Printing in Asending Order: ");
for (i = 0; i <arrayHeight-1; i++)
{
if (array[i][0] > array[i][1 + 1])
{
array[1][i] = array[1][0+1];
swap = array[1][i];
array[i][1 + 1];
printf("\n [%d][%d] ", array[i][0], array[1][i]);
}
}
}
There's a fair amount of things going on here.
Your Question
Your program is printing out strange parts of your array because of the way you're calling printf from within BubbleSort. While BubbleSort is still running, your array isn't fully sorted. However, the function calls printf after each attempt at swapping array elements. If you'd like to print your whole array after sorting, it would be better to allow the sorting function to run to completion, then print out the array in full afterwards.
Other Stuff
There are a lot of points tangential to your question that I'd like to raise to help you out from a style and correctness perspective. Also, some of these are rather interesting.
#include Statements
When compiling this, you should be getting several warnings. If you're using gcc, one of those warnings will be something like:
main.c: warning: incompatible implicit declaration of built-in function ‘printf’
printf ("***** Bubble Sort ***** \n");
This states that the function printf has been implicitly declared when it was called. That is, the compiler inferred that a function printf exists because you called a function named printf. The problem is that it knows nothing about this function other than that it probably exists. This means the complier doesn't know what the function is supposed to return or what arguments it is supposed to accept, so it cannot help you if you use it inappropriately. To avoid this problem, you should include the standard C Input/Output headers in your program like so:
#include <stdio.h>
The stdio.h header file includes many functions besides just printf. Check out man 3 stdio for more information on it.
Define or Declare Functions Before Calling Them
One of the less-modern aspects of C is that it runs through your program from top to bottom. Many modern languages allow you to put your function declarations anywhere in your code and then it works things out on its own. Javascript's variable and function hoisting is an example of this.
Because C does not do this, you should define or declare your functions before you call them. If you call them without a declaration or definiton, the compiler will fall back to the default function signature extern int <function_name>(); That is, if you do not supply a declaration or definition for your function, C will assume that function is defined elsewhere, returns an int, and takes an unspecified number of arguments.
In this program, the function DisplayArray is defined with three arguments:
int DisplayArray(int array[100][2], int arrayHeight, int swap);
However, it is called with only two arguments:
DisplayArray(array, arrayHeight);
This can only happen because when the function is first called, it hasn't yet been defined, so the compiler, without knowing any better, assumes the call is made correctly.
When this is corrected (the definition is put above the first call), the compiler will throw an error stating that the function DisplayArray takes three arguments, but it was called with only two.
Calling Functions / Program Structure
The most oft-cited benefit of creating functions in your code is modularity. This is the idea that you can freely re-use code at different points in your program while knowing what that code is going to do. This program sacrifices this benefit by creating a sort of function-chain, where each function calls the other. InputArray calls DisplayArray, and DisplayArray calls BubbleSort.
This means any time you'd like to print an array, you must be okay with it being bubble-sorted as well. This is considered bad practice because it reduces the amount of times calling the function is useful. A more useful function would be one that displays the array but does not call BubbleSort or modify the array in any way.
Bubble Sorting
Your question doesn't specify exactly how you'd like to bubble sort, but the function here doesn't implement the BubbleSort algorithm. Generally, it's best to make sure you understand the algorithm before applying it to strange cases like 2-D arrays. I've included a working example below, which I hope helps get you on the right track.
Briefly, note that there two loops in a bubble sort:
* an inner loop that runs through the array and swaps neighboring elements
* an outer loop that runs the inner loop until the entire array is sorted
Minor Things
C programs generally prefer snake_case to CamelCase, but more generally, you should do what works best for you. If you're on a team, use a style consistent with that team.
All of the functions in this program return int, yet none of them actually use a return statement or return a useful value. If you have a function does not return a useful value, return void instead (e.g. - void DisplayArray(int array[100][2], int arrayHeight)).
Your displayArray function swaps the position of x and y. printf will display parameters in the order you specify unless directed otherwise. Check out man 3 printf for more on that function.
Working Example
#include <stdio.h>
void DisplayArray(int array[100][2], int arrayHeight)
{
int i, j;
printf("\n The 2-D Array contains : \n");
for(i=0; i<arrayHeight; i++)
{
printf("[%d][%d]\n\r", array[i][0], array[i][1]);
}
}
void BubbleSort(int array[100][2], int arrayHeight)
{
int i;
int swap[2];
int swapHappened = 1;
// the outer loop runs until no swaps need to be made
// no swapping implies the array is fully sorted
while (swapHappened) {
swapHappened = 0;
// the inner loop swaps neighboring elements
// this is what 'bubbles' elements to the ends of the array
for (i = 0; i < arrayHeight-1; i++)
{
if ((array[i][0] > array[i+1][0]) ||
(array[i][0] == array[i+1][0]) && (array[i][1] > array[i+1][1]))
{
// if a swap happens, the array isn't sorted yet, set this variable
// so the `while` loop continues sorting
swapHappened = 1;
// save the higher-value row to a swap variable
swap[0] = array[i][0];
swap[1] = array[i][1];
// push the lower-valued row down one row
array[i][0] = array[i+1][0];
array[i][1] = array[i+1][1];
// put the saved, higher-value row where the lower-valued one was
array[i+1][0] = swap[0];
array[i+1][1] = swap[1];
}
}
DisplayArray(array, arrayHeight);
}
}
int main()
{
int arrayHeight, array[100][2];
printf ("***** Bubble Sort ***** \n");
int i, xCoord, yCoord;
printf("\n How many items of data do you wish to enter? ");
scanf("%d",&arrayHeight);
for(i=0; i<arrayHeight; i++)
{
printf("Please enter in the X coordinate: ");
scanf("%d", &xCoord);
printf("Please enter in the Y coordinate: ");
scanf("%d", &yCoord);
array[i][0] = xCoord;/* Name of XCoordinate and position within Array*/
array[i][1] = yCoord;/*Name of YCoordinate and position within Array*/
}
DisplayArray(array, arrayHeight);
BubbleSort(array, arrayHeight);
DisplayArray(array, arrayHeight);
return 0;
}
I don't get what you are trying to do with your BubbleSort function.
But just to get a few things right :
if (array[i][0] > array[i][1 + 1])
this shouldn't work, your array was initialized as "int array [100][2]". Conventionally the highest number that should be in the second square bracket is 1. (1+1 =2, by the way)
array[1][i] = array[1][0+1];
swap = array[1][i];
C executes code in a sequential basis, so the array[1][i] is overwritten with array[1][0+1] even before the original value is saved in the 'swap' variable.
array[i][1 + 1];
This line of code does not seem do anything.
If you could tell whether you are trying to sort 'by element' or by 'line' (ie by each array in the 2D array), maybe we could help you approach the problem correctly.

Solve segmentation fault error in C

I am trying to store the sum 1/k^2 in an array using this code:
int main()
{
int i,n, e;
double terms[n];
double x, y;
printf(" Introduce n\n");
scanf("%d", &n);
y=1;
i=0;
while(e<n)
{
x=1/((y)*(y));
printf("x is %.16lf\n",x);
terms[i]=x;
printf("terms is %.16lf\n", terms[i]);
y++;
i++;
e++;
}
}
And I get the "segmentation fault" error. Why is this happening? How can I avoid it?
I am programming in C
n is garbage in double terms[n]; that causes undefined behaviour. Enable compiler warning by compiling with gcc -Wall and observe. Never ignore warnings.
Initialize n before declaring terms[n] OR
printf(" Introduce n\n");
scanf("%d", &n);
double terms[n];
Also e is uninitialized, initialize it.
e = 0 ;
while (e < n){
/* code */
}
When declaring an array with n elements (double terms[n];), the allocation of said array is done in the compilation stage. Because you left your n variable un-initialized, it has indeterminate value (random from the user perspective), so you don't know what is the size of said array.
Scanning an int into n later, does not help at all as it is done in the run-time (and also, it is done AFTER the array declaration. It could have worked if you have used malloc for the allocation AFTER the scanf).
Anyway, you currently have an array with "random" size, and accessing it is Undefined Behavior -> segfault
The crash comes from undefined size of the terms[n] array. You are crossing array memory boundaries.
A few variables are not initialized:
double terms[n]; // n is not initialized
while (e<n){ // e is not initialized
You have many choices to properly build terms array (marked in the code as well):
1) Decide upfront on the specific size of the array. (This is not flexible approach!)
2) Allocate array dynamically when you read n.
3) Declare terms[n] after reading n.
Test program:
#include <stdio.h>
#include <stdlib.h>
int main(){
int i;
int n;
int e = 0;
// 1. One of the 3 choices - thus is a rigid one
// double terms[TERMS_SIZE]; // make TERMS_SIZE big enough, read n has to be less than TERMS_SIZE
double x, y;
printf(" Introduce n\n");
scanf("%d", &n);
// 2.
// double *terms = malloc ( n* sizeof sizeof(double));
// or
// 3.
double terms[n];
y=1;
i=0;
while (e<n){
x=1/((y)*(y));
printf("x is %.16lf\n",x);
terms[i]=x;
printf("terms is %.16lf\n",terms[i]);
y++;
i++;
e++;
}
// If 2. used free the memory
// free(terms);
return 0;
}
Output:
4
Introduce n
x is 1.0000000000000000
terms is 1.0000000000000000
x is 0.2500000000000000
terms is 0.2500000000000000
x is 0.1111111111111111
terms is 0.1111111111111111
x is 0.0625000000000000
terms is 0.0625000000000000

Why does c print a different array the second time it's printed?

My cousin has a school project and we can't figure out why is the array different the second time it's printed when there is no values changing in between?
Basically you enter a number which states how many rows/columns will the matrix have, and during first loop he assigns a number to every position and prints out the random number. However, the second time we go through the matrix the numbers are different and it seems that they are copied through the matrix from bottom left corner to top right corner for some reason. It seems strange to us because we never assign a different value to a position in the array after defining it for the first time.
int i,j,n,matrica[i][j],suma=0;
srand(time(NULL));
printf("\nunesi prirodan broj N[3,20] = \n");
scanf("%d",&n);
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
matrica[i][j]=rand()%100;
printf("%d, %d = %4d ",i, j, matrica[i][j]);
if(j==n-1) {
printf("\n");
}
}
}
printf("\n");
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
printf("%d, %d = %4d ", i, j, matrica[i][j]);
if(j==n-1) {
printf("\n");
}
}
}
And here is the result of this (the code I pasted here has 2 prints, and in the image there is 3 but every time you go through the matrix after the first time it's going to be the same):
We need to use malloc to allocate the dynamic amount of memory.
After
scanf("%d",&n) // PS You should check the return value - read the manual page
Put
matrica = malloc(sizeof(int) * n * n);
And declare it as
int *matrica;
Then replace
matrica[i][j]
with
matrica[i * n + j]
And after you have finished with matrica - use free i.e.
free(matrica);
int i,j,n,matrica[i][j]
At this point I must ask, what value do you think i and j will have? Right there you're invoking undefined behaviour by referring to variables declared with automatic storage duration which you've not initialised. Anything after this point is... undefined behaviour.
Having said that, I noticed a few other parts that look strange. Which book are you reading? The reason I ask is that the people I know to be reading reputable textbooks don't have these problems, thus your textbook (or resource, whatever) mustn't be working for you...
I can't read the commentary inside of the string literals, which is a shame, since that's usually quite valuable contextual information to have in a question. Nonetheless, moving on, if this were me, I'd probably declare a pointer to an array n of int, after asking for n, like so:
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t n;
printf("Enter n, please: ");
fflush(stdout);
if (scanf("%zu", &n) != 1 || n == 0 || SIZE_MAX / n < n) {
puts("Invalid input or arithmetic overflow...");
return -1;
}
int (*array)[n] = malloc(n * sizeof *array);
if (!array) {
puts("Allocation error...");
return -1;
}
/* now you can use array[0..(n-1)][0..(n-1)] as you might expect */
free(array);
}
This should work for quite high numbers, much higher than int array[n][n]; would in its place... and it gives you that option to tell the user it was an "Allocation error...", rather than just SIGSEGV, SIGILL, SIGBUS or something...
... but nothing would be more optimal than just saving the seed you use to generate the random numbers, and the user input; that's only two integers, no need for dynamic allocation. There's no point storing what rand generates, amd you realise this, right? rand can generate that output purely using register storage, the fastest memory commonly available in our processors. You won't beat it with arrays, not meaningfully, and not... just not.

How can i add numbers to an array using scan f

I want to add numbers to an array using scanf
What did i do wrong? it says expected an expression on the first bracket { in front of i inside the scanf...
void addScores(int a[],int *counter){
int i=0;
printf("please enter your score..");
scanf_s("%i", a[*c] = {i});
}//end add scores
I suggest:
void addScores(int *a, int count){
int i;
for(i = 0; i < count; i++) {
printf("please enter your score..");
scanf("%d", a+i);
}
}
Usage:
int main() {
int scores[6];
addScores(scores, 6);
}
a+i is not friendly to newcomer.
I suggest
scanf("%d", &a[i]);
Your code suggests that you expect that your array will be dynamically resized; but that's not what happens in C. You have to create an array of the right size upfront. Assuming that you allocated enough memory in your array for all the scores you might want to collect, the following would work:
#include <stdio.h>
int addScores(int *a, int *count) {
return scanf("%d", &a[(*count)++]);
}
int main(void) {
int scores[100];
int sCount = 0;
int sumScore = 0;
printf("enter scores followed by <return>. To finish, type Q\n");
while(addScores(scores, &sCount)>0 && sCount < 100);
printf("total number of scores entered: %d\n", --sCount);
while(sCount >= 0) sumScore += scores[sCount--];
printf("The total score is %d\n", sumScore);
}
A few things to note:
The function addScores doesn't keep track of the total count: that variable is kept in the main program
A simple mechanism for end-of-input: if a letter is entered, scanf will not find a number and return a value of 0
Simple prompts to tell the user what to do are always an essential part of any program - even a simple five-liner.
There are more compact ways of writing certain expressions in the above - but in my experience, clarity ALWAYS trumps cleverness - and the compiler will typically optimize out any apparent redundancy. Thus - don't be afraid of extra parentheses to make sure you will get what you intended.
If you do need to dynamically increase the size of your array, look at realloc. It can be used in conjunction with malloc to create arrays of variable size. But it won't work if your initial array is declared as in the above code snippet.
Testing for a return value (of addScores, and thus effectively of scanf) >0 rather than !=0 catches the case where someone types ctrl-D ("EOF") to terminate input. Thanks #chux for the suggestion!

Resources