← The C Language
Lesson 50 of 77 · 10 XP
Accessing memory
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Allocated memory is accessed through a pointer — with an index or with arithmetic:
int *a = malloc(5 * sizeof *a);
a[0] = 10; // the same as *(a + 0) = 10
*(a + 1) = 20; // the same as a[1] = 20
Pointers can be passed to functions: that way a function gets access to data on the heap. You can also return a pointer to allocated memory from a function. Unlike a local variable, it will stay alive:
int *make_range(int n)
{
int *a = malloc(n * sizeof *a);
if (a == NULL)
return NULL;
for (int i = 0; i < n; i++)
a[i] = i;
return a; // the calling code will free it
}
It's important to agree on who owns the memory and who frees it. Usually this is written in a comment to the function.
Task. Write char *repeat(const char *s, int k), which returns a new string on the heap — s repeated k times. The program reads a word and k, prints the result and frees the memory.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.