1
我一直試圖將argv[x]
賦值給變量指向的結構。 我寫了下面的代碼,並得到分段錯誤,我知道這是內存違規。我不明白我犯了什麼錯誤。 下面是代碼:指向結構argv賦值的指針
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
typedef struct somestruct {
char name[20];
char surname[20];
char misc[4056];
} somestruct;
int
main(int argc, char *argv[])
{
somestruct *pvar;
pvar = malloc(sizeof(somestruct));
if (pvar==NULL)
printf("malloc failed with: %s\n", strerror(errno));
pvar = (somestruct *) memset(pvar, 0, sizeof(somestruct));
memcpy((char *) &(pvar->name), argv[1], 20);
memcpy((char *) &(pvar->surname), argv[2], 20);
memcpy((char *) &(pvar->misc), argv[3],4056);
return 0;
}
預先感謝您。
謝謝Grijesh。 – 2013-02-28 09:22:57
@DaniloMitrovic歡迎Danilo – 2013-02-28 09:26:00