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;
}

Try going at it like this...

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


int main()
{
  
	char line[50];
	int count = 0;
	char c;

	while((c = getchar() )!= '\n')
	{
		line[count++] = c;
	}

	line[count] = '\0';
	printf("you entered: %s\n",line);

	char *p = line;
	char *start = line;/*save the start of a word*/
	char *mya[100];
	int argCount = 0;

	while(*p)
	{ 
		if(*p == ' ')
		{
			*p = '\0';
			mya[argCount] = start;
			argCount++;
			start = p + 1;/*next starting position*/
		}
		p++;
	}

	mya[argCount] = start;/*assign last one*/

	fprintf(stdout, "%s\n", mya[0]);
	fprintf(stdout, "%s\n", mya[1]);
	fprintf(stdout, "%s\n", mya[2]);
	fprintf(stdout, "%s\n", mya[3]);
	return 0;
}

Edited 5 Years Ago by gerard4143: n/a

This is C. The Standard does not allow you to define variables after executable statements as you do in lines 22-25. The definitiosn must be above the while() statement.

This article has been dead for over six months. Start a new discussion instead.