2015-12-05 93 views
1

这段代码运行时出现了段错误,但编译没有问题。哪里不对?指针结构的问题

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

typedef struct { 
    char *fld[129]; 
} isomsg; 

void iso8583_init(isomsg *m) 
{ 
    int i; 

    for (i = 0; i <= 128; i++) { 
     m->fld[i] = NULL; 
    } 
} 


isomsg m; 

int main(int argc, char *argv[]) { 

    iso8583_init(&m); 

    strcpy(m.fld[0],"Fisrt"); 

    printf("First = %s\n",m.fld[0]); 

    system("PAUSE"); 
    return 0; 
} 

回答

2

有问题的行是:

strcpy(m.fld[0],"Fisrt"); 

m.fld[0]是初始化为NULL指针。如果地址指向NULL,则不能写入地址。这是undefined behaviour

你可能想:

m.fld[0] = "Fisrt"; 

这将字符串字面指针m.fld[0]的地址。

或者,如果你想使字符串拷贝文字"First"那么你可以使用strdup()(POSIX):

m.fld[0] = strdup("Fisrt"); 

或者使用malloc() + strcpy()(标准C):

m.fld[0] = malloc(sizeof("First")); //allocate memory of 6 bytes 
strcpy(m.fld[0], "First"); 

(您应该检查strdup/malloc()是否因为失败而返回NULL。)

+0

非常感谢;这解决了我的问题 – user5240895

+0

如果我使用:memcpy(&m.fld [0],“First”,5); – user5240895

+0

@ user5240895 memcpy()是另一种复制方式。但是在任何情况下,您都需要将指针指向有效的内存位置,即您仍然需要对传递给memcpy()的指针执行malloc()。 –