227k views
1 vote
Char *chars;

chars = malloc(11 * sizeof(char));

for (int j = 0; j < 11; j++) { chars[j] = helloworld[j]; }
can you modify this to make the function print elwrd?

User Mchl
by
7.9k points

1 Answer

1 vote

To modify the code to print "elwrd", you can add a loop after assigning the characters from `helloworld` to `chars`. Here's the modified code:

```C

#include <stdio.h>

#include <stdlib.h>

int main() {

char *chars;

chars = malloc(11 * sizeof(char));

char helloworld[] = "helloworld";

for (int j = 0; j < 11; j++) {

chars[j] = helloworld[j];

}

// Print "elwrd"

for (int j = 1; j < 5; j++) {

printf("%c", chars[j]);

}

// Free the allocated memory

free(chars);

return 0;

}

```

In this modified code, after assigning the characters from `helloworld` to `chars`, we add a loop to print the characters `'e'`, `'l'`, `'w'`, `'r'`, and `'d'`. The loop iterates from index 1 to index 4 (inclusive), printing each character using `printf("%c", chars[j])`.

Note that the `free(chars)` statement is added to release the memory allocated for `chars` before the program terminates.

User Gerd Castan
by
8.4k points