Это логическая ошибка:
is.peek() != '\0' || is.peek() != delim
если is.peek()
== '\ 0' , then it won't equal
delim (unless is also '\0')
if
is.peek () == delim
, то оно не будет равно [ 116] (опять же, кроме случаев, когда '\ 0')
Вы ищете:
is.peek() != '\0' && is.peek() != delim
Это завершает цикл, если is.peek()
равно '\0'
или [119 ]
/* We include the following to get the prototypes for:
* malloc -- allocates memory on the freestore
* free -- releases memory allocated via above
* atoi -- convert a C-style string to an integer
* strtoul -- is strongly suggested though as a replacement
*/
#include <stdlib.h>
static int *foo;
int main(int argc, char *argv[]) {
size_t size = atoi(argv[ 1 ]); /*argv[ 0 ] is the executable's name */
foo = malloc(size * sizeof *foo); /* create an array of size `size` */
if (foo) { /* allocation succeeded */
/* do something with foo */
free(foo); /* release the memory */
}
return 0;
}
Caveat:Off материал манжеты, без любой проверки ошибок.
В C можно сделать это с этим при игнорировании проверки ошибок:
#include <stdlib.h>
static int *foo;
int main(int argc, char **argv)
{
int size = atoi(argv[1]);
foo = malloc(size * sizeof(*foo));
...
}
Если Вы не хотите глобальной переменной, и Вы используете C99, Вы могли бы сделать:
int main(int argc, char **argv)
{
int size = atoi(argv[1]);
int foo[size];
...
}
Это использует VLA - массив переменной длины.
Если необходимо инициализировать данные, можно использовать calloc:
int* arr = calloc (nb_elems, sizeof(int));
/* Do something with your array, then don't forget to release the memory */
free (arr);
Таким образом, выделенная память будет инициализирована с, обнуляет, который может быть полезным. Обратите внимание, что можно использовать любой тип данных вместо интервала.
int count = getHowManyINeed();
int *foo = malloc(count * sizeof(int));