Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C programming pointer char array

The following C program will print the shortest and longest string as t[0] and t[n-1]. However, when I run this code, it says there is a memory problem. What is wrong with my code?

The problem is the last two lines, with "strcpy".

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

void fx (char* t[], int n);

int main(void)
{
    char* t[] = {"horse", "elephant", "cat", "rabbit"};
    int n;
    n = sizeof( t )/ sizeof( t[0] );
    fx(t, n);
    printf("shortest is %s, longest is %s\n", t[0], t[n-1]);
}

void fx (char* t[], int n)
{
    char st[50], lt[50];
    strcpy(lt,t[0]);
    strcpy(st,t[0]);
    for (int i=0; i<n; i++)
    {
        if (strlen(t[i]) < strlen(st))
            strcpy(st,t[i]);
        if (strlen(t[i]) > strlen(lt))
            strcpy(lt,t[i]);
    }
    strcpy( t[0], st);
    strcpy( t[n-1], lt);
}
like image 716
user2863356 Avatar asked Mar 27 '26 16:03

user2863356


2 Answers

Both strcpy()s,

strcpy( t[0], st);
strcpy( t[n-1], lt);

are wrong! t[i] points to const string literals - not modifiable, which causes undefined behavior at runtime.

like image 108
Grijesh Chauhan Avatar answered Mar 29 '26 05:03

Grijesh Chauhan


char* t[] = {"horse", "elephant", "cat", "rabbit"};

declares an array of pointers to string literals. String literals may be placed in read-only memory and cannot be modified. The final strcpy lines in fx are trying to write to read-only memory.

like image 34
simonc Avatar answered Mar 29 '26 06:03

simonc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!