freinds
freinds

Reputation: 59

how to assign a char to array?

int compress(char str[]) {

  char tempStr [256];
  int i,j, counter=0;


     if (!isdigit(str[i]) && (!isspace(str[i]))) {
        tempStr[j] = str[i];  
        j++;
        printf("%c", tempStr[i]); 
     } else {
        counter++;
     }

     str = tempStr;
}

char str[] = "abc abc abc 123";
result = compress(&str);

Question:

  1. how to assign a str char to tempStr?
  2. how to replace str to tempStr in function compress? I think str = tempStr is wrong

thanks

Upvotes: 0

Views: 1340

Answers (4)

Mahesh
Mahesh

Reputation: 34615

 char tempStr [256];

tempStr is a character array that can hold 256 characters.

But what happens with this statement- str = tempStr; ?

When you say, tempStr, what you get is the pointer to the first element of the array (i.e., &tempStr[0] ). So, with the statement you aren't actually copying the elements of tempStr to str. The rvalue is of type char* but the lvalue is of type char [], which are incompatible and results compilation error.

To actually copy the elements of the array, you should use strcpy.

Upvotes: 0

AndersK
AndersK

Reputation: 36082

It seems you are a bit confused about strings, arrays and pointers.

char str[] = "abc abc abc 123"; means that somewhere in memory you have an array with those characters. when so declared, the 'str' is constant and cannot be set to point somewhere else.

instead you need assign each individual character which is sort of what you started to do in your function with the statement tempStr[j] = str[i]:

you need to loop through the characters in str and check each character, then assign the char to the tempStr which should be at least as large as the original str[] array.

something like

char *tempStr = calloc( strlen( str ) + 1, 1 ); // allocates a buffer +1 char for \0
for (int i = 0, j = 0; i < strlen( str ); ++i)
{
  if (!isdigit(str[i]) && (!isspace(str[i]))) 
  {
    tempStr[j++] = str[i];  
    printf("%c", str[i]); 
  } 
}

now you have removed some characters from str[] however you need now to move back the contents of tempStr to str, this can be done with a strcpy:

strcpy( str, tempStr );

then free the buffer

free( tempStr );

and Bob is your uncle.

Upvotes: 1

burningice
burningice

Reputation: 391

1.Your code miss tempStr defination, like char tempStr[LENGTH], make sure LENGTH is big enough. 2.C string should be terminated by '\0', so you need set tempStr[j] = '\0' after the loop (which is missing I think). Then you can use strcpy copy tempStr to str.

Upvotes: 1

littleadv
littleadv

Reputation: 20262

You should use memcpy or strcpy (if it's a null terminated string).

In the example, tempStr is not defined, so I'm guessing it's an array of chars. Although, you'll probably need a loop somewhere...

Upvotes: 0

Related Questions