-
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[]) {
int n, i;
int *numbers;
printf("How many numbers? ");
scanf("%d", &n);
numbers = malloc(n*sizeof (int));
if (numbers == NULL) {
fprintf(stderr, "out of memory\n");
exit(1);
}
for (i = 0; i < n; i++)
scanf("%d", &numbers[i]);
printf("In reverse order:\n");
for (i = n - 1; i >= 0; i--)
printf("%d\n", numbers[i]);
return 0;
}
-
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[]) {
int i;
int *buffer;
int buffer_length = 1024;
/*
* allocate initial buffer
*/
buffer = malloc(buffer_length*sizeof (int));
if (buffer == NULL) {
fprintf(stderr, "out of memory\n");
exit(1);
}
for (i = 0; ; i++) {
if (i >= buffer_length) {
/*
* buffer full - increase its size
*/
buffer_length += 1024;
buffer = realloc(buffer, buffer_length*sizeof (int));
if (buffer == NULL) {
fprintf(stderr, "out of memory\n");
exit(1);
}
}
scanf("%d", &buffer[i]);
if (buffer[i] < 0)
break;
}
printf("In reverse order:\n");
for (i--; i >= 0; i--)
printf("%d\n", buffer[i]);
return 0;
}
-
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*
* split a comma-separated string into sub-strings
* return substrings in malloc'ed NULL terminated array
*/
char **
split(char *s) {
char **substrings;
char *p, *q;
int n_substrings, i;
/*
* count how many substrings
*/
n_substrings = 1;
for (p = s; *p != '\0'; p++)
if (*p == ',')
n_substrings++;
substrings = malloc((n_substrings + 1)*sizeof (char *));
if (substrings == NULL) {
fprintf(stderr, "out of memory\n");
exit(1);
}
p = s;
for (i = 0; i < n_substrings; i++) {
/*
* calculate length of this substring
*/
int substring_length = 0;
for (q = p; *q != ',' && *q != '\0'; q++)
substring_length++;
/*
* malloc space for this substring
*/
substrings[i] = malloc((substring_length + 1)*sizeof (char));
if (substrings[i] == NULL) {
fprintf(stderr, "out of memory\n");
exit(1);
}
/*
* copy substring to malloc'ed space
*/
strncpy(substrings[i], p, substring_length);
substrings[i][substring_length] = '\0';
/*
* move p to start of next substring
*/
p += substring_length + 1;
}
substrings[n_substrings] = NULL;
return substrings;
}
enum {
MAX_LINE = 1024
};
int
main(int argc, char *argv[]) {
int i;
char line[MAX_LINE];
char **substrings;
printf("Enter a comma separated string: ");
fgets(line, MAX_LINE, stdin);
for (i = 0; i < MAX_LINE; i++)
if (line[i] == '\n') {
line[i] = '\0';
break;
}
substrings = split(line);
for (i = 0;; i++) {
if (substrings[i] == NULL)
break;
printf("substring %d = '%s'\n", i, substrings[i]);
}
return 0;
}