How do I access a 3×3 array from first element to last using a pointer?

Is there a way to use a pointer to point at the first element of the array then loop until the end of the array?

#include <stdio.h>


int main(){
    int A[50][50][50];
    int sum;
    int i,j,k;
    int row,column,depth;
    int *ptr;
            do {
                printf("Please input row: ");//row
                scanf("%d", &row);
                printf("Please input column: ");//column
                scanf("%d", &column);
                printf("Please input depth: ");//depth
                scanf("%d", &depth);

                if (row <= 0 || column <=0 || depth <=0) {
                    printf("Wrong input!!!n");
                }
            } while (row <= 0);

            printf("Row is equal to:%dn", row);
            printf("Column is equal to:%dn", column);
            printf("Depth is equal to:%dn", depth);

            for (i=0;i<row ;i++) {
                for(j=0;j<column;j++){
                    for(k=0;k<depth;k++){
                        printf("Please input value for Array[%d][%d][%d]: ", i + 1,j+1,k+1);
                        scanf("%d", &A[i][j][k]);
            }
                }
                    }
            ptr = &A[0][0][0];

        


  printf("nThe sum of all elements is: %dn", sum);

}

I’m trying to calculate all the sum of all element using pointer and trying to using the loop but it won’t work is there other way to access it.

Here’s how my loop looks:

for(i=0;i<row;i++){
                sum+=*(ptr+i);
                    for(j=0;j<column;j++){
                    sum+=*(ptr+j);
                        for(k=0;k<depth;k++){
                            sum+=*(ptr+k);
            }
                }
                    }

I’m currently studying in Pointer lesson in C programing so i know just only basic.

New contributor

jr. is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

13

Strictly & most correctly speaking, you cannot iterate across the array int A[50][50][50]; using a pointer of type int*.

The reason why is that arr[i] is “syntactic sugar” for the 100% equivalent form *(arr + i) and therefore the rule that all array access boils down to is always the rule of pointer arithmetic using the + operator. Formally, this operator has a restriction specified in C17 6.5.6:

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

Meaning pointer arithmetic followed by dereferencing is only well-defined within the bounds of the pointed-at array. A pointer type* may only do arithmetic within the bounds of elements 0 to n in an array of type type [n].

When you do ptr = &A[0][0][0]; you set the int* ptr to point at the very first array of type int [50]. Consecutive iteration of ptr and access is only defined within that int [50] array. No matter if you use ptr[i] or ptr++ ... *ptr. Once you go past the first array, you are invoking undefined behavior if you de-reference the pointer from there on.

In practice compilers are forced to allocate this whole thing as an array-of-array-of-arrays in adjacent memory and therefore often also generate code that works, even though the C language makes no guarantees for it. But writing code relying on undefined behavior is dangerous and brittle. So if you got this task from a teacher who is “proving” to you that “it works”, please send them my way by linking them this post 🙂 You can’t prove that code relying on undefined behavior “works” through practical experiments (see What is undefined behavior and how does it work?)

As mentioned in this off-site duplicate Can I access an array element from a pointer to an object contiguous with but outside the array?, one possible work-around is to use a pointer to character type instead. Then thanks to the special rule regarding character types, the compiler is forced to view the whole int A[50][50][50]; just as if it was an unsigned char A[50*50*50*sizeof(int)] and from there you can access it byte by byte.

4

you need to correctly index the pointer and make sure you’re accessing the elements of the 3D array properly. Your current implementation has some issues with pointer arithmetic.

look at this code

#include <stdio.h>

int main() {
    int A[50][50][50];
    int sum = 0;
    int i, j, k;
    int row, column, depth;
    int *ptr;

    do {
        printf("Please input row: ");
        scanf("%d", &row);
        printf("Please input column: ");
        scanf("%d", &column);
        printf("Please input depth: ");
        scanf("%d", &depth);

        if (row <= 0 || column <= 0 || depth <= 0) {
            printf("Wrong input!!!n");
        }
    } while (row <= 0 || column <= 0 || depth <= 0);

    printf("Row is equal to: %dn", row);
    printf("Column is equal to: %dn", column);
    printf("Depth is equal to: %dn", depth);

    for (i = 0; i < row; i++) {
        for (j = 0; j < column; j++) {
            for (k = 0; k < depth; k++) {
                printf("Please input value for Array[%d][%d][%d]: ", i + 1, j + 1, k + 1);
                scanf("%d", &A[i][j][k]);
            }
        }
    }

    
    ptr = &A[0][0][0];

    
    for (i = 0; i < row; i++) {
        for (j = 0; j < column; j++) {
            for (k = 0; k < depth; k++) {
                sum += *ptr; 
                ptr++;
            }
        }
    }

    printf("nThe sum of all elements is: %dn", sum);

    return 0;
}

make sure to initialize sum to 0
don’t use separate loops for each dimension and remember the pointer is incremented directly inside the innermost loop
after accessing the value at *ptr, increment ptr to point to the next integer
be sure all dimensions are checked for positive values in the do while loop

3

Using an intermediate char * in the following way does not use the bounds of any of the inner arrays. It uses the array like one big array of char that is also properly aligned as an array of int. It should be free of undefined behavior:

/* given: int A[50][50][50], row <= 50, col <= 50, depth <= 50 */
char *cptr = (char *)&A;
int sum = 0;
for (int i = 0; i < row; i++) {
    for (int j = 0; j < col; j++) {
        for (int k = 0; k < depth; k++) {
            size_t ioffset = (i * row * col) + (j * col) + k; 
            size_t coffset = ioffset * sizeof(int);
            int *iptr = (int *)(cptr + coffset);
            sum += *iptr;
        }
    }
}
printf("Sum = %dn", sum);

(The above code is a modified version of code with undefined behavior from a deleted answer to the question, with the addition of the intermediate char *.)

Iterating through all elements of the array (not just the used elements) could be done in the following way:

sum = 0;
for (char *cp = (char *)&A; cp < (char *)&A + sizeof (A); cp += sizeof (int)) {
    int *ip = (int *)cp;
    sum += *ip;
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật