#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main(void){
char pos[4][4];
char loc[4];
int i;
for(i=0;i<4;i++){
pos[i][0]=4;
pos[i][1]=4;
pos[i][2]=4;
pos[i][3]=4;
} loc[i]=" ";
strcat(loc[i],pos[i]);
}
我试图将 pos[i] 的所有内容保存在一个串联的 字符串。我不知道该怎么做。如果有任何提示,我将不胜感激。
最佳答案
改编后的代码:
#include <stdio.h>
#include <string.h>
int main(void) {
char pos[4][4];
char *loc;
int i;
for (i = 0; i < 4; i++) {
pos[i][0] = 'a' + i;
pos[i][1] = 'a' + i;
pos[i][2] = 'a' + i;
pos[i][3] = 'a' + i;
};
loc = (char *) pos;
for (i = 0; i != sizeof(pos); i++) {
fputc(loc[i], stdout);
}
fputc('\n', stdout);
/* output: aaaabbbbccccdddd */
return 0;
}
pos
已经是您要查找的串联。
pos
是连续字符的内存块的地址
并且可以这样声明和初始化:
char pos[4][4] = {
{ 'a', 'a', 'a', 'a' }
, { 'b', 'b', 'b', 'b' }
, { 'c', 'c', 'c', 'c' }
, { 'd', 'd', 'd', 'd' }
};
或者这样(编译器可能会发出警告):
char pos[4][4] = {
'a', 'a', 'a', 'a'
, 'b', 'b', 'b', 'b'
, 'c', 'c', 'c', 'c'
, 'd', 'd', 'd', 'd'
};
这两个维度只是 pos
的一个 View ,它可以被展平:(char *) pos
。
如果您需要拼合副本:
char cpy[sizeof(pos)];
memcpy(cpy, pos, sizeof(pos));
关于连接 C 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34155832/