why doesnt this work?

This is a discussion on why doesnt this work? within the C Programming forums, part of the General Programming Boards category; hi, I have these two functions that declare and alter char* arrays - why dosent it work...? ( i know ...

  1. #1
    Registered User
    Join Date
    Jan 2009

    why doesnt this work?


    I have these two functions that declare and alter char* arrays - why dosent it work...? ( i know it dosent i just need some explaning done )

    #include <stdio.h>
    void addchars(char *sa[]){
    char *name[10];
    name[0] = "foo";
    sprintf(sa, "%s", name[0]);
    int main() {
    char *sa[128];
    printf("numbers: %s\n", sa[0]);
    printf("numbers: %s\n", sa[0]);

  2. #2
    Registered User
    Join Date
    Apr 2008
    first thing: enable warnings before compiling, this line is wrong:
    sprintf(sa, "%s", name[0]);
    and your compiler would have told you if you asked.

    second thing, sa is just an array of pointers, there is no memory allocated for the strings, so sprintf() won't work (segv), replace sprintf() with sa[0]="foo" and you get what you want.

  3. #3
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    You must understand that string literals are really constant: http://cpwiki.sourceforge.net/Common...kes_and_errors
    So when you try to use sprintf, you write into memory where you are not allowed, hence you would get a crash.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.
    For information on how to enable C++11 on your compiler, look here.
    よく聞くがいい!私は天才だからね! ^_^

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. strcmp returning 1...
    By Axel in forum C Programming
    Replies: 12
    Last Post: 09-08-2006, 07:48 PM
  2. getline() don't want to work anymore...
    By mikahell in forum C++ Programming
    Replies: 7
    Last Post: 07-31-2006, 10:50 AM
  3. Why don't the tutorials on this site work on my computer?
    By jsrig88 in forum C++ Programming
    Replies: 3
    Last Post: 05-15-2006, 10:39 PM
  4. fopen();
    By GanglyLamb in forum C Programming
    Replies: 8
    Last Post: 11-03-2002, 11:39 AM
  5. DLL __cdecl doesnt seem to work?
    By Xei in forum C++ Programming
    Replies: 6
    Last Post: 08-21-2002, 04:36 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21