C++
tensor manipulation
programming
data structures
coding tutorial

How to fill a tensor in C

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

In plain C, a tensor is usually just a contiguous block of memory plus shape information. Filling it means deciding how the multidimensional indices map to the flat buffer, then writing values into that buffer consistently.

Start with a flat memory layout

A tensor with shape (rows, cols, depth) is typically stored as a one-dimensional array in row-major order. For example, a 2 x 3 x 4 tensor holds 2 * 3 * 4 = 24 elements.

In C, you might allocate it like this:

c
1#include <stdio.h>
2#include <stdlib.h>
3
4int main(void) {
5    int rows = 2;
6    int cols = 3;
7    int depth = 4;
8    int total = rows * cols * depth;
9
10    float *tensor = malloc(sizeof(float) * total);
11    if (tensor == NULL) {
12        return 1;
13    }
14
15    free(tensor);
16    return 0;
17}

At that point, the tensor is just a flat float *. The multidimensional meaning comes from how you calculate offsets.

Fill with nested loops

The clearest way to fill a tensor is with nested loops and an index calculation:

c
1#include <stdio.h>
2#include <stdlib.h>
3
4int main(void) {
5    int rows = 2, cols = 3, depth = 4;
6    int total = rows * cols * depth;
7    float *tensor = malloc(sizeof(float) * total);
8    if (tensor == NULL) {
9        return 1;
10    }
11
12    for (int i = 0; i < rows; i++) {
13        for (int j = 0; j < cols; j++) {
14            for (int k = 0; k < depth; k++) {
15                int index = i * (cols * depth) + j * depth + k;
16                tensor[index] = (float)(i + j + k);
17            }
18        }
19    }
20
21    printf("%f\n", tensor[0]);
22    free(tensor);
23    return 0;
24}

If you only want a constant such as 5.0f everywhere, keep the same loop structure and assign that constant instead of a computed expression.

The key part is the index formula. That is what turns three coordinates into a position in the contiguous buffer.

Use memset only for simple byte patterns

If you want to fill the entire tensor with zero, calloc or memset can help:

c
float *tensor = calloc(total, sizeof(float));

Or:

c
memset(tensor, 0, sizeof(float) * total);

But memset only works safely for patterns that make sense byte-by-byte. Zero is fine. Arbitrary floating-point values such as 1.0f are not. For non-zero initialization, use loops.

Wrap the indexing logic in a helper

To make the code safer and easier to reuse, hide the offset math in a function:

c
int offset3d(int i, int j, int k, int cols, int depth) {
    return i * (cols * depth) + j * depth + k;
}

Then filling becomes:

c
tensor[offset3d(i, j, k, cols, depth)] = value;

That reduces repeated index math and makes layout assumptions more explicit.

Libraries follow the same idea

Even when you use a tensor library, the underlying concept is similar: the tensor owns a contiguous or strided memory region, and the library provides safer indexing helpers. Understanding the flat-buffer model is still useful because it explains why shape, stride, and memory order matter.

Common Pitfalls

  • Forgetting that a tensor in C is usually just a flat buffer with manual indexing.
  • Using the wrong offset formula and silently writing into the wrong positions.
  • Using memset for non-zero floating-point initialization.
  • Forgetting to free allocated memory.
  • Mixing row-major assumptions with a layout expected by another library or API.

Summary

  • In plain C, filling a tensor usually means filling a flat contiguous buffer.
  • Nested loops plus a correct index formula are the standard approach.
  • 'calloc or memset are fine for zero initialization, but loops are safer for arbitrary values.'
  • Small helper functions make index math easier to maintain.
  • Understanding the flat memory layout is the foundation for using tensor libraries correctly.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.