我試圖在這個程序中將M和N的值設置爲任何從C程序在命令行上接收的字符串解析的值。但是,每當我運行代碼時,我都會遇到分段錯誤。我對C中的指針概念很陌生,所以我知道它就在那裏。爲什麼在這個程序中出現分段錯誤?
的代碼應該工作如下:
./a.out -1,12
打印:
1,12
感謝您的幫助!
#include <stdio.h>
#include <stdlib.h>
void getnumber(char *toTest, int *a, int *c);
int main (int argc, char *argv[])
{
int a, c, curr;
a = 1;
c = 1;
curr = 1;
if (argv[1][0] == '-')
{
curr = 2;
getMandNValues(argv[1], &a, &c);
}
printf("%d, %d\n", a, c);
return 0;
}
void getMandNValues(char *src, int *a, int *c)
{
char aString[sizeof src];
char bString[sizeof src];
int i = 0;
while((aString[i] = &src[i+1]) != ',')
++i;
aString[i] = '\0';
int j = 0;
while((bString[j] = &src[i + 2]) != '\0')
{
++j;
++i;
}
bString[j] = '\0';
*a = atoi(aString);
*c = atoi(bString);
}
編譯器的輸出是:
/tmp/foo.c: In function ‘main’:
/tmp/foo.c:18: warning: passing argument 2 of ‘getMandNValues’ makes pointer from integer without a cast
/tmp/foo.c:18: warning: passing argument 3 of ‘getMandNValues’ makes pointer from integer without a cast
/tmp/foo.c: In function ‘getMandNValues’:
/tmp/foo.c:34: warning: assignment makes integer from pointer without a cast
/tmp/foo.c:41: warning: assignment makes integer from pointer without a cast
我真的很希望你沒有實際縮進(或者更確切地說n ot)你所有的代碼... – 2010-11-06 16:03:53
有人應該對aString和bString的長度留言。 – 2010-11-06 16:10:26
aString和bString的大小在您的代碼中將始終爲4。它們不會是src字符串中傳遞的長度。 – 2010-11-06 16:13:59