Hello All,
I am not sure why my algorithm is not working for this problem. I need to store space separated arguments in an array char* argBuffer[], so I can later make some system calls . The problem is that the last argument is writes over all indexes of the array. I'm newer to C programming.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
int main(){
char line[50];
int count = 0;
char c;
//get user input stop when enter is pressed
while((c = getchar() )!= '\n'){
line[count] = c;
count++;
}
line[count] = '\0';
printf("you entered: %s\n",line);
char* p = &line[0];
char* argBuffer[100];
count = 0;
int argCount = 0;
char temp[10];
//parse commands by space character
while(*p){
if(*p == ' '){
argBuffer[argCount] = temp;
argCount++;
int i = 0;
count = 0;
for (i; i < count; i++){ temp[i] = '\0';}
} else {
//build temp
char c = *p;
temp[count] = c;
temp[count + 1] = '\0';
count++;
}
*p++;
}
// no space at end of input so must add last argument
argBuffer[argCount] = temp;
printf("argCount = %d\n",argCount);
// for input ex ls -l
printf("argBuffer[%d] = %s)\n",0,argBuffer[0]);
printf("argBuffer[%d] = %s)\n",1,argBuffer[1]);
// why does the last argument overwrite the indexes in argBuffer?
return 0;
}