读书人

一个结构体变量相加的有关问题

发布时间: 2012-03-08 13:30:13 作者: rapoo

一个结构体变量相加的问题
[code=C/C++][/code]
1 #include <stdio.h>
2 #include <string.h>
3
4 typedef struct card {
5 int i;
6 char str[100];
7 }card;
8 int main(void)
9 {
10 int i;
11 card cd, *cp, tt;
12 cd.i = 10;
13 cd.str = {'a', 'b', 'c', 'd'};
14 cp->i = 20;
15 cp->str = {};
16 tt.i = cd.i + cp->i;
17 tt.str = strcpy(cp->str, cd.str);
18 //i = strlen(tt.str);
19 //tt.str[i + 1] = {'\0'};
20 printf("tt.i %d\n", tt.i);
21 printf("tt.str %s\n", tt.str);
22 return 0;
23 }

[解决办法]
那个格式只能在初始化时用。你这里不是初始化一个数组。
[解决办法]

C/C++ code
#include <stdio.h>#include <string.h>   typedef struct card {    int i;    char str[100];}card;int main(void){    //int i;    char *p;    card *cp;    card cd = {10,{'a', 'b', 'c', 'd'}};    card tt = {0,{'\0'}};    cp = new card;    cp->i = 20;    strcpy(cp->str,"e");    tt.i = cd.i + cp->i;    p = strcat(cp->str, cd.str);    strcat(tt.str,p);    //i = strlen(tt.str);    //tt.str[i + 1] = {'\0'};    printf("tt.i %d\n", tt.i);    printf("tt.str %s\n", tt.str);    return 0;}
[解决办法]
C/C++ code
    cd.i = 10;    memcpy(cd.str, "abcd", strlen("abcd"));
[解决办法]
那就用free替代
C/C++ code
#include <stdio.h>#include <string.h>#include <malloc.h>   typedef struct card {    int i;    char str[100];}card;int main(void){    //int i;    char *p;    card *cp;    card cd = {10,{'a', 'b', 'c', 'd'}};    card tt = {0,{'\0'}};    cp = (card*)malloc(sizeof(card));    cp->i = 20;    strcpy(cp->str,"e");    tt.i = cd.i + cp->i;    p = strcat(cp->str, cd.str);    strcat(tt.str,p);    //i = strlen(tt.str);    //tt.str[i + 1] = {'\0'};    printf("tt.i %d\n", tt.i);    printf("tt.str %s\n", tt.str);    free(cp);    return 0;} 

读书人网 >C语言

热点推荐