gpt4 book ai didi

c - 如何使用指针从二维字符数组中生成句子

转载 作者:行者123 更新时间:2023-11-30 16:18:37 24 4
gpt4 key购买 nike

我是 C 新手,所以如果我不够清楚,请耐心等待。我有一个作业,我需要创建一个函数来获取平方字符矩阵并从中生成一个字符串。该函数最终应该返回一个指向字符串的指针,这样在 main 中我可以用它初始化一个字符串并在最后打印它。

(而且我只能使用此函数内的指针,而不是常规数组语法)

例如矩阵是:

R O M E 
G O A L
H E A D
D E A D

我想造一个这样的句子:"ROME GOAL HEAD DEAD" .

我尝试制作一个仅在矩阵行上运行的 for 循环,这样我就可以将每一行复制到我之前在使用 strcpy() 的第一行中已经准备好的字符串(其中有足够的空间)。另一个strcat() .

什么也没发生。

抱歉我的英语不好,谢谢。

char * makeString(char *smallMat, int rows, char *pStr ) {
int i;
char sentence[(rows * rows) + rows + rows];
pStr = &sentence;
for (i = 0; i < rows; ++i) {
if (i == 0) {
strcpy(sentence, *(smallMat + i));
}
else{
strcat(sentence, ' ' + *(smallMat + i));
}
}
return pStr;
}

最佳答案

正如 @anonmess 所指出的,对于非 0 终止的字符序列,您不能使用 strcpy() 等。正如您自己所说,任务是使用指针。如果您使用了 strcpy() (并且如果它有效),您将解决该分配;)

这是一个不使用 pStr 的完整解决方案。

#include <stdio.h>  // printf()
#include <stdlib.h> // malloc()

static char smallMat[4][4] = {
{ 'R', 'O', 'M', 'E' },
{ 'G', 'O', 'A', 'L' },
{ 'H', 'E', 'A', 'D' },
{ 'D', 'E', 'A', 'D' }
};

char* makeString(char* smallMat, int rows) {
int currentRow, currentColumn;

/* space for all characters (rows * rows)
* + one character for each space + terminating '\0'. */
char* sentence = malloc((rows * rows) + rows);

char* p = sentence;

for (currentRow = 0; currentRow < rows; ++currentRow) {
for (currentColumn = 0; currentColumn < rows; ++currentColumn) {
*p++ = *(smallMat + (currentRow * rows) + currentColumn);
}
*p++ = ' ';
}
*--p = '\0'; /* replace the last space with terminating 0,
* so it can be printed. */
return sentence;
}

int main() {
char* output = makeString(smallMat, 4);
printf(output);
free(output);
return 0;
}

关于c - 如何使用指针从二维字符数组中生成句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55856688/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com