Addition Of Pointers in C [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Please go through the following loops:
I am especially confused about the first loop,
1st loop:
for(i = 0; i < n; i++)
{
scanf("%d", ptr + i);
}
for(i = 0; i < n; i++)
{
sum = sum + (*(ptr + i));
}
2nd loop:
int *x ;
for(i = 0; i < n; i++)
{
x = ptr + sizeof(i);
scanf("%d",x );
}
for(i = 0; i < n; i++)
{
x = ptr + sizeof(i) ;
sum = sum + (*x);
}
Why do entering the elements in the array by using malloc
using the above loops give the same result ?
Why are the first and second loop giving equal or right result ?
why are (ptr + i) and ptr + sizeof(i) working in same waY?
Entire program is
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define NULL 0
int main()
{
int *ptr;
int i, n, sum = 0 ;
float avg ;
printf("Enter the number of elements you want to store in the array.");
scanf("%d", &n);
ptr = (int *) malloc( n * sizeof(int)) ; /*Dynamic Memory allocation*/
if(ptr == NULL)
{
printf("The required amount of memory is not available. ");
getch();
exit(0);
}
else
{
printf("Enter the elements\n");
for(i = 0; i < n; i++)
{
scanf("%d", ptr + i);
}
for(i = 0; i < n; i++)
{
sum = sum + (*(ptr + i));
}
printf("\nThe sum of %d elements entered is = %d",n , sum );
avg = sum / n ;
printf("\nThe average of %d number of the array is %f", n, avg);
}
printf("\n");
getch();
}

why are (ptr + i) and ptr + sizeof(i) working in same waY?
They are not. In the first example, you read n values into an array (storing them in succesive elements), and then add those n values. In the second example, you read n values and store them all in the same element of the array (overwriting the previous element), so you end up with an array that is mostly uninitialized, but has one element set to the last value read. You then add that element to itself n times.
So you might end up with the same sum in both cases (for example, if your numbers are 1,3,2), or you might not.

Related

How to get the maximum even product from a given array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 days ago.
Improve this question
Given an array A of n integers, each of the n integers has a value Ai
Your task is to choose two elements at two different indexes that have the maximum even product. Suppose you have A of 3 integers A=[8,2,5] the maximum even product should be A1×A3=8×5=40 Note that you cannot choose A1,A1 since they have the same index. If there's no such pair with even product. Print −1
Input
The first line of input contains an integer n (2≤n≤10^5) the length of the array.
The second line of input contains n space separated positive integers A1,A2,…An (1≤Ai≤10^9)
Output
Print the maximum even product in the array, if there's no such pair with even product, print −1 instead.
My code is here on ideone.com and here as text:
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
long long int n, a[100000], max = -1;
scanf("%lld", &n);
for(int i = 0; i < n; i++)
scanf("%lld", &a[i]);
for(int i = 0; i < n-1; i++)
{
for(int j = i+1; j < n; j++)
{
if(a[i] * a[j] % 2 == 0)
{
if(a[i] * a[j] > max)
max = a[i] * a[j];
}
}
}
printf("%lld", max);
}
this code give me Time limit exceeded on test 12 Even after I increased the size of the array
The previous answer doesn't account for the case: if all the numbers are even
Here is my take on the problem
Assuming only positive inputs
Idea:
out of the two, we need at least one even number for the product to be even
Algorithm
traverse the array, and find the largest even number, and store it in first_val
for second_val:
it just has to be the largest number in the array that is not at same index as of first_val
so, for every value, check if you can update second_val, then update it
finally, return their product if you found both of the values, else return -1
Here is my code in C to help you out:
#include <stdio.h>
#define clearScreen() printf("\033[H\033[J"); // you can ignore this. I was just testing something related to the terminal
int maxEvenProduct(int size, int arr[]){
int first_val = -1;
int second_val = -1;
for(int i = 0; i < size; i++){
printf("first_val: %d\nsecond_val: %d\n\n", first_val, second_val);
if (first_val < arr[i] && (arr[i] % 2) == 0){
if(first_val != -1 && second_val < first_val){
second_val = first_val; // first_val != -1 : to make sure that at least 1 even number is found
}
first_val = arr[i];
continue; // to make sure that first and second val are not the same indexed values
}
if(arr[i] > second_val){
second_val = arr[i];
}
}
printf("Final values:\nfirst_val: %d\nsecond_val: %d\n", first_val, second_val);
return first_val == -1 || second_val == -1? -1: first_val*second_val;
}
int main(void){
int size;
int arr[100];
clearScreen();
printf("Size: ");
scanf("%d", &size);
for(int i = 0; i < size; i++){
clearScreen();
printf("Size: %d\n", size);
printf("Enter element %d: ", i+1);
scanf("%d", &arr[i]);
}
clearScreen();
printf("Array: ");
for(int i = 0; i < size; i++) printf("%d ", arr[i]);
printf("\n");
printf("Max Even Product: %d\n", maxEvenProduct(size, arr));
return 0;
}

