我正在尝试读取文件,并且仅将数字存储在数组中。
我的示例是file.csv
"1","2","3"
"1","4","6","7"
"12","15"
请不要建议这些解决方案
sizeof(arr) / sizeof(arr[0])
或*(&arr + 1) - arr
因为这两个都不给出包含实际值的数组的长度。它只是在声明数组时给出数组的长度。我想知道存在实际值时在运行时数组的长度。
问题陈述:在每一行中找到numOfwords(出现在 代码注释)。
我的代码如下:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i = 0, j = 0, k = 0;
char literal, string[4][10][4];
char *filename = "file.csv";
FILE *f;
f = fopen(filename, "r");
while ((literal = getc(f)) != EOF) {
if (isdigit(literal)) {
string[i][j][k] = literal;
k++;
} else {
if (k > 0) {
string[i][j][k] = '\0';
}
k = 0;
}
if (literal == ',') j++;
if (literal == '\n') i++, j = 0;
}
int numOfLines = i;
int total = 0;
for (int p = 0; p < numOfLines; p++) {
// int numOfWords = *(&string[p] + 1) - string[p]; // Returns 10
// int numOfWords = sizeof(string[p]) / sizeof(string[p][0]); // Returns 10
//
// The Problem Statement: Find the numOfwords in each line.
printf("numOfWords in line %p: %d\n", numOfWords);
for (long int q = 0; q < numOfWords; q++) {
/* code */
total += atoi(string[p][q]);
}
}
printf("Sum = %d", total);
}
任何比此代码更好的解决方案都值得赞赏。
输出:
numOfWords in line 1: 3
numOfWords in line 2: 4
numOfWords in line 3: 2
Sum = 51
答案 0 :(得分:2)
您必须自己跟踪放置在数组中的元素数量。没有其他办法。
答案 1 :(得分:-2)
也许是:
typedef struct
{
size_t size;
size_t elementsize;
unsigned char array[];
}myarray;
myarray *MA_Init(void)
{
myarray *arr = calloc(1, sizeof(*arr));
return arr;
}
myarray *MA_alloc(myarray *arr, size_t nelem, size_t elemsize)
{
narr = realloc(arr, nelem * elemsize + sizeof(*narr));
if(narray)
{
narray -> size = nelem;
narray -> elementsize = elemsize;
}
return narr;
}
int MA_Set(myarray *arr, size_t index, void *elem)
{
int result = !arr;
result = result && (index < arr -> size);
if(result)
{
memcpy(&arr -> array[index * arr -> elementsize], elem, arr -> elementsize);
}
return result;
}
int MA_Get(myarray *arr, size_t index, void *elem)
{
int result = !arr;
result = result && (index < arr -> size);
if(result)
{
memcpy(elem, &arr -> array[index * arr -> elementsize], arr -> elementsize);
}
return result;
}
... 等等...