将字符串从main复制到结构c

问题描述 投票:0回答:1

我有一些字符串存储在名为“info”的二维数组中,并希望将它们复制到“notes”结构中的数组“reply”中。香港专业教育学院尝试使用下面的for循环,但它的剂量复制。我没有得到错误,它只是复制字符串。我不知道还能做什么,有人可以给我一些关于我需要使用的建议吗?

struct notes{
   char tasks[40][250];
   char reply[40][250];
};

struct notes store;

#define M 11

int main()
{

    int a, i, k, l, j;
    char info[40][250];


    for( i = 0 ; i < M ; i++){
       strncpy(store.reply[i], info[i], 250);
    }   


}
c arrays loops for-loop struct
1个回答
0
投票

你的问题开始于“我有2个数组中存储的字符串数量”info“”但我们实际上并没有看到这种情况。

如果您使用某些字符串初始化了info,我认为您的代码没有任何问题。

尽量避免使用“魔法”数字;改用#define

#include <stdint.h>
#define NUM 2   //number of strings
#define LEN 25  //length of each string

struct notes{
   char tasks[NUM][LEN];
   char reply[NUM][LEN];
};

struct notes store;
char info[NUM][LEN];

int main()
{
    /* Assign strings to info */
    char *mystring1 = "Hello world";
    strncpy(info[0], mystring1, LEN);
    char *mystring2 = "I love pie";
    strncpy(info[1], mystring2, LEN);

    /* Copy them to store.reply */
    for(uint8_t i=0; i<NUM; i++){
        strncpy(store.reply[i], info[i], LEN);
    }

    /* Print results */
    for(uint8_t i=0; i<NUM; i++){
        printf("%s\n", store.reply[i]);
    }
}

输出:

Hello world
I love pie
© www.soinside.com 2019 - 2024. All rights reserved.