所以我基本上希望我的程序能夠保存多個(或在這種情況下,只有兩個)參數到一個字符串,如果程序啓動選項-a 。這裏是代碼:'無效指針'錯誤與realloc和strcat工作argv
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
int main(int argc, char **argv) {
char c;
char *optstr;
int acount = 0;
while((c = getopt(argc, argv, "a")) != -1) {
switch(c) {
case 'a': acount++; break;
case '?': fprintf(stderr, "wrong opt\n"); exit(1); break;
default: assert(0);
}
}
char *temp;
if(acount == 1) {
optstr = argv[optind];
temp = strdup(optstr);
if(optind+1 < argc) {
temp = realloc(temp, (strlen(temp) + 1 + sizeof(" ")));
temp = strcat(temp, " ");
temp = realloc(temp, (strlen(temp) + 1 + strlen(argv[optind+1])));
temp = strcat(temp, argv[optind+1]);
}
} else {
fprintf(stderr, "too many or not enough a's\n");
exit(1);
}
fprintf(stdout, "%s\n", temp);
return 0;
}
我的問題在於整個realloc業務正在進行。我最初嘗試了沒有temp變量的整個事物,而是使用optstr代替。哪些只給了我「realloc():無效指針」錯誤。我在問 - 爲什麼會這樣,爲什麼它突然與臨時工作?這是因爲optstr的指針指向argv中的參數,並且更改argv會導致錯誤?我真的不確定。
當您使用'argv [optind]'時,它的價值是什麼? –
'sizeof(「」)'?你是不是指'strlen(「」)'?順便說一句,你還沒有釋放分配的內存。 –
在這種情況下有什麼關係?它工作得很好。是的,我知道我沒有釋放自己的記憶,但這只是一個例子。 – skulpt