重要提示:我对 malloc 没有深入的了解,所以尽量让事情变得尽可能简单 您好,我想创建一个动态字符串数组(使用 malloc),然后打印这些字符串(对于初学者)。
这就是我所拥有的
int main(){
char **namesofcolumns = malloc(4 * sizeof(char*));
for(int i = 0; i < 4; i++){
namesofcolumns[i] = malloc(20 * sizeof(char));
}
int count = 1;
for(int i = 0; i < 4; i++){
printf("Enter %d column name\n", count);
scanf("%s", namesofcolumns[i]);
count++;
}
我这里可能已经有错误了。如何打印输入的字符串?
可以使用数组来代替分配内存。
#include <stdio.h>
#include <stdlib.h>
#define LENGTH 18
#define COLS 4
// stringify to use in scanf format string
#define FS(x) SFS(x)
#define SFS(x) #x
void scanHeader ( char namesOfRows[COLS][LENGTH + 1]) {
for(int itemNo = 0; itemNo < COLS; itemNo++){
printf("Enter %d column name\n", itemNo + 1);
scanf("%"FS(LENGTH)"s", namesOfRows[itemNo]); // scan up to LENGTH characters
}
}
void printHeader ( char namesOfRows[COLS][LENGTH + 1]) {
for(int itemNo = 0; itemNo < COLS * LENGTH + 2 * ( COLS - 1); itemNo++){
printf("_");
}
printf("\n");
for(int itemNo = 0; itemNo < COLS; itemNo++){
if ( itemNo) { // skip on first iteration
printf ( " |");
}
printf ( "%*.*s", LENGTH, LENGTH, namesOfRows[itemNo]);
}
printf ( "\n");
}
int main ( void) {
char namesofcolumns[COLS][LENGTH + 1] = { ""}; // +1 for the terminating zero
scanHeader ( namesofcolumns);
printHeader ( namesofcolumns);
}