How can I fix that with pointers ? with *p ? How can ı find the total of columns? I want to choose which column ı chose and see the total of it. lets say array is this:
2 6 9
5 6 9
4 8 4
2 6 0
4 6 7
then here is my program fragment:
for(*p=0;p<size;p )
sum=sum *p;
printf("\n");
CodePudding user response:
Using pointers:
#include <stdio.h>
#define Size(x) (sizeof(x) / sizeof(*x))
int main() {
int array[][3] = {
{2, 6, 9},
{5, 6, 9},
{4, 8, 4},
{2, 6, 0},
{4, 6, 7}
};
int selected_column;
// Size(*array) will be 3, the number of columns, that is:
// sizeof(int[3]) / sizeof(int)
printf("Select column (1 - %zu): ", Size(*array));
if(scanf(" %d", &selected_column) != 1 ||
selected_column < 1 || selected_column > Size(*array)) return 1;
--selected_column; // make it zero-based
int sum = 0;
// Size(array) will be 5, the number of rows, that is:
// sizeof(int[5][3]) / sizeof(int[3])
for(int(*p)[Size(*array)] = array, (*e)[Size(*array)] = p Size(array);
p != e; p)
{
sum = (*p)[selected_column];
}
printf("col %d sum = %d\n", selected_column, sum);
}
A much simpler and idiomatic approach would be to iterate over he outer array (consisting of int[3]
s):
#include <stdio.h>
#define Size(x) (sizeof(x) / sizeof(*x))
int main() {
int array[][3] = {
{2, 6, 9},
{5, 6, 9},
{4, 8, 4},
{2, 6, 0},
{4, 6, 7}
};
int selected_column;
printf("Select column (1 - %zu): ", Size(*array));
if(scanf(" %d", &selected_column) != 1 ||
selected_column < 1 || selected_column > Size(*array)) return 1;
--selected_column;
int sum = 0;
for(int row = 0; row < Size(array); row) {
sum = array[row][selected_column];
}
printf("col %d sum = %d\n", selected_column, sum);
}
Output from both versions:
col 0 sum = 17
CodePudding user response:
Your code should look like this if you want to do it with a pointer.
#include<stdio.h>
int main(){
int arr[5][3] = {{2, 6, 9},{5, 6, 9},{4, 8, 4},{2, 6, 0},{4, 6, 7}};
int sum = 0;
int *p = arr;
for(int i=0;i<3;i ){
sum = sum *(p i);
}
printf("%d\n",sum);
return 0;
}