You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言字符串数组存文件问题:代码仅存首个元素,求多维数组存储方案

Hey Dave, let's fix this issue step by step

First: Your array definition has a critical bug

You declared char my_data[2][2], which means a 2x2 array of single characters (each element can only hold 1 printable character plus the null terminator \0). But you're trying to initialize it with strings like "this" (which is 4 characters + 1 null terminator = 5 bytes total). This causes memory overflow, corrupting your array's data and leading to unexpected behavior like only seeing partial data in the output file.

To fix this, define your array to fit the longest string you're storing. For your example, "test" is 4 characters, so use:

char my_data[2][5] = {"this", "is", "a", "test"};

The [5] gives enough space for 4 characters + the null terminator.

Second: Why your fwrite approach isn't working for your needs

You used fwrite to dump raw binary data into a .txt file. While this writes all the bytes of your array, raw binary doesn't carry any structural information (like "this is a 2x2 array"). Other programs won't know how to map those bytes back into an array they can index into. Also, text files aren't designed for raw binary data—you'll see gibberish if you open it in a text editor.

Better formats for multi-dimensional array storage

Since you want other programs to access elements via standard array indexing, here are the best options:

1. CSV (Comma-Separated Values)

CSV is a universal text format that's easy to parse in almost every programming language. You can store each row of your 2D array as a line, with columns separated by commas. For your data, the file would look like:

this,is
a,test

Other programs (like Python, Excel, or even another C program) can read this, split lines and commas, and build an array that supports array[row][col] indexing.

Here's modified code to write your array as CSV:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char my_data[2][5] = {"this", "is", "a", "test"};
    char path[] = "C:\\Users\\dave\\Documents\\data.csv"; // Use .csv extension for clarity
    FILE *fp ;

    if ((fp = fopen(path,"w+")) == NULL) {
        printf("cannot open file");
        exit(1);
    }

    // Write each row, with elements separated by commas
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            fprintf(fp, "%s", my_data[i][j]);
            if (j != 1) { // Skip comma after last element in the row
                fprintf(fp, ",");
            }
        }
        fprintf(fp, "\n"); // New line for next row
    }

    fclose(fp);
    return 0;
}

2. JSON

JSON is a structured format that explicitly represents arrays, making it even clearer for other programs to parse. Your data would look like:

[
  ["this", "is"],
  ["a", "test"]
]

Nearly all languages have built-in or third-party libraries to parse JSON directly into native array types, so accessing elements via array[0][0] (for "this") is trivial.

Here's a simple C implementation to write your array as JSON (no external libraries needed):

#include <stdio.h>
#include <stdlib.h>

int main() {
    char my_data[2][5] = {"this", "is", "a", "test"};
    char path[] = "C:\\Users\\dave\\Documents\\data.json";
    FILE *fp ;

    if ((fp = fopen(path,"w+")) == NULL) {
        printf("cannot open file");
        exit(1);
    }

    // Manually construct the JSON array structure
    fprintf(fp, "[\n");
    for (int i = 0; i < 2; i++) {
        fprintf(fp, "  [\"%s\", \"%s\"]", my_data[i][0], my_data[i][1]);
        if (i != 1) { // Add comma after first row
            fprintf(fp, ",");
        }
        fprintf(fp, "\n");
    }
    fprintf(fp, "]");

    fclose(fp);
    return 0;
}

3. Binary Format (for performance)

If you need fast read/write speeds and only plan to use the data with C/C++ or similar low-level languages, you can write the array in binary—but you must include metadata about the array dimensions (rows and columns) so the reader knows how to interpret the data. For example, first write the number of rows (2), then columns (2), then each string's data.

Final Notes

  • Always make sure your array is sized correctly to avoid memory overflow—this was the root cause of your initial partial data issue.
  • .txt is fine for simple text, but structured formats like CSV or JSON are far better for multi-dimensional data that needs to be accessed by other programs.

内容的提问来源于stack exchange,提问作者DaveC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 14:22:28