我发现将字符串从二维数组复制到一维数组时非常棘手。因此,我按地址访问了这些值。 for循环内部运行良好。一维数组是否真的是用二维数组值复制的。
char *str[4] = {"i " "California", "ii " "Texas", "iii " "Florida", "iv " "Washington"}; //two dimensional array
int r = 0, c, i = 0;
char *temp; //one dimesional array
for(r = 0; r < 4; r++){
c = 0;
while(*(str[r]+c) != '\0'){
printf("%c", *(str[r]+c));
c++;
temp = &str[r][c];
printf("%c", *temp);
}
printf("\n");
}
return 0;
答案 0 :(得分:1)
您可以使用calloc来分配临时指针内存大小。
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
char *str[4] = {"i " "California", "ii " "Texas", "iii " "Florida", "iv " "Washington"}; //two dimensional array
int r = 0;
for(r = 0; r < 4; r++)
{
char *temp = (char*) calloc (strlen(str[r]) ,sizeof(char));
strcpy(temp, str[r]);
printf("%s", str[r]);
printf("\n");
free(temp);
}
return 0;
}
答案 1 :(得分:0)
假设:
char array2dim[x][y];
然后创建一个一维数组。
char array1dim[x*y];
memcpy( array1dim, array2dim, x*y );