Dynamic Memory in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I can't understand what doing the row
*(m[i] + sizes[i] - 1) = n;
#include <stdio.h>
#include <stdlib.h>
#define MAXSTR 100
int main()
{
int i, j, k, n;
char str[MAXSTR];
printf("Enter amount of rows: ");
fgets(str, MAXSTR, stdin);
k = atoi(str);
int* sizes = (int * ) calloc(k, sizeof(int));
int* sum = (int * ) calloc(k, sizeof(int));
int** m = (int ** ) calloc(k, sizeof(int * ));
printf("Enter matrix:\n");
for (i = 0; i < k; i++)
{
fgets(str, MAXSTR, stdin);
char* sym = str;
while (1)
{
m[i] = (int * ) realloc(m[i], (++sizes[i]) * sizeof(int));
n = strtol(sym, & sym, 10);
sum[i] += n;
if (n)
{
*(m[i] + sizes[i] - 1) = n;
}
else
{
--sizes[i];
break;
}
}
}
printf("\nMatrix: \n");
for (i = 0; i < k; i++)
{
for (j = 0; j < sizes[i]; j++)
printf("%i ", *(m[i] + j));
printf("\n");
}
printf("\nSum of elements of row:\n");
for (i = 0; i < k; i++)
printf("#%i - %i\n", i + 1, sum[i]);
free(sizes);
free(sum);
free(m);
return 0;
m is the matrix. Or more formally, it appears to be an array of "rows". Where each row is an array of integers.
sizes[i] is the length of the row represented by m[i].
This expression
*(m[i] + sizes[i] - 1) = n;
Appears to assign the value n to the last index of the row identified by m[i]. Essentially, it's appending to the end of the reallocated array.
This entire block of code is a bit complex:
while (1)
{
m[i] = (int * ) realloc(m[i], (++sizes[i]) * sizeof(int));
n = strtol(sym, & sym, 10);
sum[i] += n;
if (n)
{
*(m[i] + sizes[i] - 1) = n;
}
else
{
--sizes[i];
break;
}
}
It could be simplified to just:
int rowsize = 0;
while (1)
{
n = strtol(sym, &sym, 10); // parse the next number in str
if (n == 0) // the row ends when 0 is read
{
break;
}
m[i] = (int *)realloc(m[i], (rowsize+1) * sizeof(int); // grow the row's size by 1
m[i][rowsize] = n;
sum[i] += n;
rowsize++;
}
sizes[i] = rowsize;
m[i] is a pointer to the first element in the i:th matrix row
sizes[i] is the current number of columns in row i
sizes[i] - 1 is the last element in row i
m[i] + sizes[i] - 1 is a pointer to the last element in row i
*(m[i] + sizes[i] - 1) is the last element in row i
When allocating memory in C the result should not be cast, so
int* sizes = (int * ) calloc(k, sizeof(int));
should be simply
int* sizes = calloc(k, sizeof(int));
Also, the rows of the matrix m are never freed; to free the entire matrix you would need
for (i = 0; i < k; i++) {
free(m[i]);
}
free(m);
To answer your question the statement *(m[i] + sizes[i] - 1) = n; assigns the value n to whatever m[i] + sizes[i] - 1 points to. m is a pointer to a pointer to an int, so m[i] is an address of an int pointer. sizes[i] - 1 is usually how you convert from a size to index, so it's an offset from that int pointer.
Here are some suggested changes (all but one implemented below):
Reduce variable scope but initialize sum to NULL before the first failure so it can be unconditionally deallocated
It is better user experience to just read the data and terminate with an empty line instead of asking for the user count upfront. Just update the count k as we go along. This eliminates atoi which does not do any error handling. If you want to crash the program due to being out of memory you have to provide the data not just large a count.
(not fixed) realloc of 1 element at a time, if the O(i^2) is a performance issue, keep track of size and capacity of sum. When size == capacity, realloc by some factor, say, 2. Optionally, realloc to size when when we finish reading data as we now have the actual number of lines k.
No point of printing the array you just entered, which means we can get rid of the m and sizes arrays
Deallocate sum if realloc fails by introducing a temporary sum2 variable that will be NULL on error, but sum will still point to previously allocated data
Check for under and overflow of n and sum
Use sizeof on variable instead of type so you can change type just one place if needed
Allow 0 values by passing in by using a separate pointer endptr than sym to strtol()
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#define CHECK(p, msg) if(!(p)) {\
printf("%s:%d %s\n", __FILE__, __LINE__, (msg));\
goto out;\
}
#define MAXSTR 100
int main() {
int k;
char str[MAXSTR];
int *sum = NULL;
printf("Enter matrix:\n");
for(int i = 0;; i++) {
fgets(str, MAXSTR, stdin);
char *sym = str;
int *sum2 = realloc(sum, (i + 1) * sizeof(*sum));
CHECK(sum2, "realloc failed");
sum = sum2;
int j;
for(j = 0;; j++) {
char *endptr;
long n = strtol(sym, &endptr, 10);
CHECK(n >= INT_MIN && n <= INT_MAX,\
"value truncated");
if(sym == endptr) {
break;
}
sym = endptr;
CHECK((n >= 0 && sum[i] <= INT_MAX - n) || \
(n < 0 && sum[i] >= INT_MIN - n),\
"sum truncated");
sum[i] += n;
}
if(!j) {
k = i;
break;
}
}
printf("Sum of elements of row:\n");
for (int i = 0; i < k; i++)
printf("#%i - %i\n", i + 1, sum[i]);
out:
free(sum);
return 0;
}
Example execution:
Enter matrix:
0 1 2
Sum of elements of row:
#1 - 3

How to write the algorithm of this matrix in this ascending order in C.Where is error in my code?

I am writing this code to print the following matrix in this spiral order(spiral by column).But my code is printing totally different thing.
a a+7 a+8 a+15
a+1 a+6 a+9 a+14
a+2 a+5 a+10 a+13
a+3 a+4 a+11 a+12
Here is what i did:
int main() {
int a;
int Sum = 0;
int i = 0, j = 0,n;
printf("Insert the value of n: ");
scanf("%d",&n);
printf("Insert the value of a number: ");
scanf("%d",&a);
for(i=0;i<n;i++){
for(j=0;j<n;j++){
printf("%d ",a);
a = a + 7;
printf("\t");
}
printf("%d",a);
a = a + 1 ;
printf("\n");
}
return 0;
}
The way I approached this is to build the matrix of values you actually want, but doing so in column order, where we can relatively easily control the logic of value progression by row. Then, with that matrix in hand, print out the values in row order, as you want the output:
int main()
{
int a = 7;
int n = 4;
int array[4][4];
for (int c=0; c < n; ++c)
{
for (int r=0; r < n; ++r)
{
// values ascending for even columns
if (c % 2 == 0)
{
array[r][c] = a + c*n + r;
}
// values descending for odd columns
else
{
array[r][c] = a + c*n + n-r-1;
}
}
}
for (int i=0; i < n; ++i)
{
for (int j=0; j < n; ++j)
{
printf("%d ", array[i][j]);
}
printf("\n");
}
}
Output:
Demo here:
Rextester
Instead of using this complex mechanism to keep track of all elements you can just calculate the value to add at any time by simple arithmetic.
See this
int row;
int column;
printf("\n");
for (row = 0; row < n; row++) {
for (column = 0; column < n; column++) {
int base;
int flag;
if (column % 2 != 0) {
base = (column+1)/2 * 2*n - 1;
flag = -1;
}else {
base = column/2 * 2*n;
flag = 1;
}
printf( "%d ", a + base + flag * row);
}
printf("\n");
}
I hope you are able to follow this logic. If not feel free to ask.
Demo here:
Ideone
There seem to be two issues with your code as it is. As mentioned in the above comment, you are using the variable a in the loop calculation, so it is constantly being updated. This means your loop becomes invalid after a few iterations. If you define a dummy variable, this would avoid the problem. Secondly the implementation of the spiralling is close to being right, but it's not quite there.
Consider in the case n = 4. When you print along each row, the difference between a new element and the last alternates between values of (2n - 1) = 7 and 1. To take this into account, you could for example check every time you want to print whether the column index (j) is odd or even, and use this to determine which difference to add. Once you have the row machinery fixed, it shouldn't be difficult to extend it to the columns.
Simple solution using a matrix to calculate values before print them
#include <stdio.h>
int main(void)
{
int a;
int i = 0, j = 0, n;
printf("Insert the value of n: ");
scanf("%d", &n);
printf("Insert the value of a number: ");
scanf("%d", &a);
int matrix[n][n];
for (i=0; i< n*n; i++)
{
// even columns ascending
if (((i/n) % 2) == 0)
{
matrix[i%n][i/n] = a++;
}
// odd column descending
else
{
matrix[n-(i%n)-1][i/n] = a++;
}
}
for (i=0; i< n; i++)
{
for (j=0; j< n; j++)
{
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Output
Insert the value of n: 4
Insert start value: 1
1 8 9 16
2 7 10 15
3 6 11 14
4 5 12 13

How can I pass a malloc array to another function in order to change its values [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to implement a bubble sort algorithm, but with 3 functions, a gen_array to generate the array given a size and a maximum for the values and a sort to sort the values in a bubble sort way. I can't get the sort part to work.
However, the gen_array funcion is doing what it is supposed to and working when I call it and print its values on main().
Here is the code.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int gen_array(int ** list, int size, int max) {
*list = (int *)malloc(size * sizeof(int));
if (*list == NULL){
printf("ERROR: out of memory\n");
return 1;
}
srand( (unsigned)time( NULL ) );
for (int i = 0; i < size; ++i) {
(*list)[i] = rand() % max;
}
return 0;
}
int sort(int * a, int s) {
int *temp;
for (int i = 1; i < s; ++i) {
for (int j = 0; j < i - 1; ++j) {
if (*(a + i) > *(a + i + 1)) {
*(a + i) = temp;
*(a + i) = *(a + i + 1);
*(a + i + 1) = temp;
}
}
}
return 0;
}
int main() {
int size;
printf("array Size --> ");
scanf("%d", &size);
int * a;
gen_array(&a ,size, 100);
for (int i = 0; i < size; ++i) {
printf("%d ", a[i]);
}
printf("\n");
sort(a, size);
for (int j = 0; j < size; ++j) {
printf("%d", a[j]);
}
free(a);
getchar();
return 0;
}
After following #mch's comment I got this output,
Array Size --> 5
1 4 46 4 51
1 4 4 0 0
Process finished with exit code 0
So, the list is generating with 5 elements,
but the sort part isn't working, I believe the sort code is right (the bubble algorithm), but the pointers aren't being used correctly?
Perhaps I should copy the contents of the array with realloc() ?
There are several problematic errors in your code.
First, temp should be int, not int*. Remember, a is a pointer to the start of an array in the heap. *(a + i) is the value of the ith element of that array.
Second, temp should be set to *(a + i), not the other way around.
Also, as Weather Vane pointed out in the comments, the loops are wrong. You need to check array elements j and j + 1, not i. There are some other changes needed as part of that, but you can see those below.
Here's the sort method with these changes (I think the rest is all right except that you need to add spaces the second time you list the items):
int sort(int *a, int s) {
int temp;
for (int i = 0; i < s; ++i) {
for (int j = 0; j < s - i - 1; ++j) {
if (*(a + j) > *(a + j + 1)) {
temp = *(a + j);
*(a + j) = *(a + j + 1);
*(a + j + 1) = temp;
}
}
}
return 0;
}

Using pointers instead of an array [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I wrote this program a few weeks ago using arrays and now I need to use pointers instead of using arrays. I'm not exactly sure how to go about doing that so any tips would be appreciated! Thanks! :D
Here is the code:
#include <stdio.h>
int showArray(int row);
int exchangeRow(int row1, int row2);
int x, y;
int array[10][10];
int j;
int k;
int inputrow;
int inputcolumn;
int scanrow;
int temp;
int row1;
int row2;
int main() {
// Initialize array
for(j = 0; j < 10; j++) {
printf("\n");
for(k = 0; k < 10; k++) {
array[j][k] = j * 10 + k;
printf("%d ", array[j][k]);
}
}
printf("\n \n");
// Print out selected row
printf("Type in a number for the corresponding row to be printed \n");
scanf("%d", &inputrow);
if(inputrow >= 0 && inputrow < 10) {
for(j = 0; j < 10; j++) {
printf("%d ", array[inputrow][j]);
}
}
printf("\n \n");
//Print out selected column
printf("Type in a number for the corresponding column to be printed \n");
scanf("%d", &inputcolumn);
if(inputcolumn >= 0 && inputcolumn < 10) {
for(j = 0; j < 10; j++) {
printf("%d ", array[j][inputcolumn]);
}
}
printf("\n \n");
printf("Type in a number for the row that method showArray will print \n");
scanf("%d", &scanrow);
showArray(scanrow);
printf("\n \n");
printf("Type in two numbers for the rows that method exchangeRow will switch \n");
scanf("%d %d", &row1, &row2);
exchangeRow(row1, row2);
printf("\n \n");
system("PAUSE");
}
int showArray(int row) {
for(j = 0; j < 10; j++) {
printf("%d ", array[row][j]);
}
}
int exchangeRow(int row1, int row2) {
if(row1 >= 0 && row1 < 10 && row2 >= 0 && row2 < 10) {
temp = row1;
row1 = row2;
row2 = temp;
printf("The first row now holds the values: ");
showArray(row1);
printf("\n");
printf("The second row now holds the values: ");
showArray(row2);
}
}
I take it you mean "using dynamic memory allocation"...
The way a lot of people do 2D arrays dynamically is like this:
const size_t nrows = 10, ncols = 10;
int **array = malloc( nrows * sizeof(int*) );
for( i = 0; i < nrows; i++ ) {
array[i] = malloc( ncols * sizeof(int) );
}
But I hate this. If you are doing production code, this can be very slow. It's also harder to handle the case where you run out of memory, and there's no guaranteed locality of your array. Plus, it's ugly to free:
for( i = 0; i < nrows; i++ ) free(array[i]);
free(array);
In memory, your static array[10][10] is one contiguous block. So you should do the same:
int **array = malloc( nrows * sizeof(int*) );
array[0] = malloc( nrows * ncols * sizeof(int) );
for( i = 1; i < nrows; i++ ) {
array[i] = array[i-1] + ncols;
}
To free that:
free(array[0]);
free(array);
I often take this a step further, and do a single memory allocation instead of two. That way I have just one pointer. But I won't do that here. You have to be a little conscious of alignment, and the code is a little messier. It's an optimization that usually you don't need.
Hope that helps.
To be more specific, what is required of you is to use pointer notation instead of array notaiton
This would probably mean that your 2 dimensional array should be allocated as an array of pointers. Also it's individual elements should be accessed using pointers rather than the usual array indexing.
For e.g.
int * a = malloc(10 * sizeof(int)); // allocate memory for 10 integers
*a = 1; // assign first element of array
*(a+1) = 2; // assign second
The above was for 1D array. Extend it to multiple dimensions as in your original program.
When you declare an array, such as int arr[4];, arr actually "points" to a location in memory with 4 "spaces" that holds an integer each.
&arr means "address of" arr.
So, a pointer to arr could be defined as:
int *ptr = &arr[0];
But how would you get the data that ptr points to? The answer is:
*ptr;
But, this will only show you the first value of the data stored in the first "space" that arr occupies. To get the others in the array, all you need to do is increment your pointer along the space in memory, like so:
ptr++;
Further information can be found here: http://alumni.cs.ucr.edu/~pdiloren/C++_Pointers/neighbor.htm

Resources