【发布时间】:2021-07-06 13:28:03
【问题描述】:
我正在尝试将一个字符串转换为它在 C 中的等效矩阵形式。该矩阵将有 3 行和尽可能多的列。下面的代码没有编译,我也没搞清楚是怎么回事。
GCC 抛出的错误是:
app.c:10:25: error: subscripted value is not an array, pointer, or vector
printf("%d\n", arr[i][k]);
~~~^~
1 error generated.
主文件(app.c):
#include <stdio.h>
#include "converter.h"
int main() {
char source[] = "This is the source. "; // placeholder text
int arr = convert(source);
for (int i = 0; i < 21; i++) {
for (int k = 0; k < 3; k++) {
printf("%d\n", arr[i][k]); // error occurs at this line.
}
}
return 0;
}
converter.c 文件:
// Converts an input string to its respective ASCII matrix.
#include <string.h>
#include <stdio.h>
#include "converter.h"
// Converts the entire string into an multi-dimensional array.
int convert(char text[]){
// copy the input text into a local store.
char store[strlen(text)];
strcpy(store, text);
// make sure the length of the input string is a multiple of 3 or make it so.
int excess = strlen(store)%3;
char excess_spaces[3] = " ";
if (excess != 0) {
strncat(store, excess_spaces, 3-excess);
}
// covert the source into an array
int arr[3][strlen(store)/3];
int steps = strlen(store)/3;
for (int i = 0; i < steps; i++) {
int t[3];
for (int k = 0; k < 3; k++) {
t[k] = (int) store[3*i+k];
arr[k][i] = t[k];
}
}
return arr;
}
converter.h 文件:
int convert(char text[]);
【问题讨论】:
-
不是数组、指针或向量。这似乎很清楚。你理解
arr之后是什么类型:int arr = convert(source);? -
convert函数存在多个问题。它的返回类型是int,而不是数组。此外,您不能返回对局部变量的引用,因为它在函数退出后立即变为无效 - 传入一个数组以供函数填充或使用动态内存分配。 How to return matrix (2D array) from function? (C)
标签: c