July 27th, 2013, 05:30 PM
Short question about swapping strings in C.
When i define a double array e.g array, and i use the function swap like this: swap(&array, &array).
Would this be error prone? because i know i could choose to define the following: "char* array" so the array would be an ARRAY OF POINTERS rather than an array of arrays. Is this something that might cause a problem?
Because i don't see a big difference(?).
July 28th, 2013, 01:03 AM
The only difference is the amount of work you need to do.
With char array, you would
- copy up to 10 bytes from array[x] into a temp variable
- copy array[y] into array[x]
- copy temp into array[x]
If you use strcpy, then the obvious problem is how do you allocate the temp array?
If you instead use a loop and just sway 1 char at a time (temp = array[x][i] ..), you would ideally like to bail out as soon as you'd copied the \0 from both strings, otherwise there would be a penalty for dealing with short strings.
With char *array, everything is so much simpler
char *temp = array[x];
array[x] = array[y];
array[y] = temp;
July 28th, 2013, 04:12 AM
And if it's not an array of pointers, but a usual 2-d array, why can't he still swap the addresses?
Because when i try swapping: "&new_words[j]" and "&new_words[j+1]" inside a loop, while calling to the function swap, the compiler gives the message:
INCOMPATIBLE POINTER TYPE
Aren't they still addresses, just like pointers? :chomp:
July 28th, 2013, 04:19 AM
> Aren't they still addresses, just like pointers?
No, an array of pointers (char *array), and an array of arrays (char array) are different animals.
The fact that you can do array[r][c] to access a specific char in both cases doesn't make them completely interchangeable.
More on arrays and pointers
Here's something else for you to try as well, printing out the results of
for both styles of array.
July 28th, 2013, 04:40 AM
I think i'm catching on.
The sizeof were different as i thought when i printed them.
Thanks, very informative.
Comments on this post