我正在编写一个小的C程序,练习malloc
和sscanf
库函数。但不幸的是,我遇到了分段错误。我已经谷歌搜索和苦苦挣扎了几个小时,但没有结果。有人能帮我解决这个问题吗?
#include <stdio.h>
#include <stdlib.h>
void print_array(int a[], int num_elements);
int main(void) {
int m;
printf("How many numbers do you count: \n");
scanf("%d", &m);
int *a = (int*)malloc(m * sizeof(int*));
char buf[100];
setbuf(stdin, NULL);
if (fgets(buf, sizeof buf, stdin) != NULL) {
char *p = buf;
int n, index;
while (sscanf(p, "%d %n", &a[index], &n) == 1 && index < m) {
// do something with array[i]
index++; // Increment after success @BLUEPIXY
p += n;
}
if (*p != '\0')
printf("you are giving non-numbers, will be ignored");
}
print_array(a, m);
free(a);
return 0;
}
void print_array(int a[], int num_elements) {
int i;
for (i = 0; i < num_elements; i++) {
printf("%d ", a[i]);
}
}
m
个指针分配一个数组,而不是m
个整数。代码如下:int* a = (int*)malloc(m*sizeof(int*));
- BoBTFishint n, index;
-->int n, index = 0;
- BLUEPIXYsscanf(p, "%d %n", &a[index], &n) == 1 && index < m
-->index < m && sscanf(p, "%d %n", &a[index], &n) == 1
- BLUEPIXY