使用 C 中的指针将数组的内容复制到多维数组?

标签 c arrays pointers copy

 //Given this snippet of code:

    int main() {
        char sample[] = "Hello World";
        char ma[2][6]; 
        char *sptr, *mptr;

        return 0; 
    }

我正在思考这个问题。 sptr 是指向数组sample 的指针,mptr 是指向数组ma 的指针。我是否首先需要引用指向各自数组的指针,然后循环遍历数组 ma 的每个维度,然后递增两个指针并将它们设置为彼此相等? 这是我到目前为止所写的内容

int main(){
char sample[] = "Hello World"; // Create an arry of char  to hold the string "Hello World"
char ma[2][6];    //Create an two dimensional array of char  with 2 rows and  6 columns
char *sptr, *mptr; // Create two pointer variables of type char that are used to copy the content from array sample into array ma
char*sptr = sample;
char*mptr = ma; 
int row;
int column;

for (row = 0; row < 2; row++) {
    for (column = 0; column < 6; column++){
        *sptr++ = *mptr++;
    }
}



return 0;

最佳答案

给定,

char sample[] = "Hello World";
char ma[2][6];
char *sptr, *mptr;

用起来没问题

sptr = sample;

但不是

char*sptr = sample;

不能两次定义变量。

带有 mptr 的行有不同的问题。您当然不能重新定义变量。但是,您不能使用

mptr = ma; 

在上面的语句中,ma 衰减为类型为 char (*)[6] 的值,即指向 6 个字符数组的指针。 mptr 的类型不是这样的。

为了使用

mptr = ma; 

您必须将mptr定义为:

char (*mptr)[6];

在循环中。

for (row = 0; row < 2; row++) {
    for (column = 0; column < 6; column++){
        *sptr++ = *mptr++;
    }
}

有几个问题。

下面的行有问题。

        *sptr++ = *mptr++;

但是,这可能是由于您对如何使用 mptr 的误解所致。

此外,您的问题表明您想要将一维数组的内容复制到二维数组。您需要有一个在赋值运算符的左侧包含 mptr 的表达式,以及一个在表达式的右侧包含 sptr 的表达式。

然后,您已经弄清楚如何将一维数组的内容划分为二维数组。您是否希望 sptr 的前 6 个字符位于 ma[0] 中?您希望 m[0]m[1] 为空终止字符串吗?

以及,当一维数组的长度太大而无法容纳 ma 提供的空间时该怎么办。如果 ma[0]ma[1] 是 null 终止字符串,则 ma 最多可以容纳长度为 的字符串10 .

而且,如果到达一维字符串的末尾,则必须添加逻辑来跳出 for 循环。

这里有一些可以开始的事情。

for (row = 0; row < 2 && *sptr != '\0'; row++) {

    // No matter when the iteration stops,
    // mptr[row] will be a valid null terminated string.
    mptr[row][0] = '\0';

    // Don't use all the elements of the array.
    // Leave the last element for the terminating null character. 
    for (column = 0; column < 5 && *sptr != '\0'; column++){
        mptr[row][column] = *sptr++;

        // No matter when the iteration stops,
        // mptr[row] will be a valid null terminated string.
        mptr[row][column+1] = '\0';
    }
}

关于使用 C 中的指针将数组的内容复制到多维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26134447/

相关文章:

c - '\n'如何在汇编中表达?

c - 奇怪的C优先级评估

arrays - 从(非)正态分布数字数组中删除不相关的值(尾部)

arrays - 在 Laravel 中打印出集合的值

c - 在 C 中声明文件指针而不是 FILE * 指针的替代方法

C 是否可以使用结构变量进行定义?

sql - 在 Redshift 中使用 json_extract_path_text 时如何跳过错误?

c++ - STL::带有原始指针的迭代器

arrays - unsafe.Pointer to []byte in Go

c - C中的不同撇号